Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions app/jobs/capture_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class CaptureJob < ApplicationJob
def perform(capture)
return if capture.finished?

capture.update!(status: "running", started_at: Time.current, error: nil)
capture.update!(status: "running", started_at: Time.current, error: nil, error_code: nil)
Dir.mktmpdir("stash-#{capture.method_name}-") do |workdir|
outputs = capture.capturer.new(capture, workdir).call
store(capture, outputs)
Expand All @@ -21,9 +21,9 @@ def perform(capture)
rescue Capturers::Skip => e
finish(capture, "skipped", error: e.message)
rescue Capturers::Error => e
finish(capture, "failed", error: "#{e.class.name.demodulize}: #{e.message}")
finish(capture, "failed", error: "#{e.class.name.demodulize}: #{e.message}", error_code: e.code)
rescue StandardError => e
finish(capture, "failed", error: "#{e.class}: #{e.message.to_s.first(500)}")
finish(capture, "failed", error: "#{e.class}: #{e.message.to_s.first(500)}", error_code: "unexpected")
raise
end

Expand All @@ -41,8 +41,11 @@ def store(capture, outputs)
end
end

def finish(capture, status, error: nil)
capture.update!(status: status, error: error, finished_at: Time.current)
def finish(capture, status, error: nil, error_code: nil)
# An error class that is not in CODES (a bare Capturers::Error, a new subclass) must not
# leave the capture running on a validation error.
error_code = "unexpected" if error_code && Capturers::CODES.exclude?(error_code)
capture.update!(status: status, error: error, error_code: error_code, finished_at: Time.current)
capture.archive.refresh_status!
end
end
12 changes: 12 additions & 0 deletions app/models/archive.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ def finished?
%w[done partial failed].include?(status)
end

# What stopped the archive, when something did: the failed capture whose error code matters
# most to the person who submitted the URL (Capturers::CODES order), as a hash with the code,
# the method, the message and a hint for a person. Nil while nothing has failed.
def problem
failed = captures.select { |c| c.status == "failed" }
return nil if failed.empty?

capture = failed.min_by { |c| [ Capturers::CODES.index(c.error_code) || Capturers::CODES.size, c.position ] }
code = capture.error_code || "tool_failed"
{ code: code, method: capture.method_name, message: capture.error, hint: Capturers.hint(code) }
end

def title
"#{host} · #{kind}"
end
Expand Down
5 changes: 4 additions & 1 deletion app/models/capture.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
# queued waiting for a worker
# running the capturer is running
# done the capturer stored its artifacts
# failed the capturer raised, timed out or passed the size limit; `error` says which
# failed the capturer raised, timed out or passed the size limit; `error` says which, and
# `error_code` is the reason in one word (Capturers::CODES: not_public, not_found,
# blocked, too_large, timeout, tool_failed, unexpected)
# skipped the method does not apply after all (for example, HEAD said the URL is HTML, so no file)
#
# A capture is never deleted when it fails, so the archive shows what was tried.
Expand All @@ -22,6 +24,7 @@ class Capture < CentralRecord
validates :method_name, inclusion: { in: METHODS }, uniqueness: { scope: :archive_id }
validates :status, inclusion: { in: STATUSES }
validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :error_code, inclusion: { in: Capturers::CODES }, allow_nil: true

scope :unfinished, -> { where(status: %w[queued running]) }

Expand Down
2 changes: 2 additions & 0 deletions app/serializers/archive_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def as_json(*)
created_at: a.created_at&.iso8601,
completed_at: a.completed_at&.iso8601,
page_url: archive_url(a, host: default_host),
problem: a.problem,
captures: a.captures.map { |c| capture_json(c) }
}
end
Expand All @@ -33,6 +34,7 @@ def capture_json(capture)
method: capture.method_name,
status: capture.status,
error: capture.error,
error_code: capture.error_code,
started_at: capture.started_at&.iso8601,
finished_at: capture.finished_at&.iso8601,
artifacts: capture.artifacts.map { |artifact| artifact_json(artifact) }
Expand Down
62 changes: 60 additions & 2 deletions app/services/capturers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,73 @@
# argument (never a shell string), a timeout and an output cap. A capturer never runs code from
# the archived content.
module Capturers
class Error < StandardError; end
# A capture that cannot finish raises one of these. The class is the reason, in a form a
# patch app can act on: `code` goes into `captures.error_code` and into the API, the message
# into `captures.error`. Capturers.hint(code) is the sentence for the person who can fix it.
class Error < StandardError
# The HTTP status that caused it, when one did.
attr_accessor :http_status
# The output of the tool that failed, when one did (Base#run!).
attr_accessor :tool_output

def self.code
name.demodulize.underscore
end

def code
self.class.code
end
end

# The method does not apply to this URL after all. The capture becomes `skipped`.
class Skip < Error; end
# The tool ran past CAPTURE_TIMEOUT.
class Timeout < Error; end
# The output passed CAPTURE_MAX_BYTES.
class TooLarge < Error; end
# The tool exited with an error.
# The tool exited with an error, and nothing more specific is known.
class ToolFailed < Error; end
# The source needs a sign-in or a share: a private repository, a Google document that is not
# shared with anyone with the link, a private video. The owner can fix it.
class NotPublic < Error; end
# Nothing is at the URL: 404 or 410, a deleted video, a repository that is gone.
class NotFound < Error; end
# The host refused the archiver: 403, 429, an anti-bot wall. Later may work.
class Blocked < Error; end

# The error codes a capture can carry, in the order that matters most to the person who
# submitted the URL. Archive#problem picks the first one present.
CODES = %w[not_public not_found blocked too_large timeout tool_failed unexpected].freeze

HINTS = {
"not_public" => "The source is private. Ask the owner to share it with anyone with the link, or to send a public URL, then run the archive again.",
"not_found" => "Nothing is at that URL. Ask for the right link, then run the archive again.",
"blocked" => "The site refused the archiver. Run the archive again later.",
"too_large" => "The file is larger than the size limit.",
"timeout" => "The capture ran out of time. Run the archive again.",
"tool_failed" => "The capture tool failed. Run the archive again. If it fails the same way, it is a Stash problem.",
"unexpected" => "Stash hit an unexpected error. Run the archive again. If it fails the same way, it is a Stash problem."
}.freeze

# One sentence for a person, for a code. Unknown codes get the generic one.
def self.hint(code)
HINTS.fetch(code.to_s, HINTS["tool_failed"])
end

# Builds the error for an HTTP status: 401 needs a sign-in, 403 and 429 are a refusal, 404 and
# 410 mean gone, anything else is a plain failure.
def self.http_error(status, message)
klass =
case status.to_i
when 401 then NotPublic
when 403, 429 then Blocked
when 404, 410 then NotFound
else ToolFailed
end
error = klass.new(message)
error.http_status = status.to_i
error
end

# One file for CaptureJob to store. `path` is inside the work directory.
Output = Data.define(:role, :path, :filename, :content_type)
Expand Down
24 changes: 23 additions & 1 deletion app/services/capturers/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,33 @@ def log(line)
def run!(*command, env: {}, timeout: Capturers.timeout)
log("$ #{command.map { |part| part.to_s.include?(" ") ? part.to_s.inspect : part }.join(" ")}")
result = Subprocess.run(*command, chdir: workdir, timeout: timeout, env: env) { |line| log(line) }
raise ToolFailed, "#{command.first} exited with status #{result.status.exitstatus}" unless result.success?
unless result.success?
error = ToolFailed.new("#{command.first} exited with status #{result.status.exitstatus}")
error.tool_output = result.output
raise error
end

result
end

# Runs the block, and when a tool fails, reads the tool's own output (never the command
# line or the URL) for the reason: a sign-in or a share that is missing (NotPublic) or a
# source that is gone (NotFound). Any other failure stays a ToolFailed. `tool` names the
# tool in the message.
def classify_tool_failure(tool, not_public:, not_found:)
yield
rescue ToolFailed => e
output = e.tool_output.to_s.last(4.kilobytes)
if not_public.any? { |pattern| output.match?(pattern) }
raise NotPublic, "#{tool}: the source is private or needs a sign-in. " \
"Ask the owner to make it public, then run the archive again. (#{e.message})"
elsif not_found.any? { |pattern| output.match?(pattern) }
raise NotFound, "#{tool}: the source is gone or the URL is wrong. (#{e.message})"
end

raise
end

def path(name)
::File.join(workdir, name)
end
Expand Down
38 changes: 36 additions & 2 deletions app/services/capturers/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,52 @@ def call

private

GOOGLE_NAMES = { "document" => "Google Doc", "presentation" => "Google Slides deck",
"spreadsheets" => "Google Sheet", "drawings" => "Google Drawing" }.freeze

def google(kind, id)
export = GOOGLE_EXPORTS.fetch(kind)
native = Download.fetch(google_export_url(kind, id, export[:native]), to: path("document.#{export[:native]}"))
native = google_export(kind, id, export[:native], export[:type])
log("Google export: #{native.byte_size} bytes as #{export[:native]}")
pdf = Download.fetch(google_export_url(kind, id, "pdf"), to: path("document.pdf"))
pdf = google_export(kind, id, "pdf", "application/pdf")
log("Google export: #{pdf.byte_size} bytes as pdf")
[
output("original", "document.#{export[:native]}", content_type: export[:type], filename: "#{id}.#{export[:native]}"),
output("rendition", "document.pdf", content_type: "application/pdf", filename: "#{id}.pdf")
]
end

# One Google export. A document that is not shared with anyone with the link answers 404,
# or 401, or a 302 to the Google sign-in page (a 200 of HTML on another host), the same as
# one that does not exist. Every one of those is NotPublic: the owner has to act. A 429
# stays Blocked: Google is rate limiting, and later works.
def google_export(kind, id, format, expected_type)
fetched =
begin
Download.fetch(google_export_url(kind, id, format), to: path("document.#{format}"))
rescue NotFound, NotPublic => e
raise not_shared(kind, e.http_status)
rescue Blocked => e
raise not_shared(kind, e.http_status) if e.http_status == 403

raise
end
served = fetched.content_type.to_s
if fetched.uri.host != "docs.google.com" || Router::HTML_TYPES.include?(served) || !served.start_with?(expected_type)
log("Google export answered #{served} from #{fetched.uri.host}, not the #{format}")
raise not_shared(kind, "a sign-in page")
end
fetched
end

def not_shared(kind, answer)
error = NotPublic.new("Google answered #{answer} for the #{GOOGLE_NAMES.fetch(kind)}: " \
"it is not shared with anyone with the link, or it does not exist. " \
"Ask the owner to share it, then run the archive again.")
error.http_status = answer if answer.is_a?(Integer)
error
end

def google_export_url(kind, id, format)
case kind
when "presentation", "drawings" then "https://docs.google.com/#{kind}/d/#{id}/export/#{format}"
Expand Down
7 changes: 4 additions & 3 deletions app/services/capturers/download.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ module Download

Fetched = Data.define(:uri, :content_type, :filename, :path, :byte_size)

# Downloads the URL into `to`. Returns a Fetched. Raises TooLarge past the cap, ToolFailed on an
# HTTP error.
# Downloads the URL into `to`. Returns a Fetched. Raises TooLarge past the cap, and on an HTTP
# error the class for its status (Capturers.http_error): NotPublic, Blocked, NotFound or
# ToolFailed.
def self.fetch(url, to:, max_bytes: Capturers.max_bytes)
uri = URI.parse(url)
MAX_REDIRECTS.times do
Expand Down Expand Up @@ -42,7 +43,7 @@ def self.fetch(url, to:, max_bytes: Capturers.max_bytes)
result = Fetched.new(uri: uri, content_type: content_type_of(response), filename: filename_of(response, uri),
path: to, byte_size: size)
else
raise ToolFailed, "GET #{uri.host} answered #{response.code}"
raise Capturers.http_error(response.code, "GET #{uri.host} answered #{response.code}")
end
end
end
Expand Down
6 changes: 5 additions & 1 deletion app/services/capturers/gallery.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ def call
command += [ "--cookies", ENV["YTDLP_COOKIES_FILE"] ] if ENV["YTDLP_COOKIES_FILE"].present?
command += [ "--proxy", ENV["YTDLP_PROXY"] ] if ENV["YTDLP_PROXY"].present?
command << "--" << url
run!(*command, env: { "HOME" => workdir })
classify_tool_failure("gallery-dl",
not_public: [ /login required/i, /AuthenticationError/i, /AuthorizationError/i, /account is private/i, /private account/i ],
not_found: [ /NotFoundError/i, /HttpError.*404/i, /HttpError.*410/i ]) do
run!(*command, env: { "HOME" => workdir })
end

files = Dir.glob(path("post/**/*")).select { |f| ::File.file?(f) }.sort
raise ToolFailed, "gallery-dl downloaded nothing" if files.empty?
Expand Down
6 changes: 5 additions & 1 deletion app/services/capturers/git.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ class Git < Base
def call
clone_url = clone_url_for(url)
log("git: cloning #{clone_url}")
run!("git", "clone", "--mirror", "--quiet", clone_url, "repo.git")
classify_tool_failure("git clone",
not_public: [ /Authentication failed/i, /could not read Username/i, /Permission denied/i, /authentication required/i ],
not_found: [ /Repository not found/i, /not found/i, /does not exist/i ]) do
run!("git", "clone", "--mirror", "--quiet", clone_url, "repo.git")
end
run!("git", "-C", "repo.git", "bundle", "create", "../repo.bundle", "--all")
refs = run!("git", "-C", "repo.git", "for-each-ref", "--format=%(objectname) %(refname)").output
head = run!("git", "-C", "repo.git", "symbolic-ref", "HEAD").output.strip
Expand Down
14 changes: 12 additions & 2 deletions app/services/capturers/github.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,22 @@ def get(route, raw: false, allow_missing: false, allow_empty: false)
when Net::HTTPSuccess then raw ? response.body : JSON.parse(response.body)
when Net::HTTPNotFound
return nil if allow_missing
raise ToolFailed, "GitHub answered 404 for #{uri.path}: the repository is private or gone"
# GitHub answers 404 for a private repository too, so the owner is the one to ask.
error = NotPublic.new("GitHub answered 404 for #{uri.path}: the repository is private or gone. " \
"Ask the owner to make it public, then run the archive again.")
error.http_status = 404
raise error
when Net::HTTPNoContent, Net::HTTPAccepted
return [] if allow_empty
raise ToolFailed, "GitHub answered #{response.code} for #{uri.path}"
when Net::HTTPUnauthorized
# Public repositories need no token, so a 401 means GITHUB_TOKEN is bad, not the source.
raise ToolFailed, "GitHub rejected GITHUB_TOKEN (401). Fix the token in the env file, then run the archive again."
when Net::HTTPForbidden, Net::HTTPTooManyRequests
raise Capturers.http_error(response.code, "GitHub answered #{response.code} for #{uri.path}: " \
"the API rate limit, or an abuse block. Run the archive again later.")
else
raise ToolFailed, "GitHub answered #{response.code} for #{uri.path}"
raise Capturers.http_error(response.code, "GitHub answered #{response.code} for #{uri.path}")
end
rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError => e
raise ToolFailed, "could not reach GitHub: #{e.class}"
Expand Down
14 changes: 12 additions & 2 deletions app/services/capturers/video.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,20 @@ def call
command += [ "--cookies", ENV["YTDLP_COOKIES_FILE"] ] if ENV["YTDLP_COOKIES_FILE"].present?
command += [ "--proxy", ENV["YTDLP_PROXY"] ] if ENV["YTDLP_PROXY"].present?
command << "--" << url
run!(*command, env: { "HOME" => workdir })
classify_tool_failure("yt-dlp",
not_public: [ /Private video/i, /This video is private/i, /Sign in to confirm/i, /members-only/i,
/login required/i, /requires authentication/i, /not available to you/i ],
not_found: [ /Video unavailable/i, /has been removed/i, /does not exist/i, /HTTP Error 404/i ]) do
run!(*command, env: { "HOME" => workdir })
end

media = Dir.glob(path("video.*")).reject { |f| f.end_with?(".info.json", ".png") }.first
raise ToolFailed, "yt-dlp wrote no media file" unless media
unless media
# yt-dlp exits 0 and writes nothing when --max-filesize stops the download.
raise TooLarge, "yt-dlp: the video is larger than the limit of #{Capturers.max_bytes} bytes" if capture.log.to_s.match?(/larger than max-filesize/i)

raise ToolFailed, "yt-dlp wrote no media file"
end

outputs = [ output("original", ::File.basename(media), content_type: Marcel::MimeType.for(Pathname.new(media))) ]
outputs << output("metadata", "video.info.json", content_type: "application/json") if ::File.exist?(path("video.info.json"))
Expand Down
18 changes: 18 additions & 0 deletions app/views/archives/show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@
</div>
</header>

<% if (problem = @archive.problem) %>
<div class="callout callout-danger" role="status">
<%= icon(:triangle_alert, size: 18) %>

<div class="callout-body">
<p class="callout-title"><%= problem[:hint] %></p>

<p class="break-words">
<%= badge problem[:code].tr("_", " "), tone: :danger %> <%= problem[:method] %>: <%= problem[:message] %>
</p>
</div>
</div>
<% end %>

<% unless @archive.finished? %>
<div class="callout callout-info" role="status">
<%= icon(:loader_circle, size: 18, class: "spinner") %>
Expand All @@ -72,6 +86,10 @@
<h2 class="card-title"><%= capture.method_name %></h2>
<%= status_badge(capture.status) %>

<% if capture.error_code.present? %>
<%= badge capture.error_code.tr("_", " "), tone: :outline %>
<% end %>

<% if capture.duration %>
<span class="text-xs text-ink-faint"><%= capture.duration.round(1) %> s</span>
<% end %>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# The machine-readable reason of a failed capture (Capturers::CODES), next to the message in
# `error`. Patch apps read it from the API to tell the submitter what to fix.
class AddErrorCodeToCaptures < ActiveRecord::Migration[8.1]
def change
add_column :captures, :error_code, :string
end
end
Loading
Loading