Fix misc rubocop warnings.

This commit is contained in:
evazion
2020-06-16 21:36:15 -05:00
parent dc460aab53
commit b551e3634f
25 changed files with 75 additions and 95 deletions

View File

@@ -57,7 +57,7 @@ class APNGInspector
# if we did, file is probably maliciously formed # if we did, file is probably maliciously formed
# fail gracefully without marking the file as corrupt # fail gracefully without marking the file as corrupt
chunks += 1 chunks += 1
if chunks > 100000 if chunks > 100_000
iend_reached = true iend_reached = true
break break
end end
@@ -66,7 +66,8 @@ class APNGInspector
file.seek(current_pos + chunk_len + 4, IO::SEEK_SET) file.seek(current_pos + chunk_len + 4, IO::SEEK_SET)
end end
end end
return iend_reached
iend_reached
end end
def inspect! def inspect!
@@ -105,6 +106,7 @@ class APNGInspector
if framedata.nil? || framedata.length != 4 if framedata.nil? || framedata.length != 4
return -1 return -1
end end
return framedata.unpack1("N".freeze)
framedata.unpack1("N".freeze)
end end
end end

View File

@@ -6,7 +6,7 @@ module ArtistFinder
SITE_BLACKLIST = [ SITE_BLACKLIST = [
"artstation.com/artist", # http://www.artstation.com/artist/serafleur/ "artstation.com/artist", # http://www.artstation.com/artist/serafleur/
"www.artstation.com", # http://www.artstation.com/serafleur/ "www.artstation.com", # http://www.artstation.com/serafleur/
%r!cdn[ab]?\.artstation\.com/p/assets/images/images!i, # https://cdna.artstation.com/p/assets/images/images/001/658/068/large/yang-waterkuma-b402.jpg?1450269769 %r{cdn[ab]?\.artstation\.com/p/assets/images/images}i, # https://cdna.artstation.com/p/assets/images/images/001/658/068/large/yang-waterkuma-b402.jpg?1450269769
"ask.fm", # http://ask.fm/mikuroko_396 "ask.fm", # http://ask.fm/mikuroko_396
"bcyimg.com", "bcyimg.com",
"bcyimg.com/drawer", # https://img9.bcyimg.com/drawer/32360/post/178vu/46229ec06e8111e79558c1b725ebc9e6.jpg "bcyimg.com/drawer", # https://img9.bcyimg.com/drawer/32360/post/178vu/46229ec06e8111e79558c1b725ebc9e6.jpg
@@ -52,7 +52,7 @@ module ArtistFinder
"hentai-foundry.com", "hentai-foundry.com",
"hentai-foundry.com/pictures/user", # http://www.hentai-foundry.com/pictures/user/aaaninja/ "hentai-foundry.com/pictures/user", # http://www.hentai-foundry.com/pictures/user/aaaninja/
"hentai-foundry.com/user", # http://www.hentai-foundry.com/user/aaaninja/profile "hentai-foundry.com/user", # http://www.hentai-foundry.com/user/aaaninja/profile
%r!pictures\.hentai-foundry\.com(?:/\w)?!i, # http://pictures.hentai-foundry.com/a/aaaninja/ %r{pictures\.hentai-foundry\.com(?:/\w)?}i, # http://pictures.hentai-foundry.com/a/aaaninja/
"i.imgur.com", # http://i.imgur.com/Ic9q3.jpg "i.imgur.com", # http://i.imgur.com/Ic9q3.jpg
"instagram.com", # http://www.instagram.com/serafleur.art/ "instagram.com", # http://www.instagram.com/serafleur.art/
"iwara.tv", "iwara.tv",
@@ -68,7 +68,7 @@ module ArtistFinder
"nicovideo.jp/user", # http://www.nicovideo.jp/user/317609 "nicovideo.jp/user", # http://www.nicovideo.jp/user/317609
"nicovideo.jp/user/illust", # http://seiga.nicovideo.jp/user/illust/29075429 "nicovideo.jp/user/illust", # http://seiga.nicovideo.jp/user/illust/29075429
"nijie.info", # http://nijie.info/members.php?id=15235 "nijie.info", # http://nijie.info/members.php?id=15235
%r!nijie\.info/nijie_picture!i, # http://pic03.nijie.info/nijie_picture/32243_20150609224803_0.png %r{nijie\.info/nijie_picture}i, # http://pic03.nijie.info/nijie_picture/32243_20150609224803_0.png
"patreon.com", # http://patreon.com/serafleur "patreon.com", # http://patreon.com/serafleur
"pawoo.net", # https://pawoo.net/@148nasuka "pawoo.net", # https://pawoo.net/@148nasuka
"pawoo.net/web/accounts", # https://pawoo.net/web/accounts/228341 "pawoo.net/web/accounts", # https://pawoo.net/web/accounts/228341
@@ -120,7 +120,7 @@ module ArtistFinder
SITE_BLACKLIST_REGEXP = Regexp.union(SITE_BLACKLIST.map do |domain| SITE_BLACKLIST_REGEXP = Regexp.union(SITE_BLACKLIST.map do |domain|
domain = Regexp.escape(domain) if domain.is_a?(String) domain = Regexp.escape(domain) if domain.is_a?(String)
%r!\Ahttps?://(?:[a-zA-Z0-9_-]+\.)*#{domain}/\z!i %r{\Ahttps?://(?:[a-zA-Z0-9_-]+\.)*#{domain}/\z}i
end) end)
def find_artists(url) def find_artists(url)
@@ -128,7 +128,7 @@ module ArtistFinder
artists = [] artists = []
while artists.empty? && url.size > 10 while artists.empty? && url.size > 10
u = url.sub(/\/+$/, "") + "/" u = url.sub(%r{/+$}, "") + "/"
u = u.to_escaped_for_sql_like.gsub(/\*/, '%') + '%' u = u.to_escaped_for_sql_like.gsub(/\*/, '%') + '%'
artists += Artist.joins(:urls).where(["artists.is_deleted = FALSE AND artist_urls.normalized_url LIKE ? ESCAPE E'\\\\'", u]).limit(10).order("artists.name").all artists += Artist.joins(:urls).where(["artists.is_deleted = FALSE AND artist_urls.normalized_url LIKE ? ESCAPE E'\\\\'", u]).limit(10).order("artists.name").all
url = File.dirname(url) + "/" url = File.dirname(url) + "/"

View File

@@ -148,8 +148,6 @@ class BulkUpdateRequestProcessor
end.join("\n") end.join("\n")
end end
private
def self.is_tag_move_allowed?(antecedent_name, consequent_name) def self.is_tag_move_allowed?(antecedent_name, consequent_name)
antecedent_tag = Tag.find_by_name(Tag.normalize_name(antecedent_name)) antecedent_tag = Tag.find_by_name(Tag.normalize_name(antecedent_name))
consequent_tag = Tag.find_by_name(Tag.normalize_name(consequent_name)) consequent_tag = Tag.find_by_name(Tag.normalize_name(consequent_name))

View File

@@ -16,7 +16,7 @@ module HasBitFlags
end end
define_method("#{attribute}=") do |val| define_method("#{attribute}=") do |val|
if val.to_s =~ /t|1|y/ if val.to_s =~ /[t1y]/
send("#{field}=", send(field) | bit_flag) send("#{field}=", send(field) | bit_flag)
else else
send("#{field}=", send(field) & ~bit_flag) send("#{field}=", send(field) & ~bit_flag)

View File

@@ -11,8 +11,6 @@ module Mentionable
# - user_field # - user_field
def mentionable(options = {}) def mentionable(options = {})
@mentionable_options = options @mentionable_options = options
message_field = mentionable_option(:message_field)
after_save :queue_mention_messages after_save :queue_mention_messages
end end

View File

@@ -89,7 +89,7 @@ module Searchable
def where_array_count(attr, value) def where_array_count(attr, value)
qualified_column = "cardinality(#{qualified_column_for(attr)})" qualified_column = "cardinality(#{qualified_column_for(attr)})"
range = PostQueryBuilder.new(nil).parse_range(value, :integer) range = PostQueryBuilder.new(nil).parse_range(value, :integer)
where_operator("cardinality(#{qualified_column_for(attr)})", *range) where_operator(qualified_column, *range)
end end
def search_boolean_attribute(attribute, params) def search_boolean_attribute(attribute, params)
@@ -170,7 +170,7 @@ module Searchable
end end
end end
def search_text_attribute(attr, params, **options) def search_text_attribute(attr, params)
if params[attr].present? if params[attr].present?
where(attr => params[attr]) where(attr => params[attr])
elsif params[:"#{attr}_eq"].present? elsif params[:"#{attr}_eq"].present?
@@ -279,7 +279,8 @@ module Searchable
return find_ordered(parse_ids[1]) return find_ordered(parse_ids[1])
end end
end end
return default_order
default_order
end end
def default_order def default_order

View File

@@ -11,7 +11,7 @@ class DText
html = DTextRagel.parse(text, **options) html = DTextRagel.parse(text, **options)
html = postprocess(html, *data) html = postprocess(html, *data)
html html
rescue DTextRagel::Error => e rescue DTextRagel::Error
"" ""
end end
@@ -135,7 +135,7 @@ class DText
fragment = Nokogiri::HTML.fragment(html) fragment = Nokogiri::HTML.fragment(html)
titles = fragment.css("a.dtext-wiki-link").map do |node| titles = fragment.css("a.dtext-wiki-link").map do |node|
title = node["href"][%r!\A/wiki_pages/(.*)\z!i, 1] title = node["href"][%r{\A/wiki_pages/(.*)\z}i, 1]
title = CGI.unescape(title) title = CGI.unescape(title)
title = WikiPage.normalize_title(title) title = WikiPage.normalize_title(title)
title title
@@ -163,7 +163,7 @@ class DText
string = string.dup string = string.dup
string.gsub!(/\s*\[#{tag}\](?!\])\s*/mi, "\n\n[#{tag}]\n\n") string.gsub!(/\s*\[#{tag}\](?!\])\s*/mi, "\n\n[#{tag}]\n\n")
string.gsub!(/\s*\[\/#{tag}\]\s*/mi, "\n\n[/#{tag}]\n\n") string.gsub!(%r{\s*\[/#{tag}\]\s*}mi, "\n\n[/#{tag}]\n\n")
string.gsub!(/(?:\r?\n){3,}/, "\n\n") string.gsub!(/(?:\r?\n){3,}/, "\n\n")
string.strip! string.strip!
@@ -203,7 +203,7 @@ class DText
end end
end end
text = text.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "") text.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "")
end end
def self.from_html(text, inline: false, &block) def self.from_html(text, inline: false, &block)

View File

@@ -17,10 +17,7 @@ class ImageProxy
end end
response = HTTParty.get(url, Danbooru.config.httparty_options.deep_merge(headers: {"Referer" => fake_referer_for(url)})) response = HTTParty.get(url, Danbooru.config.httparty_options.deep_merge(headers: {"Referer" => fake_referer_for(url)}))
if response.success? raise "HTTP error code: #{response.code} #{response.message}" unless response.success?
return response response
else
raise "HTTP error code: #{response.code} #{response.message}"
end
end end
end end

View File

@@ -16,7 +16,7 @@ class IpLookup
end end
def info def info
return {} unless api_key.present? return {} if api_key.blank?
response = Danbooru::Http.cache(cache_duration).get("https://api.ipregistry.co/#{ip_addr}?key=#{api_key}") response = Danbooru::Http.cache(cache_duration).get("https://api.ipregistry.co/#{ip_addr}?key=#{api_key}")
return {} if response.status != 200 return {} if response.status != 200
json = response.parse.deep_symbolize_keys.with_indifferent_access json = response.parse.deep_symbolize_keys.with_indifferent_access

View File

@@ -42,7 +42,7 @@ class MediaFile::Flash < MediaFile
signature = contents[0..2] signature = contents[0..2]
# SWF version # SWF version
version = contents[3].unpack('C').join.to_i _version = contents[3].unpack('C').join.to_i
# Determine the length of the uncompressed stream # Determine the length of the uncompressed stream
length = contents[4..7].unpack('V').join.to_i length = contents[4..7].unpack('V').join.to_i
@@ -50,7 +50,7 @@ class MediaFile::Flash < MediaFile
# If we do, in fact, have compression # If we do, in fact, have compression
if signature == 'CWS' if signature == 'CWS'
# Decompress the body of the SWF # Decompress the body of the SWF
body = Zlib::Inflate.inflate( contents[8..length] ) body = Zlib::Inflate.inflate(contents[8..length])
# And reconstruct the stream contents to the first 8 bytes (header) # And reconstruct the stream contents to the first 8 bytes (header)
# Plus our decompressed body # Plus our decompressed body
@@ -58,10 +58,10 @@ class MediaFile::Flash < MediaFile
end end
# Determine the nbits of our dimensions rectangle # Determine the nbits of our dimensions rectangle
nbits = contents.unpack('C'*contents.length)[8] >> 3 nbits = contents.unpack('C' * contents.length)[8] >> 3
# Determine how many bits long this entire RECT structure is # Determine how many bits long this entire RECT structure is
rectbits = 5 + nbits * 4 # 5 bits for nbits, as well as nbits * number of fields (4) rectbits = 5 + nbits * 4 # 5 bits for nbits, as well as nbits * number of fields (4)
# Determine how many bytes rectbits composes (ceil(rectbits/8)) # Determine how many bytes rectbits composes (ceil(rectbits/8))
rectbytes = (rectbits.to_f / 8).ceil rectbytes = (rectbits.to_f / 8).ceil
@@ -70,11 +70,11 @@ class MediaFile::Flash < MediaFile
rect = contents[8..(8 + rectbytes)].unpack("#{'B8' * rectbytes}").join rect = contents[8..(8 + rectbytes)].unpack("#{'B8' * rectbytes}").join
# Read in nbits incremenets starting from 5 # Read in nbits incremenets starting from 5
dimensions = Array.new dimensions = []
4.times do |n| 4.times do |n|
s = 5 + (n * nbits) # Calculate our start index s = 5 + (n * nbits) # Calculate our start index
e = s + (nbits - 1) # Calculate our end index e = s + (nbits - 1) # Calculate our end index
dimensions[n] = rect[s..e].to_i(2) # Read that range (binary) and convert it to an integer dimensions[n] = rect[s..e].to_i(2) # Read that range (binary) and convert it to an integer
end end
# The values we have here are in "twips" # The values we have here are in "twips"

View File

@@ -106,10 +106,7 @@ module PaginationExtension
def total_count def total_count
@paginator_count ||= unscoped.from(except(:offset, :limit, :order).reorder(nil)).count @paginator_count ||= unscoped.from(except(:offset, :limit, :order).reorder(nil)).count
rescue ActiveRecord::StatementInvalid => e rescue ActiveRecord::StatementInvalid => e
if e.to_s =~ /statement timeout/ raise unless e.to_s =~ /statement timeout/
@paginator_count ||= 1_000_000 @paginator_count ||= 1_000_000
else
raise
end
end end
end end

View File

@@ -128,15 +128,15 @@ class PawooApiClient
rescue rescue
data = {} data = {}
end end
return Account.new(data) Account.new(data)
end end
end end
private private
def fetch_access_token def fetch_access_token
raise MissingConfigurationError.new("missing pawoo client id") if Danbooru.config.pawoo_client_id.nil? raise MissingConfigurationError, "missing pawoo client id" if Danbooru.config.pawoo_client_id.nil?
raise MissingConfigurationError.new("missing pawoo client secret") if Danbooru.config.pawoo_client_secret.nil? raise MissingConfigurationError, "missing pawoo client secret" if Danbooru.config.pawoo_client_secret.nil?
Cache.get("pawoo-token") do Cache.get("pawoo-token") do
result = client.client_credentials.get_token result = client.client_credentials.get_token

View File

@@ -58,7 +58,7 @@ class PixivWebAgent
end end
begin begin
mech.get("https://comic.pixiv.net") do |page| mech.get("https://comic.pixiv.net") do
cookie = mech.cookies.select {|x| x.name == COMIC_SESSION_COOKIE_KEY}.first cookie = mech.cookies.select {|x| x.name == COMIC_SESSION_COOKIE_KEY}.first
if cookie if cookie
Cache.put(COMIC_SESSION_CACHE_KEY, cookie.value, 1.week) Cache.put(COMIC_SESSION_CACHE_KEY, cookie.value, 1.week)

View File

@@ -94,7 +94,7 @@ module PostSets
end end
def get_random_posts def get_random_posts
per_page.times.inject([]) do |all, x| per_page.times.inject([]) do |all, _|
all << ::Post.user_tag_match(tag_string).random all << ::Post.user_tag_match(tag_string).random
end.compact.uniq end.compact.uniq
end end
@@ -104,9 +104,9 @@ module PostSets
@post_count = get_post_count @post_count = get_post_count
if is_random? if is_random?
temp = get_random_posts get_random_posts
else else
temp = normalized_query.build.paginate(page, count: post_count, search_count: !post_count.nil?, limit: per_page) normalized_query.build.paginate(page, count: post_count, search_count: !post_count.nil?, limit: per_page)
end end
end end
end end

View File

@@ -7,10 +7,11 @@ class SpamDetector
# if a person receives more than 10 automatic spam reports within a 1 hour # if a person receives more than 10 automatic spam reports within a 1 hour
# window, automatically ban them forever. # window, automatically ban them forever.
AUTOBAN_THRESHOLD = 10 AUTOBAN_THRESHOLD = 10
AUTOBAN_WINDOW = 1.hours AUTOBAN_WINDOW = 1.hour
AUTOBAN_DURATION = 999999 AUTOBAN_DURATION = 999_999
attr_accessor :record, :user, :user_ip, :content, :comment_type attr_accessor :record, :user, :user_ip, :content, :comment_type
rakismet_attrs author: proc { user.name }, rakismet_attrs author: proc { user.name },
author_email: proc { user.email_address&.address }, author_email: proc { user.email_address&.address },
blog_lang: "en", blog_lang: "en",
@@ -84,8 +85,8 @@ class SpamDetector
end end
is_spam is_spam
rescue StandardError => exception rescue StandardError => e
DanbooruLogger.log(exception) DanbooruLogger.log(e)
false false
end end
end end

View File

@@ -21,7 +21,7 @@ class StorageManager::SFTP < StorageManager
temp_upload_path = dest_path + "-" + SecureRandom.uuid + ".tmp" temp_upload_path = dest_path + "-" + SecureRandom.uuid + ".tmp"
dest_backup_path = dest_path + "-" + SecureRandom.uuid + ".bak" dest_backup_path = dest_path + "-" + SecureRandom.uuid + ".bak"
each_host do |host, sftp| each_host do |_host, sftp|
sftp.upload!(file.path, temp_upload_path) sftp.upload!(file.path, temp_upload_path)
sftp.setstat!(temp_upload_path, permissions: DEFAULT_PERMISSIONS) sftp.setstat!(temp_upload_path, permissions: DEFAULT_PERMISSIONS)
@@ -40,7 +40,7 @@ class StorageManager::SFTP < StorageManager
end end
def delete(dest_path) def delete(dest_path)
each_host do |host, sftp| each_host do |_host, sftp|
force { sftp.remove!(dest_path) } force { sftp.remove!(dest_path) }
end end
end end

View File

@@ -25,8 +25,7 @@ module TagAutocomplete
def search(query) def search(query)
query = Tag.normalize_name(query) query = Tag.normalize_name(query)
candidates = count_sort( count_sort(
query,
search_exact(query, 8) + search_exact(query, 8) +
search_prefix(query, 4) + search_prefix(query, 4) +
search_correct(query, 2) + search_correct(query, 2) +
@@ -34,7 +33,7 @@ module TagAutocomplete
) )
end end
def count_sort(query, words) def count_sort(words)
words.uniq(&:name).sort_by do |x| words.uniq(&:name).sort_by do |x|
x.post_count * x.weight x.post_count * x.weight
end.reverse.slice(0, LIMIT) end.reverse.slice(0, LIMIT)

View File

@@ -4,11 +4,11 @@ module TagRelationshipRetirementService
THRESHOLD = 2.years THRESHOLD = 2.years
def forum_topic_title def forum_topic_title
return "Retired tag aliases & implications" "Retired tag aliases & implications"
end end
def forum_topic_body def forum_topic_body
return "This topic deals with tag relationships created two or more years ago that have not been used since. They will be retired. This topic will be updated as an automated system retires expired relationships." "This topic deals with tag relationships created two or more years ago that have not been used since. They will be retired. This topic will be updated as an automated system retires expired relationships."
end end
def dry_run def dry_run
@@ -27,7 +27,7 @@ module TagRelationshipRetirementService
forum_post = ForumPost.create!(creator: User.system, body: forum_topic_body, topic: topic) forum_post = ForumPost.create!(creator: User.system, body: forum_topic_body, topic: topic)
end end
end end
return topic topic
end end
def find_and_retire! def find_and_retire!
@@ -50,16 +50,6 @@ module TagRelationshipRetirementService
yield(rel) yield(rel)
end end
end end
# model.active.where("created_at < ?", SMALL_THRESHOLD.ago).find_each do |rel|
# if is_underused?(rel.consequent_name)
# yield(rel)
# end
# end
end
def is_underused?(name)
(Tag.find_by_name(name).try(:post_count) || 0) < COUNT_THRESHOLD
end end
def is_unused?(name) def is_unused?(name)

View File

@@ -2,7 +2,7 @@ class UploadLimit
extend Memoist extend Memoist
INITIAL_POINTS = 1000 INITIAL_POINTS = 1000
MAXIMUM_POINTS = 10000 MAXIMUM_POINTS = 10_000
attr_reader :user attr_reader :user
@@ -75,7 +75,7 @@ class UploadLimit
points += upload_value(points, is_deleted) points += upload_value(points, is_deleted)
points = points.clamp(0, MAXIMUM_POINTS) points = points.clamp(0, MAXIMUM_POINTS)
#warn "slots: %2d, points: %3d, value: %2d" % [UploadLimit.points_to_level(points) + 5, points, UploadLimit.upload_value(level, is_deleted)] # warn "slots: %2d, points: %3d, value: %2d" % [UploadLimit.points_to_level(points) + 5, points, UploadLimit.upload_value(level, is_deleted)]
end end
points points

View File

@@ -15,7 +15,6 @@ class UploadService
start! start!
end end
rescue ActiveRecord::RecordNotUnique rescue ActiveRecord::RecordNotUnique
return
end end
def start! def start!
@@ -31,8 +30,8 @@ class UploadService
begin begin
create_post_from_upload(@upload) create_post_from_upload(@upload)
rescue Exception => x rescue Exception => e
@upload.update(status: "error: #{x.class} - #{x.message}", backtrace: x.backtrace.join("\n")) @upload.update(status: "error: #{e.class} - #{e.message}", backtrace: e.backtrace.join("\n"))
end end
return @upload return @upload
end end
@@ -53,16 +52,16 @@ class UploadService
@upload.save! @upload.save!
@post = create_post_from_upload(@upload) @post = create_post_from_upload(@upload)
return @upload @upload
rescue Exception => x rescue Exception => e
@upload.update(status: "error: #{x.class} - #{x.message}", backtrace: x.backtrace.join("\n")) @upload.update(status: "error: #{e.class} - #{e.message}", backtrace: e.backtrace.join("\n"))
@upload @upload
end end
end end
def warnings def warnings
return [] if @post.nil? return [] if @post.nil?
return @post.warnings.full_messages @post.warnings.full_messages
end end
def create_post_from_upload(upload) def create_post_from_upload(upload)

View File

@@ -13,7 +13,7 @@ class UploadService
rescue Exception rescue Exception
end end
return [upload, remote_size] [upload, remote_size]
end end
if file if file
@@ -21,7 +21,7 @@ class UploadService
Preprocessor.new(file: file).delayed_start(CurrentUser.id) Preprocessor.new(file: file).delayed_start(CurrentUser.id)
end end
return [upload] [upload]
end end
end end
end end

View File

@@ -46,11 +46,9 @@ class UploadService
def predecessor def predecessor
if md5.present? if md5.present?
return Upload.where(status: ["preprocessed", "preprocessing"], md5: md5).first Upload.where(status: ["preprocessed", "preprocessing"], md5: md5).first
end elsif Utils.is_downloadable?(source)
Upload.where(status: ["preprocessed", "preprocessing"], source: source).first
if Utils.is_downloadable?(source)
return Upload.where(status: ["preprocessed", "preprocessing"], source: source).first
end end
end end
@@ -63,21 +61,20 @@ class UploadService
start! start!
end end
rescue ActiveRecord::RecordNotUnique rescue ActiveRecord::RecordNotUnique
return
end end
def start! def start!
if Utils.is_downloadable?(source) if Utils.is_downloadable?(source)
if Post.system_tag_match("source:#{canonical_source}").where.not(id: original_post_id).exists? if Post.system_tag_match("source:#{canonical_source}").where.not(id: original_post_id).exists?
raise ActiveRecord::RecordNotUnique.new("A post with source #{canonical_source} already exists") raise ActiveRecord::RecordNotUnique, "A post with source #{canonical_source} already exists"
end end
if Upload.where(source: source, status: "completed").exists? if Upload.where(source: source, status: "completed").exists?
raise ActiveRecord::RecordNotUnique.new("A completed upload with source #{source} already exists") raise ActiveRecord::RecordNotUnique, "A completed upload with source #{source} already exists"
end end
if Upload.where(source: source).where("status like ?", "error%").exists? if Upload.where(source: source).where("status like ?", "error%").exists?
raise ActiveRecord::RecordNotUnique.new("An errored upload with source #{source} already exists") raise ActiveRecord::RecordNotUnique, "An errored upload with source #{source} already exists"
end end
end end
@@ -95,21 +92,21 @@ class UploadService
upload.tag_string = params[:tag_string] upload.tag_string = params[:tag_string]
upload.status = "preprocessed" upload.status = "preprocessed"
upload.save! upload.save!
rescue Exception => x rescue Exception => e
upload.update(file_ext: nil, status: "error: #{x.class} - #{x.message}", backtrace: x.backtrace.join("\n")) upload.update(file_ext: nil, status: "error: #{e.class} - #{e.message}", backtrace: e.backtrace.join("\n"))
end end
return upload upload
end end
def finish!(upload = nil) def finish!(upload = nil)
pred = upload || self.predecessor pred = upload || predecessor
# regardless of who initialized the upload, credit should # regardless of who initialized the upload, credit should
# goto whoever submitted the form # goto whoever submitted the form
pred.initialize_attributes pred.initialize_attributes
pred.attributes = self.params pred.attributes = params
# if a file was uploaded after the preprocessing occurred, # if a file was uploaded after the preprocessing occurred,
# then process the file and overwrite whatever the preprocessor # then process the file and overwrite whatever the preprocessor
@@ -118,7 +115,7 @@ class UploadService
pred.status = "completed" pred.status = "completed"
pred.save pred.save
return pred pred
end end
end end
end end

View File

@@ -62,7 +62,7 @@ class UploadService
end end
def source_strategy(upload) def source_strategy(upload)
return Sources::Strategies.find(upload.source, upload.referer_url) Sources::Strategies.find(upload.source, upload.referer_url)
end end
def find_replacement_url(repl, upload) def find_replacement_url(repl, upload)
@@ -78,7 +78,7 @@ class UploadService
return source_strategy(upload).canonical_url return source_strategy(upload).canonical_url
end end
return upload.source upload.source
end end
def process! def process!

View File

@@ -83,7 +83,7 @@ class UploadService
} }
end end
return file file
end end
end end
end end

View File

@@ -2,6 +2,7 @@ class UserDeletion
include ActiveModel::Validations include ActiveModel::Validations
attr_reader :user, :password attr_reader :user, :password
validate :validate_deletion validate :validate_deletion
def initialize(user, password) def initialize(user, password)