From 309821bf731bf957db1b059eab4586c8ba2a0903 Mon Sep 17 00:00:00 2001 From: evazion Date: Sun, 22 Dec 2019 16:21:58 -0600 Subject: [PATCH] rubocop: fix various style issues. --- Rakefile | 2 +- app/controllers/application_controller.rb | 10 +- .../artist_commentaries_controller.rb | 2 +- app/controllers/artist_urls_controller.rb | 4 +- app/controllers/artists_controller.rb | 2 +- app/controllers/comments_controller.rb | 3 +- app/controllers/counts_controller.rb | 4 +- app/controllers/dmails_controller.rb | 2 +- app/controllers/explore/posts_controller.rb | 3 +- .../forum_post_votes_controller.rb | 2 +- app/controllers/forum_posts_controller.rb | 7 +- app/controllers/forum_topics_controller.rb | 7 +- app/controllers/ip_addresses_controller.rb | 5 +- app/controllers/legacy_controller.rb | 3 +- .../user/email_notifications_controller.rb | 4 +- .../moderator/post/queues_controller.rb | 4 +- app/controllers/pool_elements_controller.rb | 3 +- app/controllers/pool_versions_controller.rb | 2 +- .../post_replacements_controller.rb | 5 +- app/controllers/posts_controller.rb | 8 +- app/controllers/sessions_controller.rb | 2 +- app/controllers/tag_aliases_controller.rb | 2 +- .../tag_implications_controller.rb | 2 +- app/controllers/tags_controller.rb | 3 +- app/controllers/users_controller.rb | 2 +- app/controllers/wiki_pages_controller.rb | 8 +- app/helpers/application_helper.rb | 20 ++- app/helpers/artist_versions_helper.rb | 2 +- app/helpers/bulk_update_requests_helper.rb | 2 +- app/helpers/pagination_helper.rb | 8 +- app/helpers/posts_helper.rb | 16 +-- app/helpers/uploads_helper.rb | 4 +- app/helpers/users_helper.rb | 2 +- app/helpers/wiki_page_versions_helper.rb | 12 +- app/helpers/wiki_pages_helper.rb | 4 +- app/jobs/tag_batch_change_job.rb | 2 +- .../upload_preprocessor_delayed_start_job.rb | 2 +- app/jobs/upload_service_delayed_start_job.rb | 2 +- app/logical/alias_and_implication_importer.rb | 2 +- app/logical/apng_inspector.rb | 66 +++++----- app/logical/approver_pruner.rb | 2 +- app/logical/d_text.rb | 13 +- app/logical/danbooru/has_bit_flags.rb | 2 +- app/logical/danbooru_image_resizer.rb | 3 +- app/logical/danbooru_logger.rb | 4 +- app/logical/danbooru_math.rb | 6 +- app/logical/deviant_art_api_client.rb | 2 +- app/logical/downloads/file.rb | 8 +- app/logical/forum_updater.rb | 2 +- app/logical/moderator/ip_addr_search.rb | 3 +- app/logical/nico_seiga_api_client.rb | 4 +- app/logical/nico_seiga_manga_api_client.rb | 2 +- app/logical/note_sanitizer.rb | 8 +- app/logical/pagination_extension.rb | 2 +- app/logical/pawoo_api_client.rb | 2 +- app/logical/pixiv_api_client.rb | 20 +-- app/logical/pixiv_ugoira_converter.rb | 6 +- app/logical/pixiv_web_agent.rb | 2 +- app/logical/popular_search_service.rb | 7 +- app/logical/post_pruner.rb | 10 +- app/logical/post_query_builder.rb | 10 +- app/logical/post_sets/post.rb | 12 +- app/logical/post_sets/recommended.rb | 2 +- app/logical/related_tag_calculator.rb | 2 +- app/logical/related_tag_query.rb | 2 +- app/logical/reports/upload_tags.rb | 1 - app/logical/reports/uploads.rb | 2 +- app/logical/reports/user_promotions.rb | 6 +- app/logical/session_loader.rb | 4 +- app/logical/set_diff.rb | 2 +- app/logical/sources/strategies.rb | 4 +- app/logical/sources/strategies/art_station.rb | 19 ++- app/logical/sources/strategies/base.rb | 32 +++-- app/logical/sources/strategies/deviant_art.rb | 4 - app/logical/sources/strategies/nico_seiga.rb | 2 - app/logical/sources/strategies/nijie.rb | 11 +- app/logical/sources/strategies/pawoo.rb | 2 - app/logical/sources/strategies/pixiv.rb | 9 +- app/logical/sources/strategies/tumblr.rb | 4 +- app/logical/sources/strategies/twitter.rb | 4 +- app/logical/spam_detector.rb | 4 +- app/logical/sqs_service.rb | 3 +- app/logical/storage_manager.rb | 2 +- app/logical/storage_manager/local.rb | 2 +- app/logical/storage_manager/match.rb | 63 +++++---- app/logical/storage_manager/sftp.rb | 32 +++-- app/logical/tag_alias_request.rb | 2 +- app/logical/tag_autocomplete.rb | 15 +-- app/logical/tag_change_notice_service.rb | 2 +- app/logical/tag_implication_request.rb | 2 +- .../tag_relationship_retirement_service.rb | 5 +- app/logical/upload_error_checker.rb | 1 - app/logical/upload_service.rb | 1 - app/logical/upload_service/preprocessor.rb | 6 +- app/logical/upload_service/replacer.rb | 2 +- app/logical/upload_service/utils.rb | 17 ++- app/logical/user_deletion.rb | 12 +- app/logical/user_name_validator.rb | 4 +- app/logical/user_promotion.rb | 28 ++-- app/models/application_record.rb | 2 +- app/models/artist.rb | 26 ++-- app/models/artist_commentary.rb | 4 +- app/models/artist_url.rb | 6 +- app/models/ban.rb | 4 +- app/models/bulk_update_request.rb | 18 ++- app/models/comment.rb | 10 +- app/models/comment_vote.rb | 2 +- app/models/dmail_filter.rb | 2 +- app/models/favorite.rb | 4 +- app/models/favorite_group.rb | 18 ++- app/models/forum_post.rb | 14 +- app/models/forum_topic.rb | 27 ++-- app/models/ip_address.rb | 2 +- app/models/mod_action.rb | 24 ++-- app/models/note.rb | 2 +- app/models/pixiv_ugoira_frame_data.rb | 4 +- app/models/pool.rb | 6 +- app/models/pool_archive.rb | 1 - app/models/pool_version.rb | 2 +- app/models/post.rb | 123 +++++++++--------- app/models/post_appeal.rb | 2 +- app/models/post_approval.rb | 2 +- app/models/post_archive.rb | 8 +- app/models/post_event.rb | 2 +- app/models/post_flag.rb | 2 +- app/models/post_replacement.rb | 1 - app/models/post_version.rb | 2 +- app/models/post_vote.rb | 2 +- app/models/saved_search.rb | 38 +++--- app/models/tag.rb | 32 ++--- app/models/tag_alias.rb | 16 +-- app/models/tag_implication.rb | 16 +-- app/models/tag_relationship.rb | 14 +- app/models/upload.rb | 5 +- app/models/user.rb | 58 ++++----- app/models/user_feedback.rb | 6 +- app/models/wiki_page.rb | 6 +- app/presenters/post_presenter.rb | 4 +- app/presenters/presenter.rb | 2 +- app/presenters/tag_set_presenter.rb | 13 +- app/presenters/user_presenter.rb | 8 +- app/presenters/wiki_page_presenter.rb | 12 +- config.ru | 4 +- config/application.rb | 20 +-- config/danbooru_default_config.rb | 46 +++---- config/environments/production.rb | 2 +- config/environments/test.rb | 2 +- config/initializers/cache_store.rb | 8 +- config/initializers/mechanize_patch.rb | 12 +- config/initializers/simple_form.rb | 3 +- config/initializers/unicorn.rb | 2 +- config/routes.rb | 29 ++--- config/unicorn/development.rb | 2 +- config/unicorn/production.rb | 4 +- config/unicorn/staging.rb | 8 +- ...035904_create_user_name_change_requests.rb | 2 +- .../20130331180246_create_key_values.rb | 2 +- .../20130331182719_add_pixiv_id_to_posts.rb | 2 +- ...ge_tag_subscription_tag_query_delimiter.rb | 4 +- .../20150120005624_remove_unused_indexes.rb | 2 +- ...024220345_add_min_level_to_forum_topics.rb | 2 +- .../20161101003139_create_post_approvals.rb | 4 +- ...161221225849_drop_transaction_log_items.rb | 2 +- .../20161229001201_drop_pool_versions.rb | 4 +- .../20170106012138_create_token_buckets.rb | 6 +- ...170117233040_add_trigram_index_to_users.rb | 2 +- ...170314235626_add_tags_to_saved_searches.rb | 8 +- .../20170316224630_drop_post_versions.rb | 4 +- ...30231_add_forum_post_id_to_tag_requests.rb | 10 +- ...00209_add_title_to_bulk_update_requests.rb | 2 +- ...856_add_unique_name_constraint_to_users.rb | 8 +- ...414233617_add_updated_at_index_to_pools.rb | 2 +- ...20170512221200_create_post_replacements.rb | 8 +- ...235205_add_sort_indexes_to_forum_topics.rb | 2 +- ...204506_fix_last_noted_at_index_on_posts.rb | 2 +- .../20170914200122_add_is_spam_to_dmails.rb | 6 +- ...0171127195124_add_trigram_index_to_tags.rb | 12 +- ...002448_add_trigram_index_to_artist_urls.rb | 2 +- db/populate.rb | 39 +++--- lib/capistrano/tasks/nginx.rake | 2 +- lib/tasks/images.rake | 5 +- lib/tasks/iqdb.rake | 9 ++ script/fixes/004.rb | 0 script/fixes/005.rb | 4 +- script/fixes/006.rb | 0 script/fixes/007.rb | 0 script/fixes/008.rb | 0 script/fixes/009.rb | 0 script/fixes/010.rb | 0 script/fixes/011.rb | 0 script/fixes/012.rb | 0 script/fixes/013.rb | 10 +- script/fixes/014_note_ranges.rb | 2 +- script/fixes/015.rb | 0 script/fixes/016_fix_swf_dimensions.rb | 0 script/fixes/017_fix_md5.rb | 2 +- script/fixes/018_fix_md5.rb | 0 script/fixes/019_fix_pool_names.rb | 0 script/fixes/020_retrieve_bad_md5_posts.rb | 0 script/fixes/021_fix_deleted_pool_strings.rb | 0 script/fixes/022_expunge_missing_images.rb | 0 .../023_remove_expunged_posts_from_pools.rb | 0 script/fixes/024_move_favorites_to_parent.rb | 2 +- script/fixes/025_last_commented_at.rb | 6 +- script/fixes/026_fix_unicode_capitals.rb | 0 script/fixes/027_fix_banned_artists.rb | 0 script/fixes/028_fix_has_children.rb | 0 script/fixes/029_iqdb_import.rb | 0 .../030_calculate_has_active_children.rb | 0 script/fixes/031_fix_ugoira_dimensions.rb | 0 .../032_add_pool_category_pseudo_tags.rb | 0 .../033_enable_can_approve_posts_flag.rb | 0 script/fixes/034_fix_dmail_filters.rb | 0 .../fixes/035_fix_nico_seiga_artist_urls.rb | 0 .../036_fix_hentai_foundry_artist_urls.rb | 0 script/fixes/037_enable_can_upload_free.rb | 0 ..._reset_categorized_saved_search_setting.rb | 0 .../fixes/039_fix_saved_search_categories.rb | 0 script/fixes/040_fix_post_scores.rb | 0 .../041_remove_expunged_posts_from_iqdb.rb | 0 script/fixes/042_fix_user_cache_counters.rb | 0 script/fixes/043_fix_whitespace_usernames.rb | 0 .../044_initialized_saved_search_tags.rb | 0 script/fixes/045_dedup_users.rb | 0 script/fixes/046_fix_nicovideo_artist_urls.rb | 2 +- script/fixes/048_remove_expunged_favorites.rb | 2 +- script/fixes/049_spam_1.rb | 2 +- script/fixes/050_fix_post_tagcount.rb | 0 script/fixes/051_purge_invalid_tags.rb | 2 +- script/fixes/053_normalize_ugoira_data.rb | 0 .../fixes/055_reindex_replacements_in_iqdb.rb | 0 .../fixes/056_message_nonascii_usernames.rb | 0 script/fixes/059_fix_favorites.rb | 14 ++ script/mock_services/iqdbs.rb | 2 +- script/mock_services/mock_service_helper.rb | 4 +- script/mock_services/recommender.rb | 4 +- test/factories/artist.rb | 1 - test/factories/pool.rb | 2 +- test/factories/upload.rb | 1 - test/factories/user.rb | 1 - .../admin/dashboards_controller_test.rb | 2 +- .../artist_commentaries_controller_test.rb | 8 +- .../functional/artist_urls_controller_test.rb | 2 +- test/functional/comments_controller_test.rb | 2 +- .../forum_topics_controller_test.rb | 10 +- .../user/deletions_controller_test.rb | 2 +- .../user/email_changes_controller_test.rb | 2 +- .../moderator/dashboards_controller_test.rb | 2 +- .../moderator/ip_addrs_controller_test.rb | 2 +- .../post/disapprovals_controller_test.rb | 2 +- .../moderator/post/posts_controller_test.rb | 4 +- test/functional/notes_controller_test.rb | 2 +- .../post_replacements_controller_test.rb | 4 +- test/functional/uploads_controller_test.rb | 16 +-- test/functional/users_controller_test.rb | 4 +- test/jobs/application_job_test.rb | 3 +- test/models/tag_autocomplete_test.rb | 2 +- ...ag_relationship_retirement_service_test.rb | 3 +- test/models/upload_service_test.rb | 72 +++++----- test/test_helper.rb | 6 +- test/test_helpers/download_test_helper.rb | 6 +- test/unit/apng_inspector_test.rb | 1 - test/unit/artist_commentary_test.rb | 2 +- test/unit/artist_test.rb | 6 +- test/unit/artist_url_test.rb | 2 +- test/unit/bulk_update_request_test.rb | 4 +- test/unit/cloudflare_service_test.rb | 2 +- test/unit/dmail_test.rb | 4 +- test/unit/downloads/file_test.rb | 6 +- test/unit/downloads/pixiv_test.rb | 5 +- test/unit/downloads/tumblr_test.rb | 2 +- test/unit/favorite_group_test.rb | 6 +- test/unit/forum_post_test.rb | 4 +- test/unit/forum_topic_test.rb | 6 +- test/unit/pool_test.rb | 2 - test/unit/post_archive_test.rb | 12 +- test/unit/post_flag_test.rb | 2 +- test/unit/post_pruner_test.rb | 2 +- test/unit/post_test.rb | 21 ++- test/unit/post_view_count_service_test.rb | 2 +- test/unit/related_tag_query_test.rb | 1 - test/unit/sources/nico_seiga_test.rb | 4 +- test/unit/sources/pawoo_test.rb | 6 +- test/unit/sources/pixiv_test.rb | 8 +- test/unit/sources/twitter_test.rb | 2 +- test/unit/token_bucket_test.rb | 2 +- test/unit/user_feedback_test.rb | 2 +- test/unit/user_test.rb | 2 +- 288 files changed, 912 insertions(+), 962 deletions(-) mode change 100644 => 100755 app/logical/upload_error_checker.rb create mode 100644 lib/tasks/iqdb.rake mode change 100644 => 100755 script/fixes/004.rb mode change 100644 => 100755 script/fixes/005.rb mode change 100644 => 100755 script/fixes/006.rb mode change 100644 => 100755 script/fixes/007.rb mode change 100644 => 100755 script/fixes/008.rb mode change 100644 => 100755 script/fixes/009.rb mode change 100644 => 100755 script/fixes/010.rb mode change 100644 => 100755 script/fixes/011.rb mode change 100644 => 100755 script/fixes/012.rb mode change 100644 => 100755 script/fixes/013.rb mode change 100644 => 100755 script/fixes/014_note_ranges.rb mode change 100644 => 100755 script/fixes/015.rb mode change 100644 => 100755 script/fixes/016_fix_swf_dimensions.rb mode change 100644 => 100755 script/fixes/017_fix_md5.rb mode change 100644 => 100755 script/fixes/018_fix_md5.rb mode change 100644 => 100755 script/fixes/019_fix_pool_names.rb mode change 100644 => 100755 script/fixes/020_retrieve_bad_md5_posts.rb mode change 100644 => 100755 script/fixes/021_fix_deleted_pool_strings.rb mode change 100644 => 100755 script/fixes/022_expunge_missing_images.rb mode change 100644 => 100755 script/fixes/023_remove_expunged_posts_from_pools.rb mode change 100644 => 100755 script/fixes/024_move_favorites_to_parent.rb mode change 100644 => 100755 script/fixes/025_last_commented_at.rb mode change 100644 => 100755 script/fixes/026_fix_unicode_capitals.rb mode change 100644 => 100755 script/fixes/027_fix_banned_artists.rb mode change 100644 => 100755 script/fixes/028_fix_has_children.rb mode change 100644 => 100755 script/fixes/029_iqdb_import.rb mode change 100644 => 100755 script/fixes/030_calculate_has_active_children.rb mode change 100644 => 100755 script/fixes/031_fix_ugoira_dimensions.rb mode change 100644 => 100755 script/fixes/032_add_pool_category_pseudo_tags.rb mode change 100644 => 100755 script/fixes/033_enable_can_approve_posts_flag.rb mode change 100644 => 100755 script/fixes/034_fix_dmail_filters.rb mode change 100644 => 100755 script/fixes/035_fix_nico_seiga_artist_urls.rb mode change 100644 => 100755 script/fixes/036_fix_hentai_foundry_artist_urls.rb mode change 100644 => 100755 script/fixes/037_enable_can_upload_free.rb mode change 100644 => 100755 script/fixes/038_reset_categorized_saved_search_setting.rb mode change 100644 => 100755 script/fixes/039_fix_saved_search_categories.rb mode change 100644 => 100755 script/fixes/040_fix_post_scores.rb mode change 100644 => 100755 script/fixes/041_remove_expunged_posts_from_iqdb.rb mode change 100644 => 100755 script/fixes/042_fix_user_cache_counters.rb mode change 100644 => 100755 script/fixes/043_fix_whitespace_usernames.rb mode change 100644 => 100755 script/fixes/044_initialized_saved_search_tags.rb mode change 100644 => 100755 script/fixes/045_dedup_users.rb mode change 100644 => 100755 script/fixes/046_fix_nicovideo_artist_urls.rb mode change 100644 => 100755 script/fixes/048_remove_expunged_favorites.rb mode change 100644 => 100755 script/fixes/049_spam_1.rb mode change 100644 => 100755 script/fixes/050_fix_post_tagcount.rb mode change 100644 => 100755 script/fixes/053_normalize_ugoira_data.rb mode change 100644 => 100755 script/fixes/055_reindex_replacements_in_iqdb.rb mode change 100644 => 100755 script/fixes/056_message_nonascii_usernames.rb create mode 100755 script/fixes/059_fix_favorites.rb diff --git a/Rakefile b/Rakefile index 2d06b2dc8..e9e8a013e 100644 --- a/Rakefile +++ b/Rakefile @@ -1,7 +1,7 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require File.expand_path('../config/application', __FILE__) +require File.expand_path('config/application', __dir__) require 'rake' Rails.application.load_tasks diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 9bee200f3..ba3d08ffc 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -16,14 +16,14 @@ class ApplicationController < ActionController::Base rescue_from Exception, :with => :rescue_exception - protected - def self.rescue_with(*klasses, status: 500) - rescue_from *klasses do |exception| + rescue_from(*klasses) do |exception| render_error_page(status, exception) end end + protected + def enable_cors response.headers["Access-Control-Allow-Origin"] = "*" end @@ -61,7 +61,7 @@ class ApplicationController < ActionController::Base when ActionController::RoutingError render_error_page(405, exception) when ActionController::UnknownFormat, ActionView::MissingTemplate - render_error_page(406, exception, message: "#{request.format.to_s} is not a supported format for this page") + render_error_page(406, exception, message: "#{request.format} is not a supported format for this page") when PaginationExtension::PaginationError render_error_page(410, exception, template: "static/pagination_error", message: "You cannot go beyond page #{Danbooru.config.max_numbered_pages}.") when Post::SearchError @@ -80,7 +80,7 @@ class ApplicationController < ActionController::Base def render_error_page(status, exception, message: exception.message, template: "static/error", format: request.format.symbol) @exception = exception @expected = status < 500 - @message = message.encode("utf-8", { invalid: :replace, undef: :replace }) + @message = message.encode("utf-8", invalid: :replace, undef: :replace) @backtrace = Rails.backtrace_cleaner.clean(@exception.backtrace) format = :html unless format.in?(%i[html json xml js atom]) diff --git a/app/controllers/artist_commentaries_controller.rb b/app/controllers/artist_commentaries_controller.rb index bf64af583..055aa0c8e 100644 --- a/app/controllers/artist_commentaries_controller.rb +++ b/app/controllers/artist_commentaries_controller.rb @@ -34,7 +34,7 @@ class ArtistCommentariesController < ApplicationController @artist_commentary.revert_to!(@version) end -private + private def commentary_params params.fetch(:artist_commentary, {}).except(:post_id).permit(%i[ diff --git a/app/controllers/artist_urls_controller.rb b/app/controllers/artist_urls_controller.rb index 900d8ff0b..eb4228214 100644 --- a/app/controllers/artist_urls_controller.rb +++ b/app/controllers/artist_urls_controller.rb @@ -5,7 +5,7 @@ class ArtistUrlsController < ApplicationController def index @artist_urls = ArtistUrl.includes(:artist).paginated_search(params) respond_with(@artist_urls) do |format| - format.json { render json: @artist_urls.to_json(include: "artist",) } + format.json { render json: @artist_urls.to_json(include: "artist") } format.xml { render xml: @artist_urls.to_xml(include: "artist", root: "artist-urls") } end end @@ -16,7 +16,7 @@ class ArtistUrlsController < ApplicationController respond_with(@artist_url) end -private + private def artist_url_params permitted_params = %i[is_active] diff --git a/app/controllers/artists_controller.rb b/app/controllers/artists_controller.rb index d9e505e15..c54d68754 100644 --- a/app/controllers/artists_controller.rb +++ b/app/controllers/artists_controller.rb @@ -85,7 +85,7 @@ class ArtistsController < ApplicationController end end -private + private def load_artist @artist = Artist.find(params[:id]) diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb index 309289870..488622c04 100644 --- a/app/controllers/comments_controller.rb +++ b/app/controllers/comments_controller.rb @@ -72,7 +72,8 @@ class CommentsController < ApplicationController respond_with(@comment) end -private + private + def index_for_post @post = Post.find(params[:post_id]) @comments = @post.comments diff --git a/app/controllers/counts_controller.rb b/app/controllers/counts_controller.rb index 11e2c05a3..6c4a758c1 100644 --- a/app/controllers/counts_controller.rb +++ b/app/controllers/counts_controller.rb @@ -3,8 +3,8 @@ class CountsController < ApplicationController def posts @count = Post.fast_count( - params[:tags], - timeout: CurrentUser.statement_timeout, + params[:tags], + timeout: CurrentUser.statement_timeout, raise_on_timeout: true, skip_cache: params[:skip_cache] ) diff --git a/app/controllers/dmails_controller.rb b/app/controllers/dmails_controller.rb index 427f82449..d76e19985 100644 --- a/app/controllers/dmails_controller.rb +++ b/app/controllers/dmails_controller.rb @@ -60,7 +60,7 @@ class DmailsController < ApplicationController @dmail.update_column(:is_spam, false) end -private + private def check_privilege(dmail) if !dmail.visible_to?(CurrentUser.user, params[:key]) diff --git a/app/controllers/explore/posts_controller.rb b/app/controllers/explore/posts_controller.rb index 006df5e98..ab378d48b 100644 --- a/app/controllers/explore/posts_controller.rb +++ b/app/controllers/explore/posts_controller.rb @@ -28,7 +28,8 @@ module Explore render :layout => "blank" end - private + private + def set_date @date = params[:date] ? Date.parse(params[:date]) : Date.today end diff --git a/app/controllers/forum_post_votes_controller.rb b/app/controllers/forum_post_votes_controller.rb index 555b691e8..59fedd82e 100644 --- a/app/controllers/forum_post_votes_controller.rb +++ b/app/controllers/forum_post_votes_controller.rb @@ -19,7 +19,7 @@ class ForumPostVotesController < ApplicationController respond_with(@forum_post_vote) end -private + private def forum_post_vote_params params.fetch(:forum_post_vote, {}).permit(:score) diff --git a/app/controllers/forum_posts_controller.rb b/app/controllers/forum_posts_controller.rb index 63fd90657..282e35358 100644 --- a/app/controllers/forum_posts_controller.rb +++ b/app/controllers/forum_posts_controller.rb @@ -4,10 +4,10 @@ class ForumPostsController < ApplicationController before_action :load_post, :only => [:edit, :show, :update, :destroy, :undelete] before_action :check_min_level, :only => [:edit, :show, :update, :destroy, :undelete] skip_before_action :api_check - + def new if params[:topic_id] - @forum_topic = ForumTopic.find(params[:topic_id]) + @forum_topic = ForumTopic.find(params[:topic_id]) raise User::PrivilegeError.new unless @forum_topic.visible?(CurrentUser.user) end if params[:post_id] @@ -66,7 +66,8 @@ class ForumPostsController < ApplicationController respond_with(@forum_post) end -private + private + def load_post @forum_post = ForumPost.find(params[:id]) @forum_topic = @forum_post.topic diff --git a/app/controllers/forum_topics_controller.rb b/app/controllers/forum_topics_controller.rb index 75ef9c583..5a14f0880 100644 --- a/app/controllers/forum_topics_controller.rb +++ b/app/controllers/forum_topics_controller.rb @@ -93,13 +93,12 @@ class ForumTopicsController < ApplicationController def unsubscribe subscription = ForumSubscription.where(:forum_topic_id => @forum_topic.id, :user_id => CurrentUser.user.id).first - if subscription - subscription.destroy - end + subscription&.destroy respond_with(@forum_topic) end -private + private + def normalize_search if params[:title_matches] params[:search] ||= {} diff --git a/app/controllers/ip_addresses_controller.rb b/app/controllers/ip_addresses_controller.rb index c910cecf0..8689acc02 100644 --- a/app/controllers/ip_addresses_controller.rb +++ b/app/controllers/ip_addresses_controller.rb @@ -5,13 +5,12 @@ class IpAddressesController < ApplicationController def index if search_params[:group_by] == "ip_addr" @ip_addresses = IpAddress.search(search_params).group_by_ip_addr(search_params[:ipv4_masklen], search_params[:ipv6_masklen]).paginate(params[:page], limit: params[:limit] || 1000) - respond_with(@ip_addresses) elsif search_params[:group_by] == "user" @ip_addresses = IpAddress.includes(:user).search(search_params).group_by_user.paginate(params[:page], limit: params[:limit] || 1000) - respond_with(@ip_addresses) else @ip_addresses = IpAddress.includes(:user, :model).paginated_search(params) - respond_with(@ip_addresses) end + + respond_with(@ip_addresses) end end diff --git a/app/controllers/legacy_controller.rb b/app/controllers/legacy_controller.rb index 25740baa5..3cd6f8c8d 100644 --- a/app/controllers/legacy_controller.rb +++ b/app/controllers/legacy_controller.rb @@ -33,7 +33,8 @@ class LegacyController < ApplicationController render :plain => "this resource is no longer available", :status => 410 end -private + private + def tag_query params[:tags] || (params[:post] && params[:post][:tags]) end diff --git a/app/controllers/maintenance/user/email_notifications_controller.rb b/app/controllers/maintenance/user/email_notifications_controller.rb index 85736687a..e5d00bf57 100644 --- a/app/controllers/maintenance/user/email_notifications_controller.rb +++ b/app/controllers/maintenance/user/email_notifications_controller.rb @@ -1,7 +1,7 @@ module Maintenance module User class EmailNotificationsController < ApplicationController - class VerificationError < Exception ; end + class VerificationError < Exception; end before_action :validate_sig, :only => [:destroy] rescue_from VerificationError, :with => :render_403 @@ -15,7 +15,7 @@ module Maintenance @user.save end - private + private def render_403 render plain: "", :status => 403 diff --git a/app/controllers/moderator/post/queues_controller.rb b/app/controllers/moderator/post/queues_controller.rb index dd9203b0f..205677d10 100644 --- a/app/controllers/moderator/post/queues_controller.rb +++ b/app/controllers/moderator/post/queues_controller.rb @@ -2,7 +2,7 @@ module Moderator module Post class QueuesController < ApplicationController RANDOM_COUNT = 12 - + respond_to :html, :json before_action :approver_only skip_before_action :api_check @@ -38,7 +38,7 @@ module Moderator respond_with(@posts) end - protected + protected def per_page cookies["mq_per_page"] || search_params[:per_page] || 25 diff --git a/app/controllers/pool_elements_controller.rb b/app/controllers/pool_elements_controller.rb index 464d83df9..9fc8cde76 100644 --- a/app/controllers/pool_elements_controller.rb +++ b/app/controllers/pool_elements_controller.rb @@ -27,7 +27,8 @@ class PoolElementsController < ApplicationController @pools end -private + private + def append_pool_to_session(pool) recent_pool_ids = session[:recent_pool_ids].to_s.scan(/\d+/) recent_pool_ids << pool.id.to_s diff --git a/app/controllers/pool_versions_controller.rb b/app/controllers/pool_versions_controller.rb index c77cafd31..27b718fcd 100644 --- a/app/controllers/pool_versions_controller.rb +++ b/app/controllers/pool_versions_controller.rb @@ -22,7 +22,7 @@ class PoolVersionsController < ApplicationController end end -private + private def set_timeout PoolArchive.connection.execute("SET statement_timeout = #{CurrentUser.user.statement_timeout}") diff --git a/app/controllers/post_replacements_controller.rb b/app/controllers/post_replacements_controller.rb index 2fe64f9b0..31a7e0696 100644 --- a/app/controllers/post_replacements_controller.rb +++ b/app/controllers/post_replacements_controller.rb @@ -23,13 +23,14 @@ class PostReplacementsController < ApplicationController end def index - params[:search][:post_id] = params.delete(:post_id) if params.has_key?(:post_id) + params[:search][:post_id] = params.delete(:post_id) if params.key?(:post_id) @post_replacements = PostReplacement.paginated_search(params) respond_with(@post_replacements) end -private + private + def create_params params.require(:post_replacement).permit(:replacement_url, :replacement_file, :final_source, :tags) end diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index e97503696..2b0be440b 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -58,7 +58,7 @@ class PostsController < ApplicationController if @post.visible? @post.revert_to!(@version) end - + respond_with(@post) do |format| format.js end @@ -68,7 +68,7 @@ class PostsController < ApplicationController @post = Post.find(params[:id]) @other_post = Post.find(params[:other_post_id].to_i) @post.copy_notes_to(@other_post) - + if @post.errors.any? @error_message = @post.errors.full_messages.join("; ") render :json => {:success => false, :reason => @error_message}.to_json, :status => 400 @@ -91,7 +91,7 @@ class PostsController < ApplicationController respond_with_post_after_update(@post) end -private + private def tag_query params[:tags] || (params[:post] && params[:post][:tags]) @@ -109,7 +109,7 @@ private render :template => "static/error", :status => 500 else response_params = {:q => params[:tags_query], :pool_id => params[:pool_id], :favgroup_id => params[:favgroup_id]} - response_params.reject!{|key, value| value.blank?} + response_params.reject! {|key, value| value.blank?} redirect_to post_path(post, response_params) end end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 5e93b19f9..140effd02 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -28,6 +28,6 @@ class SessionsController < ApplicationController end def sign_out - destroy() + destroy end end diff --git a/app/controllers/tag_aliases_controller.rb b/app/controllers/tag_aliases_controller.rb index 0b0f45ebe..acc86b969 100644 --- a/app/controllers/tag_aliases_controller.rb +++ b/app/controllers/tag_aliases_controller.rb @@ -40,7 +40,7 @@ class TagAliasesController < ApplicationController respond_with(@tag_alias, :location => tag_alias_path(@tag_alias)) end -private + private def tag_alias_params params.require(:tag_alias).permit(%i[antecedent_name consequent_name forum_topic_id skip_secondary_validations]) diff --git a/app/controllers/tag_implications_controller.rb b/app/controllers/tag_implications_controller.rb index 1c5951764..0b3f1f077 100644 --- a/app/controllers/tag_implications_controller.rb +++ b/app/controllers/tag_implications_controller.rb @@ -40,7 +40,7 @@ class TagImplicationsController < ApplicationController respond_with(@tag_implication, :location => tag_implication_path(@tag_implication)) end -private + private def tag_implication_params params.require(:tag_implication).permit(%i[antecedent_name consequent_name forum_topic_id skip_secondary_validations]) diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 4843f3b96..4a3cd5665 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -37,7 +37,8 @@ class TagsController < ApplicationController respond_with(@tag) end -private + private + def check_privilege(tag) raise User::PrivilegeError unless tag.editable_by?(CurrentUser.user) end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 696b26ae0..66d524cfd 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -99,7 +99,7 @@ class UsersController < ApplicationController private def check_privilege(user) - raise User::PrivilegeError unless (user.id == CurrentUser.id || CurrentUser.is_admin?) + raise User::PrivilegeError unless user.id == CurrentUser.id || CurrentUser.is_admin? end def user_params(context) diff --git a/app/controllers/wiki_pages_controller.rb b/app/controllers/wiki_pages_controller.rb index d2c9ff751..10a50f0d3 100644 --- a/app/controllers/wiki_pages_controller.rb +++ b/app/controllers/wiki_pages_controller.rb @@ -10,7 +10,7 @@ class WikiPagesController < ApplicationController end def edit - @wiki_page, _ = WikiPage.find_by_id_or_title(params[:id]) + @wiki_page, _found_by = WikiPage.find_by_id_or_title(params[:id]) respond_with(@wiki_page) end @@ -49,7 +49,7 @@ class WikiPagesController < ApplicationController end def update - @wiki_page, _ = WikiPage.find_by_id_or_title(params[:id]) + @wiki_page, _found_by = WikiPage.find_by_id_or_title(params[:id]) @wiki_page.update(wiki_page_params(:update)) flash[:notice] = @wiki_page.warnings.full_messages.join(".\n \n") if @wiki_page.warnings.any? @@ -57,13 +57,13 @@ class WikiPagesController < ApplicationController end def destroy - @wiki_page, _ = WikiPage.find_by_id_or_title(params[:id]) + @wiki_page, _found_by = WikiPage.find_by_id_or_title(params[:id]) @wiki_page.update(is_deleted: true) respond_with(@wiki_page) end def revert - @wiki_page, _ = WikiPage.find_by_id_or_title(params[:id]) + @wiki_page, _found_by = WikiPage.find_by_id_or_title(params[:id]) @version = @wiki_page.versions.find(params[:version_id]) @wiki_page.revert_to!(@version) flash[:notice] = "Page was reverted" diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index c3414e380..e9bf75873 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -8,7 +8,7 @@ module ApplicationHelper def wordbreakify(string) lines = string.scan(/.{1,10}/) - wordbreaked_string = lines.map{|str| h(str)}.join("") + wordbreaked_string = lines.map {|str| h(str)}.join("") raw(wordbreaked_string) end @@ -43,7 +43,7 @@ module ApplicationHelper def error_messages_for(instance_name) instance = instance_variable_get("@#{instance_name}") - if instance && instance.errors.any? + if instance&.errors&.any? %{
Error: #{instance.__send__(:errors).full_messages.join(", ")}
}.html_safe else "" @@ -133,11 +133,11 @@ module ApplicationHelper return "anonymous" if user.blank? user_class = "user-#{user.level_string.downcase}" - user_class = user_class + " user-post-approver" if user.can_approve_posts? - user_class = user_class + " user-post-uploader" if user.can_upload_free? - user_class = user_class + " user-super-voter" if user.is_super_voter? - user_class = user_class + " user-banned" if user.is_banned? - user_class = user_class + " with-style" if CurrentUser.user.style_usernames? + user_class += " user-post-approver" if user.can_approve_posts? + user_class += " user-post-uploader" if user.can_upload_free? + user_class += " user-super-voter" if user.is_super_voter? + user_class += " user-banned" if user.is_banned? + user_class += " with-style" if CurrentUser.user.style_usernames? if options[:raw_name] name = user.name else @@ -252,15 +252,13 @@ module ApplicationHelper CurrentUser.can_approve_posts? && (cookies[:moderated].blank? || Time.at(cookies[:moderated].to_i) < 72.hours.ago) end -protected + protected + def nav_link_match(controller, url) url =~ case controller when "sessions", "users", "maintenance/user/password_resets", "admin/users" /^\/(session|users)/ - when "forum_posts" - /^\/forum_topics/ - when "comments" /^\/comments/ diff --git a/app/helpers/artist_versions_helper.rb b/app/helpers/artist_versions_helper.rb index 87ed000c1..acd1c685e 100644 --- a/app/helpers/artist_versions_helper.rb +++ b/app/helpers/artist_versions_helper.rb @@ -1,6 +1,6 @@ module ArtistVersionsHelper def artist_versions_listing_type - params.dig(:search, :artist_id).present? && CurrentUser.is_member? ? :revert : :standard + (params.dig(:search, :artist_id).present? && CurrentUser.is_member?) ? :revert : :standard end def artist_version_other_names_diff(artist_version) diff --git a/app/helpers/bulk_update_requests_helper.rb b/app/helpers/bulk_update_requests_helper.rb index 9d9bd135e..64d580586 100644 --- a/app/helpers/bulk_update_requests_helper.rb +++ b/app/helpers/bulk_update_requests_helper.rb @@ -94,7 +94,7 @@ module BulkUpdateRequestsHelper "#{btag}remove implication " + link_to(arg1, posts_path(:tags => arg1)) + " (#{arg1_count}) -> " + link_to(arg2, posts_path(:tags => arg2)) + " (#{arg2_count})#{etag}" when :mass_update - "#{btag}mass update " + link_to(arg1, posts_path(:tags => arg1)) + " -> " + link_to(arg2, posts_path(:tags => arg2)) + "#{etag}" + "#{btag}mass update " + link_to(arg1, posts_path(:tags => arg1)) + " -> " + link_to(arg2, posts_path(:tags => arg2)) + etag.to_s when :change_category arg1_count = Tag.find_by_name(arg1).try(:post_count).to_i diff --git a/app/helpers/pagination_helper.rb b/app/helpers/pagination_helper.rb index 7289549cc..1930adf07 100644 --- a/app/helpers/pagination_helper.rb +++ b/app/helpers/pagination_helper.rb @@ -54,7 +54,7 @@ module PaginationHelper else html << numbered_paginator_item(1, records.current_page) html << numbered_paginator_item("...", records.current_page) - if records.size > 0 + if records.present? right_window = records.current_page + window else right_window = records.current_page @@ -62,13 +62,13 @@ module PaginationHelper (records.current_page - window).upto(right_window) do |page| html << numbered_paginator_item(page, records.current_page) end - if records.size > 0 + if records.present? html << numbered_paginator_item("...", records.current_page) html << numbered_paginator_final_item(records.total_pages, records.current_page) end end - if records.current_page < records.total_pages && records.size > 0 + if records.current_page < records.total_pages && records.present? html << "
  • " + link_to(content_tag(:i, nil, class: "fas fa-chevron-right"), nav_params_for(records.current_page + 1), rel: "next", id: "paginator-next", "data-shortcut": "d right") + "
  • " else html << "
  • " + content_tag(:i, nil, class: "fas fa-chevron-right") + "
  • " @@ -93,7 +93,7 @@ module PaginationHelper if page == "..." html << "
  • " html << content_tag(:i, nil, class: "fas fa-ellipsis-h") - html << "
  • " + html << "" elsif page == current_page html << "
  • " html << '' + page.to_s + '' diff --git a/app/helpers/posts_helper.rb b/app/helpers/posts_helper.rb index 3bde965c6..d7726fae3 100644 --- a/app/helpers/posts_helper.rb +++ b/app/helpers/posts_helper.rb @@ -23,7 +23,7 @@ module PostsHelper def missed_post_search_count_js return nil unless post_search_counts_enabled? - + if params[:ms] == "1" && @post_set.post_count == 0 && @post_set.is_single_tag? session_id = session.id verifier = ActiveSupport::MessageVerifier.new(Danbooru.config.reportbooru_key, serializer: JSON, digest: "SHA256") @@ -34,7 +34,7 @@ module PostsHelper def post_search_count_js return nil unless post_search_counts_enabled? - + if params[:action] == "index" && params[:page].nil? tags = Tag.scan_query(params[:tags]).sort.join(" ") @@ -68,7 +68,7 @@ module PostsHelper end def post_favlist(post) - post.favorited_users.reverse_each.map{|user| link_to_user(user)}.join(", ").html_safe + post.favorited_users.reverse_each.map {|user| link_to_user(user)}.join(", ").html_safe end def has_parent_message(post, parent_post_set) @@ -81,7 +81,7 @@ module PostsHelper sibling_count = parent_post_set.children.count - 1 if sibling_count > 0 html << " and has " - text = sibling_count == 1 ? "a sibling" : "#{sibling_count} siblings" + text = (sibling_count == 1) ? "a sibling" : "#{sibling_count} siblings" html << link_to(text, posts_path(:tags => "parent:#{post.parent_id}")) end @@ -96,7 +96,7 @@ module PostsHelper html = "" html << "This post has " - text = children_post_set.children.count == 1 ? "a child" : "#{children_post_set.children.count} children" + text = (children_post_set.children.count == 1) ? "a child" : "#{children_post_set.children.count} children" html << link_to(text, posts_path(:tags => "parent:#{post.id}")) html << " (#{link_to_wiki "learn more", "help:post_relationships"}) " @@ -111,9 +111,9 @@ module PostsHelper end def is_pool_selected?(pool) - return false if params.has_key?(:q) - return false if params.has_key?(:favgroup_id) - return false if !params.has_key?(:pool_id) + return false if params.key?(:q) + return false if params.key?(:favgroup_id) + return false if !params.key?(:pool_id) return params[:pool_id].to_i == pool.id end diff --git a/app/helpers/uploads_helper.rb b/app/helpers/uploads_helper.rb index 8840d6103..34e38e7bb 100644 --- a/app/helpers/uploads_helper.rb +++ b/app/helpers/uploads_helper.rb @@ -7,11 +7,11 @@ module UploadsHelper when /\Aerror: / search_params = params[:search].permit! - link_to(upload.sanitized_status, uploads_path(search: search_params.merge({ status: upload.sanitized_status }))) + link_to(upload.sanitized_status, uploads_path(search: search_params.merge(status: upload.sanitized_status))) else search_params = params[:search].permit! - link_to(upload.status, uploads_path(search: search_params.merge({ status: upload.status }))) + link_to(upload.status, uploads_path(search: search_params.merge(status: upload.status))) end end end diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb index 86298326b..5ba80cbf3 100644 --- a/app/helpers/users_helper.rb +++ b/app/helpers/users_helper.rb @@ -1,6 +1,6 @@ module UsersHelper def email_sig(user) verifier = ActiveSupport::MessageVerifier.new(Danbooru.config.email_key, serializer: JSON, digest: "SHA256") - verifier.generate("#{user.id}") + verifier.generate(user.id.to_s) end end diff --git a/app/helpers/wiki_page_versions_helper.rb b/app/helpers/wiki_page_versions_helper.rb index 44b1b3ba6..0f0d7e3f2 100644 --- a/app/helpers/wiki_page_versions_helper.rb +++ b/app/helpers/wiki_page_versions_helper.rb @@ -8,7 +8,7 @@ module WikiPageVersionsHelper status = [] status += ["Renamed"] if cur.title != prev.title status += ["Deleted"] if cur.is_deleted? && !prev.is_deleted? - status += ["Undeleted"] if !cur.is_deleted? && prev.is_deleted? + status += ["Undeleted"] if !cur.is_deleted? && prev.is_deleted? status.join(" ") end @@ -27,15 +27,15 @@ module WikiPageVersionsHelper cbo = Diff::LCS::ContextDiffCallbacks.new diffs = thisarr.diff(otharr, cbo) - escape_html = ->(str) {str.gsub(/&/,'&').gsub(//,'>')} + escape_html = ->(str) {str.gsub(/&/, '&').gsub(//, '>')} output = thisarr output.each { |q| q.replace(escape_html[q]) } diffs.reverse_each do |hunk| - newchange = hunk.max{|a,b| a.old_position <=> b.old_position} + newchange = hunk.max {|a, b| a.old_position <=> b.old_position} newstart = newchange.old_position - oldstart = hunk.min{|a,b| a.old_position <=> b.old_position}.old_position + oldstart = hunk.min {|a, b| a.old_position <=> b.old_position}.old_position if newchange.action == '+' output.insert(newstart, '') @@ -50,7 +50,7 @@ module WikiPageVersionsHelper if chg.new_element.match(/^\r?\n$/) output.insert(chg.old_position, '
    ') else - output.insert(chg.old_position, "#{escape_html[chg.new_element]}") + output.insert(chg.old_position, (escape_html[chg.new_element]).to_s) end end end @@ -60,7 +60,7 @@ module WikiPageVersionsHelper end if hunk[0].action == '-' - output.insert((newstart == oldstart || newchange.action != '+') ? newstart+1 : newstart, '') + output.insert((newstart == oldstart || newchange.action != '+') ? newstart + 1 : newstart, '') output.insert(oldstart, '') end end diff --git a/app/helpers/wiki_pages_helper.rb b/app/helpers/wiki_pages_helper.rb index daa3b2d40..7529d8109 100644 --- a/app/helpers/wiki_pages_helper.rb +++ b/app/helpers/wiki_pages_helper.rb @@ -11,14 +11,14 @@ module WikiPagesHelper html << "

    Posts (#{full_link})

    " html << wiki_page.post_set.presenter.post_previews_html(self) end - + html << "" html.html_safe end def wiki_page_other_names_list(wiki_page) - names_html = wiki_page.other_names.map{|name| link_to(name, "http://www.pixiv.net/search.php?s_mode=s_tag_full&word=#{u(name)}", :class => "wiki-other-name")} + names_html = wiki_page.other_names.map {|name| link_to(name, "http://www.pixiv.net/search.php?s_mode=s_tag_full&word=#{u(name)}", :class => "wiki-other-name")} names_html.join(" ").html_safe end end diff --git a/app/jobs/tag_batch_change_job.rb b/app/jobs/tag_batch_change_job.rb index fd03c6247..fc7f1ddca 100644 --- a/app/jobs/tag_batch_change_job.rb +++ b/app/jobs/tag_batch_change_job.rb @@ -1,5 +1,5 @@ class TagBatchChangeJob < ApplicationJob - class Error < Exception ; end + class Error < Exception; end queue_as :default diff --git a/app/jobs/upload_preprocessor_delayed_start_job.rb b/app/jobs/upload_preprocessor_delayed_start_job.rb index fb2541822..25356b201 100644 --- a/app/jobs/upload_preprocessor_delayed_start_job.rb +++ b/app/jobs/upload_preprocessor_delayed_start_job.rb @@ -1,6 +1,6 @@ class UploadPreprocessorDelayedStartJob < ApplicationJob queue_as :default - queue_with_priority -1 + queue_with_priority(-1) def perform(source, referer_url, uploader) UploadService::Preprocessor.new(source: source, referer_url: referer_url).delayed_start(uploader.id) diff --git a/app/jobs/upload_service_delayed_start_job.rb b/app/jobs/upload_service_delayed_start_job.rb index 916d9c2d3..21712822c 100644 --- a/app/jobs/upload_service_delayed_start_job.rb +++ b/app/jobs/upload_service_delayed_start_job.rb @@ -1,6 +1,6 @@ class UploadServiceDelayedStartJob < ApplicationJob queue_as :default - queue_with_priority -1 + queue_with_priority(-1) def perform(uploader) UploadService.delayed_start(uploader.id) diff --git a/app/logical/alias_and_implication_importer.rb b/app/logical/alias_and_implication_importer.rb index 25793320d..bbfdc0441 100644 --- a/app/logical/alias_and_implication_importer.rb +++ b/app/logical/alias_and_implication_importer.rb @@ -120,7 +120,7 @@ class AliasAndImplicationImporter end end -private + private def parse(tokens, approver) ActiveRecord::Base.transaction do diff --git a/app/logical/apng_inspector.rb b/app/logical/apng_inspector.rb index dffad8081..4921c226a 100644 --- a/app/logical/apng_inspector.rb +++ b/app/logical/apng_inspector.rb @@ -9,36 +9,35 @@ class APNGInspector @animated = false end - #PNG file consists of 8-byte magic number, followed by arbitrary number of chunks - #Each chunk has the following structure: - #4-byte length (unsigned int, can be zero) - #4-byte name (ASCII string consisting of letters A-z) - #(length)-byte data - #4-byte CRC + # PNG file consists of 8-byte magic number, followed by arbitrary number of chunks + # Each chunk has the following structure: + # 4-byte length (unsigned int, can be zero) + # 4-byte name (ASCII string consisting of letters A-z) + # (length)-byte data + # 4-byte CRC # - #Any data after chunk named IEND is irrelevant - #APNG frame count is inside a chunk named acTL, in first 4 bytes of data. + # Any data after chunk named IEND is irrelevant + # APNG frame count is inside a chunk named acTL, in first 4 bytes of data. - - #This function calls associated block for each PNG chunk - #parameters passed are |chunk_name, chunk_length, file_descriptor| - #returns true if file is read succesfully from start to IEND, - #or if 100 000 chunks are read; returns false otherwise. + # This function calls associated block for each PNG chunk + # parameters passed are |chunk_name, chunk_length, file_descriptor| + # returns true if file is read succesfully from start to IEND, + # or if 100 000 chunks are read; returns false otherwise. def each_chunk iend_reached = false File.open(@file_path, 'rb') do |file| - #check if file is not PNG at all + # check if file is not PNG at all return false if file.read(8) != PNG_MAGIC_NUMBER chunks = 0 - #We could be dealing with large number of chunks, - #so the code should be optimized to create as few objects as possible. - #All literal strings are frozen and read() function uses string buffer. + # We could be dealing with large number of chunks, + # so the code should be optimized to create as few objects as possible. + # All literal strings are frozen and read() function uses string buffer. chunkheader = '' while file.read(8, chunkheader) - #ensure that first 8 bytes from chunk were read properly - if chunkheader == nil || chunkheader.length < 8 + # ensure that first 8 bytes from chunk were read properly + if chunkheader.nil? || chunkheader.length < 8 return false end @@ -48,23 +47,23 @@ class APNGInspector return false if chunk_name =~ /[^A-Za-z]/ yield chunk_name, chunk_len, file - #no need to read further if IEND is reached + # no need to read further if IEND is reached if chunk_name == "IEND".freeze iend_reached = true break end - #check if we processed too many chunks already - #if we did, file is probably maliciously formed - #fail gracefully without marking the file as corrupt + # check if we processed too many chunks already + # if we did, file is probably maliciously formed + # fail gracefully without marking the file as corrupt chunks += 1 if chunks > 100000 iend_reached = true break end - #jump to the next chunk - go forward by chunk length + 4 bytes CRC - file.seek(current_pos+chunk_len+4, IO::SEEK_SET) + # jump to the next chunk - go forward by chunk length + 4 bytes CRC + file.seek(current_pos + chunk_len + 4, IO::SEEK_SET) end end return iend_reached @@ -99,14 +98,13 @@ class APNGInspector private - #return number of frames in acTL or -1 on failure - def parse_actl(len, file) - return -1 if len != 8 - framedata = file.read(4) - if framedata == nil || framedata.length != 4 - return -1 - end - return framedata.unpack("N".freeze)[0] + # return number of frames in acTL or -1 on failure + def parse_actl(len, file) + return -1 if len != 8 + framedata = file.read(4) + if framedata.nil? || framedata.length != 4 + return -1 end - + return framedata.unpack1("N".freeze) + end end diff --git a/app/logical/approver_pruner.rb b/app/logical/approver_pruner.rb index c37586761..dd11dcc08 100644 --- a/app/logical/approver_pruner.rb +++ b/app/logical/approver_pruner.rb @@ -1,5 +1,5 @@ module ApproverPruner - extend self + module_function def inactive_approvers User.where("bit_prefs & ? > 0", User.flag_value_for("can_approve_posts")).select do |user| diff --git a/app/logical/d_text.rb b/app/logical/d_text.rb index 532b1bea5..f37c858f7 100644 --- a/app/logical/d_text.rb +++ b/app/logical/d_text.rb @@ -64,13 +64,10 @@ class DText def self.parse_embedded_tag_request_text(text) [TagAlias, TagImplication, BulkUpdateRequest].each do |tag_request| text = text.gsub(tag_request.embedded_pattern) do |match| - begin - obj = tag_request.find($~[:id]) - tag_request_message(obj) || match - - rescue ActiveRecord::RecordNotFound - match - end + obj = tag_request.find($~[:id]) + tag_request_message(obj) || match + rescue ActiveRecord::RecordNotFound + match end end @@ -143,7 +140,7 @@ class DText def self.dtext_links_differ?(a, b) Set.new(parse_wiki_titles(a)) != Set.new(parse_wiki_titles(b)) || - Set.new(parse_external_links(a)) != Set.new(parse_external_links(b)) + Set.new(parse_external_links(a)) != Set.new(parse_external_links(b)) end def self.strip_blocks(string, tag) diff --git a/app/logical/danbooru/has_bit_flags.rb b/app/logical/danbooru/has_bit_flags.rb index 66ec54008..6e7fa2ce7 100644 --- a/app/logical/danbooru/has_bit_flags.rb +++ b/app/logical/danbooru/has_bit_flags.rb @@ -36,4 +36,4 @@ module Danbooru end end end -end \ No newline at end of file +end diff --git a/app/logical/danbooru_image_resizer.rb b/app/logical/danbooru_image_resizer.rb index 2645f8dff..34db067b3 100644 --- a/app/logical/danbooru_image_resizer.rb +++ b/app/logical/danbooru_image_resizer.rb @@ -1,5 +1,5 @@ module DanbooruImageResizer - extend self + module_function # Taken from ArgyllCMS 2.0.0 (see also: https://ninedegreesbelow.com/photography/srgb-profile-comparison.html) SRGB_PROFILE = "#{Rails.root}/config/sRGB.icm" @@ -46,7 +46,6 @@ module DanbooruImageResizer end return true - ensure temp.close temp.unlink diff --git a/app/logical/danbooru_logger.rb b/app/logical/danbooru_logger.rb index 3d1208ed9..01422f727 100644 --- a/app/logical/danbooru_logger.rb +++ b/app/logical/danbooru_logger.rb @@ -39,14 +39,14 @@ class DanbooruLogger ::NewRelic::Agent.add_custom_attributes(attributes) end - private + private_class_method # flatten_hash({ foo: { bar: { baz: 42 } } }) # => { "foo.bar.baz" => 42 } def self.flatten_hash(hash) hash.each_with_object({}) do |(k, v), h| if v.is_a?(Hash) - flatten_hash(v).map do|h_k, h_v| + flatten_hash(v).map do |h_k, h_v| h["#{k}.#{h_k}"] = h_v end else diff --git a/app/logical/danbooru_math.rb b/app/logical/danbooru_math.rb index acf69b767..d7f1238c8 100644 --- a/app/logical/danbooru_math.rb +++ b/app/logical/danbooru_math.rb @@ -4,8 +4,8 @@ class DanbooruMath return 0 end - z = Statistics2.pnormaldist(1-(1-confidence)/2) - phat = 1.0*pos/n - 100 * (phat + z*z/(2*n) - z * Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n) + z = Statistics2.pnormaldist(1 - (1 - confidence) / 2) + phat = 1.0 * pos / n + 100 * (phat + z * z / (2 * n) - z * Math.sqrt((phat * (1 - phat) + z * z / (4 * n)) / n)) / (1 + z * z / n) end end diff --git a/app/logical/deviant_art_api_client.rb b/app/logical/deviant_art_api_client.rb index 52607d6fe..3b8c35734 100644 --- a/app/logical/deviant_art_api_client.rb +++ b/app/logical/deviant_art_api_client.rb @@ -3,7 +3,7 @@ # API requests must send a user agent and must use gzip compression, otherwise # 403 errors will be returned. -class DeviantArtApiClient < Struct.new(:deviation_id) +DeviantArtApiClient = Struct.new(:deviation_id) do extend Memoist def extended_fetch diff --git a/app/logical/downloads/file.rb b/app/logical/downloads/file.rb index 71ebcd54b..0e7e8ebbc 100644 --- a/app/logical/downloads/file.rb +++ b/app/logical/downloads/file.rb @@ -3,7 +3,7 @@ require 'resolv' module Downloads class File include ActiveModel::Validations - class Error < Exception ; end + class Error < Exception; end RETRIABLE_ERRORS = [Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EIO, Errno::EHOSTUNREACH, Errno::ECONNREFUSED, Timeout::Error, IOError] @@ -12,7 +12,7 @@ module Downloads validate :validate_url - def initialize(url, referer=nil) + def initialize(url, referer = nil) @url = Addressable::URI.parse(url) rescue nil @referer = referer validate! @@ -59,7 +59,7 @@ module Downloads else raise Error.new("HTTP error code: #{res.code} #{res.message}") end - end # def + end # Prevent Cloudflare from potentially mangling the image. See issue #3528. def uncached_url @@ -87,7 +87,7 @@ module Downloads timeout: 10, stream_body: true, headers: strategy.headers, - connection_adapter: ValidatingConnectionAdapter, + connection_adapter: ValidatingConnectionAdapter }.deep_merge(Danbooru.config.httparty_options) end diff --git a/app/logical/forum_updater.rb b/app/logical/forum_updater.rb index c2b81441f..36122e08f 100644 --- a/app/logical/forum_updater.rb +++ b/app/logical/forum_updater.rb @@ -10,7 +10,7 @@ class ForumUpdater def update(message, title_tag = nil) return if forum_topic.nil? - + CurrentUser.scoped(User.system) do create_response(message) update_title(title_tag) if title_tag diff --git a/app/logical/moderator/ip_addr_search.rb b/app/logical/moderator/ip_addr_search.rb index 26a7ebe60..06908735d 100644 --- a/app/logical/moderator/ip_addr_search.rb +++ b/app/logical/moderator/ip_addr_search.rb @@ -18,7 +18,8 @@ module Moderator end end - private + private + def search_by_ip_addr(ip_addrs) sums = Hash.new {|h, k| h[k] = 0} diff --git a/app/logical/nico_seiga_api_client.rb b/app/logical/nico_seiga_api_client.rb index 600f68f11..cb596a34e 100644 --- a/app/logical/nico_seiga_api_client.rb +++ b/app/logical/nico_seiga_api_client.rb @@ -21,7 +21,7 @@ class NicoSeigaApiClient form["password"] = Danbooru.config.nico_seiga_password end.click_button end - session = mech.cookie_jar.cookies.select{|c| c.name == "user_session"}.first + session = mech.cookie_jar.cookies.select {|c| c.name == "user_session"}.first if session Cache.put("nico-seiga-session", session.value, 1.week) else @@ -74,7 +74,7 @@ class NicoSeigaApiClient def get(url) response = Danbooru::Http.cache(1.minute).get(url) - raise "nico seiga api call failed (code=#{response.code}, body=#{response.body.to_s})" if response.code != 200 + raise "nico seiga api call failed (code=#{response.code}, body=#{response.body})" if response.code != 200 Hash.from_xml(response.to_s) end diff --git a/app/logical/nico_seiga_manga_api_client.rb b/app/logical/nico_seiga_manga_api_client.rb index ecc900b8f..4bdb6a7f4 100644 --- a/app/logical/nico_seiga_manga_api_client.rb +++ b/app/logical/nico_seiga_manga_api_client.rb @@ -51,7 +51,7 @@ class NicoSeigaMangaApiClient def get(url) response = Danbooru::Http.cache(1.minute).get(url) - raise "nico seiga api call failed (code=#{response.code}, body=#{response.body.to_s})" if response.code != 200 + raise "nico seiga api call failed (code=#{response.code}, body=#{response.body})" if response.code != 200 Hash.from_xml(response.to_s) end diff --git a/app/logical/note_sanitizer.rb b/app/logical/note_sanitizer.rb index 65c22f0b9..099a161b8 100644 --- a/app/logical/note_sanitizer.rb +++ b/app/logical/note_sanitizer.rb @@ -10,7 +10,7 @@ module NoteSanitizer "span" => %w(class), "div" => %w(class align), "p" => %w(class align), - "font" => %w(color size), + "font" => %w(color size) } ALLOWED_PROPERTIES = %w( @@ -61,7 +61,7 @@ module NoteSanitizer :elements => ALLOWED_ELEMENTS, :attributes => ALLOWED_ATTRIBUTES, :add_attributes => { - "a" => { "rel" => "external noreferrer nofollow" }, + "a" => { "rel" => "external noreferrer nofollow" } }, :protocols => { "a" => { @@ -73,9 +73,9 @@ module NoteSanitizer allow_hacks: false, at_rules: [], protocols: [], - properties: ALLOWED_PROPERTIES, + properties: ALLOWED_PROPERTIES }, - :transformers => method(:relativize_links), + :transformers => method(:relativize_links) ) end diff --git a/app/logical/pagination_extension.rb b/app/logical/pagination_extension.rb index 6dd5359fe..fbc518ef1 100644 --- a/app/logical/pagination_extension.rb +++ b/app/logical/pagination_extension.rb @@ -1,5 +1,5 @@ module PaginationExtension - class PaginationError < Exception ; end + class PaginationError < Exception; end attr_accessor :current_page, :records_per_page, :paginator_count, :paginator_mode diff --git a/app/logical/pawoo_api_client.rb b/app/logical/pawoo_api_client.rb index 7803ba2ca..48f5df6df 100644 --- a/app/logical/pawoo_api_client.rb +++ b/app/logical/pawoo_api_client.rb @@ -6,7 +6,7 @@ class PawooApiClient STATUS1 = %r!\Ahttps?://pawoo\.net/web/statuses/(\d+)! STATUS2 = %r!\Ahttps?://pawoo\.net/@.+?/([^/]+)! - class MissingConfigurationError < Exception ; end + class MissingConfigurationError < Exception; end class Account attr_reader :json diff --git a/app/logical/pixiv_api_client.rb b/app/logical/pixiv_api_client.rb index ea52067ce..3b385d2d3 100644 --- a/app/logical/pixiv_api_client.rb +++ b/app/logical/pixiv_api_client.rb @@ -23,8 +23,8 @@ class PixivApiClient VistaPro Sculptris Comi\ Po! modo DAZ\ Studio 3D-Coat ] - class Error < Exception ; end - class BadIDError < Error ; end + class Error < Exception; end + class BadIDError < Error; end class WorkResponse attr_reader :json, :pages, :name, :moniker, :user_id, :page_count, :tags @@ -93,7 +93,7 @@ class PixivApiClient end def pages - # ex: + # ex: # https://i.pximg.net/c/150x150_80/novel-cover-master/img/2017/07/27/23/14/17/8465454_80685d10e6df4d7d53ad347ddc18a36b_master1200.jpg (6096b) # => # https://i.pximg.net/novel-cover-original/img/2017/07/27/23/14/17/8465454_80685d10e6df4d7d53ad347ddc18a36b.jpg (532129b) @@ -101,7 +101,8 @@ class PixivApiClient end memoize :pages - public + public + PXIMG = %r!\Ahttps?://i\.pximg\.net/c/\d+x\d+_\d+/novel-cover-master/img/(?\d+/\d+/\d+/\d+/\d+/\d+)/(?\d+_[a-f0-9]+)_master\d+\.(?jpg|jpeg|png|gif)!i def find_original(x) @@ -123,7 +124,7 @@ class PixivApiClient def name json["body"]["user"]["name"] end - + def user_id json["body"]["user"]["userId"] end @@ -177,11 +178,10 @@ class PixivApiClient elsif json["status"] == "failure" && json.dig("errors", "system", "message") =~ /対象のイラストは見つかりませんでした。/ raise BadIDError.new("Pixiv ##{illust_id} not found: work was deleted, made private, or ID is invalid.") else - raise Error.new("Pixiv API call failed (status=#{response.code} body=#{response.body.to_s})") + raise Error.new("Pixiv API call failed (status=#{response.code} body=#{response.body})") end - rescue JSON::ParserError - raise Error.new("Pixiv API call failed (status=#{response.code} body=#{response.body.to_s})") + raise Error.new("Pixiv API call failed (status=#{response.code} body=#{response.body})") end def fanbox(fanbox_id) @@ -228,14 +228,14 @@ class PixivApiClient headers = { "Referer": "http://www.pixiv.net", "X-Client-Time": client_time, - "X-Client-Hash": client_hash, + "X-Client-Hash": client_hash } params = { username: Danbooru.config.pixiv_login, password: Danbooru.config.pixiv_password, grant_type: "password", client_id: CLIENT_ID, - client_secret: CLIENT_SECRET, + client_secret: CLIENT_SECRET } url = "https://oauth.secure.pixiv.net/auth/token" diff --git a/app/logical/pixiv_ugoira_converter.rb b/app/logical/pixiv_ugoira_converter.rb index ecf30e3e4..51762e206 100644 --- a/app/logical/pixiv_ugoira_converter.rb +++ b/app/logical/pixiv_ugoira_converter.rb @@ -16,7 +16,7 @@ class PixivUgoiraConverter path = File.join(tmpdir, "images", file.name) file.extract(path) end - + # Duplicate last frame to avoid it being displayed only for a very short amount of time. last_file_name = folder.to_a.last.name last_file_name =~ /\A(\d{6})(\.\w{,4})\Z/ @@ -26,7 +26,7 @@ class PixivUgoiraConverter path_from = File.join(tmpdir, "images", last_file_name) path_to = File.join(tmpdir, "images", new_last_filename) FileUtils.cp(path_from, path_to) - + delay_sum = 0 timecodes_path = File.join(tmpdir, "timecodes.tc") File.open(timecodes_path, "w+") do |f| @@ -50,7 +50,6 @@ class PixivUgoiraConverter Rails.logger.error "[write_webm][ffmpeg] #{line}" end Rails.logger.error "[write_webm] ******************************" - return end mkvmerge_out, status = Open3.capture2e("mkvmerge -o #{write_path} --webm --timecodes 0:#{tmpdir}/timecodes.tc #{tmpdir}/tmp.webm") @@ -63,7 +62,6 @@ class PixivUgoiraConverter Rails.logger.error "[write_webm][mkvmerge] #{line}" end Rails.logger.error "[write_webm] ******************************" - return end end diff --git a/app/logical/pixiv_web_agent.rb b/app/logical/pixiv_web_agent.rb index adccbd872..f48a20c50 100644 --- a/app/logical/pixiv_web_agent.rb +++ b/app/logical/pixiv_web_agent.rb @@ -5,7 +5,7 @@ class PixivWebAgent COMIC_SESSION_COOKIE_KEY = "_pixiv-comic_session" def self.phpsessid(agent) - agent.cookies.select do |cookie| cookie.name == SESSION_COOKIE_KEY end.first.try(:value) + agent.cookies.select { |cookie| cookie.name == SESSION_COOKIE_KEY }.first.try(:value) end def self.build diff --git a/app/logical/popular_search_service.rb b/app/logical/popular_search_service.rb index 71269f3ec..026684f3c 100644 --- a/app/logical/popular_search_service.rb +++ b/app/logical/popular_search_service.rb @@ -22,9 +22,9 @@ class PopularSearchService JSON.parse(fetch_data.to_s).map {|x| x[0]} end - def fetch_data() + def fetch_data return [] unless self.class.enabled? - + dates = date.strftime("%Y-%m-%d") data = Cache.get("ps-day-#{dates}", 1.minute) do @@ -54,8 +54,7 @@ class PopularSearchService end data - - rescue => e + rescue StandardError => e DanbooruLogger.log(e) return [] end diff --git a/app/logical/post_pruner.rb b/app/logical/post_pruner.rb index bb9b3802f..e3fcac856 100644 --- a/app/logical/post_pruner.rb +++ b/app/logical/post_pruner.rb @@ -5,16 +5,14 @@ class PostPruner prune_mod_actions! end -protected + protected def prune_pending! CurrentUser.scoped(User.system, "127.0.0.1") do Post.where("is_deleted = ? and is_pending = ? and created_at < ?", false, true, 3.days.ago).each do |post| - begin - post.delete!("Unapproved in three days") - rescue PostFlag::Error - # swallow - end + post.delete!("Unapproved in three days") + rescue PostFlag::Error + # swallow end end end diff --git a/app/logical/post_query_builder.rb b/app/logical/post_query_builder.rb index 5bf458287..abecb9c08 100644 --- a/app/logical/post_query_builder.rb +++ b/app/logical/post_query_builder.rb @@ -299,7 +299,7 @@ class PostQueryBuilder if q[:flagger_ids_neg] q[:flagger_ids_neg].each do |flagger_id| if CurrentUser.can_view_flagger?(flagger_id) - post_ids = PostFlag.unscoped.search({:creator_id => flagger_id, :category => "normal"}).reorder("").select {|flag| flag.not_uploaded_by?(CurrentUser.id)}.map {|flag| flag.post_id}.uniq + post_ids = PostFlag.unscoped.search(:creator_id => flagger_id, :category => "normal").reorder("").select {|flag| flag.not_uploaded_by?(CurrentUser.id)}.map {|flag| flag.post_id}.uniq if post_ids.any? relation = relation.where.not("posts.id": post_ids) end @@ -310,11 +310,11 @@ class PostQueryBuilder if q[:flagger_ids] q[:flagger_ids].each do |flagger_id| if flagger_id == "any" - relation = relation.where('EXISTS (' + PostFlag.unscoped.search({:category => "normal"}).where('post_id = posts.id').reorder('').select('1').to_sql + ')') + relation = relation.where('EXISTS (' + PostFlag.unscoped.search(:category => "normal").where('post_id = posts.id').reorder('').select('1').to_sql + ')') elsif flagger_id == "none" - relation = relation.where('NOT EXISTS (' + PostFlag.unscoped.search({:category => "normal"}).where('post_id = posts.id').reorder('').select('1').to_sql + ')') + relation = relation.where('NOT EXISTS (' + PostFlag.unscoped.search(:category => "normal").where('post_id = posts.id').reorder('').select('1').to_sql + ')') elsif CurrentUser.can_view_flagger?(flagger_id) - post_ids = PostFlag.unscoped.search({:creator_id => flagger_id, :category => "normal"}).reorder("").select {|flag| flag.not_uploaded_by?(CurrentUser.id)}.map {|flag| flag.post_id}.uniq + post_ids = PostFlag.unscoped.search(:creator_id => flagger_id, :category => "normal").reorder("").select {|flag| flag.not_uploaded_by?(CurrentUser.id)}.map {|flag| flag.post_id}.uniq relation = relation.where("posts.id": post_ids) end end @@ -322,7 +322,7 @@ class PostQueryBuilder if q[:appealer_ids_neg] q[:appealer_ids_neg].each do |appealer_id| - relation = relation.where.not("posts.id": PostAppeal.unscoped.where(creator_id: appealer_id).select(:post_id).distinct) + relation = relation.where.not("posts.id": PostAppeal.unscoped.where(creator_id: appealer_id).select(:post_id).distinct) end end diff --git a/app/logical/post_sets/post.rb b/app/logical/post_sets/post.rb index 07fa4f05e..7edf5c289 100644 --- a/app/logical/post_sets/post.rb +++ b/app/logical/post_sets/post.rb @@ -78,7 +78,7 @@ module PostSets end def hidden_posts - posts.select { |p| !p.visible? } + posts.reject { |p| p.visible? } end def banned_posts @@ -122,17 +122,17 @@ module PostSets def posts @posts ||= begin - @post_count = get_post_count() + @post_count = get_post_count if is_random? - temp = get_random_posts() + temp = get_random_posts elsif raw temp = ::Post.raw_tag_match(tag_string).order("posts.id DESC").where("true /* PostSets::Post#posts:1 */").paginate(page, :count => post_count, :limit => per_page) else temp = ::Post.tag_match(tag_string).where("true /* PostSets::Post#posts:2 */").paginate(page, :count => post_count, :limit => per_page) end - # XXX HACK: uploader_name is needed in api responses and in data-uploader attribs (visible to mods only). + # HACK: uploader_name is needed in api responses and in data-uploader attribs (visible to mods only). temp = temp.includes(:uploader) if !is_random? && (format.to_sym != :html || CurrentUser.is_moderator?) temp.each # hack to force rails to eager load @@ -159,11 +159,11 @@ module PostSets end def is_empty_tag? - tag_array.size == 0 + tag_array.empty? end def is_pattern_search? - is_single_tag? && tag_string =~ /\*/ && !tag_array.any? {|x| x =~ /^-?source:.+/} + is_single_tag? && tag_string =~ /\*/ && tag_array.none? {|x| x =~ /^-?source:.+/} end def current_page diff --git a/app/logical/post_sets/recommended.rb b/app/logical/post_sets/recommended.rb index 87b17803c..9d1825ded 100644 --- a/app/logical/post_sets/recommended.rb +++ b/app/logical/post_sets/recommended.rb @@ -1,7 +1,7 @@ module PostSets class Recommended < PostSets::Post attr_reader :posts - + def initialize(posts) super("") @posts = posts diff --git a/app/logical/related_tag_calculator.rb b/app/logical/related_tag_calculator.rb index 4ac42aaad..e375fd567 100644 --- a/app/logical/related_tag_calculator.rb +++ b/app/logical/related_tag_calculator.rb @@ -9,7 +9,7 @@ module RelatedTagCalculator tags = frequent_tags_for_search(tag_query, search_sample_size: search_sample_size, category: category).limit(tag_sample_size) tags = tags.sort_by do |tag| # cosine distance(tag1, tag2) = 1 - {{tag1 tag2}} / sqrt({{tag1}} * {{tag2}}) - 1 - tag.overlap_count / (Math.sqrt(tag.post_count * search_count.to_f)) + 1 - tag.overlap_count / Math.sqrt(tag.post_count * search_count.to_f) end tags diff --git a/app/logical/related_tag_query.rb b/app/logical/related_tag_query.rb index 3981085f6..9527541e8 100644 --- a/app/logical/related_tag_query.rb +++ b/app/logical/related_tag_query.rb @@ -68,7 +68,7 @@ class RelatedTagQuery } end -protected + protected def tags_with_categories(list_of_tag_names) Tag.categories_for(list_of_tag_names).to_a diff --git a/app/logical/reports/upload_tags.rb b/app/logical/reports/upload_tags.rb index c7b4ab3aa..d49996079 100644 --- a/app/logical/reports/upload_tags.rb +++ b/app/logical/reports/upload_tags.rb @@ -47,6 +47,5 @@ module Reports def removed_tags removed_tags_array.join(' ') end - end end diff --git a/app/logical/reports/uploads.rb b/app/logical/reports/uploads.rb index d786f933d..2fbfd0a72 100644 --- a/app/logical/reports/uploads.rb +++ b/app/logical/reports/uploads.rb @@ -14,7 +14,7 @@ module Reports else @max_date = Date.today end - + @queries = queries.to_s.split(/,\s*/).join(",") end diff --git a/app/logical/reports/user_promotions.rb b/app/logical/reports/user_promotions.rb index 3b763b02b..edbf75a3d 100644 --- a/app/logical/reports/user_promotions.rb +++ b/app/logical/reports/user_promotions.rb @@ -56,9 +56,9 @@ module Reports return 0 end - z = Statistics2.pnormaldist(1-(1-confidence)/2) - phat = 1.0*pos/n - 100 * (phat + z*z/(2*n) - z * Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n) + z = Statistics2.pnormaldist(1 - (1 - confidence) / 2) + phat = 1.0 * pos / n + 100 * (phat + z * z / (2 * n) - z * Math.sqrt((phat * (1 - phat) + z * z / (4 * n)) / n)) / (1 + z * z / n) end def self.min_time diff --git a/app/logical/session_loader.rb b/app/logical/session_loader.rb index 25c9c4438..be4368f5e 100644 --- a/app/logical/session_loader.rb +++ b/app/logical/session_loader.rb @@ -1,5 +1,5 @@ class SessionLoader - class AuthenticationFailure < Exception ; end + class AuthenticationFailure < Exception; end attr_reader :session, :cookies, :request, :params @@ -37,7 +37,7 @@ class SessionLoader request.authorization.present? || params[:login].present? || params[:api_key].present? || params[:password_hash].present? end -private + private def set_statement_timeout timeout = CurrentUser.user.statement_timeout diff --git a/app/logical/set_diff.rb b/app/logical/set_diff.rb index f04f0e05a..3bc4b288e 100644 --- a/app/logical/set_diff.rb +++ b/app/logical/set_diff.rb @@ -30,6 +30,6 @@ class SetDiff distance = ->(other) { ::DidYouMean::Levenshtein.distance(string, other) } max_distance = string.size * max_dissimilarity - candidates.select { |candidate| distance[candidate] <= max_distance }.sort_by(&distance).first + candidates.select { |candidate| distance[candidate] <= max_distance }.min_by(&distance) end end diff --git a/app/logical/sources/strategies.rb b/app/logical/sources/strategies.rb index 282c9705f..2c0982f2c 100644 --- a/app/logical/sources/strategies.rb +++ b/app/logical/sources/strategies.rb @@ -10,11 +10,11 @@ module Sources Strategies::ArtStation, Strategies::Nijie, Strategies::Pawoo, - Strategies::Moebooru, + Strategies::Moebooru ] end - def self.find(url, referer=nil, default: Strategies::Null) + def self.find(url, referer = nil, default: Strategies::Null) strategy = all.map { |strategy| strategy.new(url, referer) }.detect(&:match?) strategy || default&.new(url, referer) end diff --git a/app/logical/sources/strategies/art_station.rb b/app/logical/sources/strategies/art_station.rb index f558af1b3..4f3181d10 100644 --- a/app/logical/sources/strategies/art_station.rb +++ b/app/logical/sources/strategies/art_station.rb @@ -27,7 +27,7 @@ module Sources::Strategies ASSET = %r!\Ahttps?://cdn\w*\.artstation\.com/p/assets/images/images/\d+/\d+/\d+/(?:medium|small|large)/!i - attr_reader :json, :image_urls + attr_reader :json def domains ["artstation.com"] @@ -38,13 +38,11 @@ module Sources::Strategies end def image_urls - image_urls_sub - .map { |asset| original_asset_url(asset) } + @image_urls ||= image_urls_sub.map { |asset| original_asset_url(asset) } end - memoize :image_urls def page_url - return nil unless project_id.present? + return nil if project_id.blank? if artist_name.present? "https://#{artist_name}.artstation.com/projects/#{project_id}" @@ -54,7 +52,7 @@ module Sources::Strategies end def profile_url - return nil unless artist_name.present? + return nil if artist_name.blank? "https://www.artstation.com/#{artist_name}" end @@ -84,14 +82,13 @@ module Sources::Strategies profile_url.present? && url == profile_url end - public - def image_urls_sub if url.match?(ASSET) return [url] end - api_response[:assets].to_a + api_response[:assets] + .to_a .select { |asset| asset[:asset_type] == "image" } .map { |asset| asset[:image_url] } end @@ -100,7 +97,7 @@ module Sources::Strategies # purposes def artist_name_from_url - urls.map { |url| url[PROJECT, :artist_name] || url[ARTIST, :artist_name] }.compact.first + urls.map { |url| url[PROJECT, :artist_name] || url[ARTIST, :artist_name] }.compact.first end def project_id @@ -108,7 +105,7 @@ module Sources::Strategies end def api_response - return {} unless project_id.present? + return {} if project_id.blank? resp = Danbooru::Http.cache(1.minute).get("https://www.artstation.com/projects/#{project_id}.json") return {} if resp.code != 200 diff --git a/app/logical/sources/strategies/base.rb b/app/logical/sources/strategies/base.rb index 5896cc71f..0f24a5c53 100644 --- a/app/logical/sources/strategies/base.rb +++ b/app/logical/sources/strategies/base.rb @@ -1,7 +1,7 @@ -# This is a collection of strategies for extracting information about a -# resource. At a minimum it tries to extract the artist name and a canonical -# URL to download the image from. But it can also be used to normalize a URL -# for use with the artist finder. +# This is a collection of strategies for extracting information about a +# resource. At a minimum it tries to extract the artist name and a canonical +# URL to download the image from. But it can also be used to normalize a URL +# for use with the artist finder. # # Design Principles # @@ -24,11 +24,11 @@ module Sources true end - # * url - Should point to a resource suitable for - # downloading. This may sometimes point to the binary file. + # * url - Should point to a resource suitable for + # downloading. This may sometimes point to the binary file. # It may also point to the artist's profile page, in cases # where this class is being used to normalize artist urls. - # Implementations should be smart enough to detect this and + # Implementations should be smart enough to detect this and # behave accordingly. # * referer_url - Sometimes the HTML page cannot be # determined from url. You should generally pass in a @@ -63,9 +63,9 @@ module Sources nil end - # Whatever url is, this method should return the direct links - # to the canonical binary files. It should not be an HTML page. It should - # be a list of JPEG, PNG, GIF, WEBM, MP4, ZIP, etc. It is what the + # Whatever url is, this method should return the direct links + # to the canonical binary files. It should not be an HTML page. It should + # be a list of JPEG, PNG, GIF, WEBM, MP4, ZIP, etc. It is what the # downloader will fetch and save to disk. def image_urls raise NotImplementedError @@ -269,7 +269,7 @@ module Sources :tag_name => tag_name, :other_names => other_names, :profile_url => profile_url, - :profile_urls => profile_urls, + :profile_urls => profile_urls }, :artists => artists.as_json(include: :sorted_urls), :image_url => image_url, @@ -284,18 +284,16 @@ module Sources :title => artist_commentary_title, :description => artist_commentary_desc, :dtext_title => dtext_artist_commentary_title, - :dtext_description => dtext_artist_commentary_desc, + :dtext_description => dtext_artist_commentary_desc }, - :api_response => api_response.to_h, + :api_response => api_response.to_h } end - def to_json + def to_json(*_args) to_h.to_json end - protected - def http_exists?(url, headers) res = HTTParty.head(url, Danbooru.config.httparty_options.deep_merge(headers: headers)) res.success? @@ -306,7 +304,7 @@ module Sources def self.to_dtext(text) text = text.to_s text = Rails::Html::FullSanitizer.new.sanitize(text, encode_special_chars: false) - text = CGI::unescapeHTML(text) + text = CGI.unescapeHTML(text) text end end diff --git a/app/logical/sources/strategies/deviant_art.rb b/app/logical/sources/strategies/deviant_art.rb index 7db3501c1..f8e3306e9 100644 --- a/app/logical/sources/strategies/deviant_art.rb +++ b/app/logical/sources/strategies/deviant_art.rb @@ -57,8 +57,6 @@ module Sources PATH_PROFILE = %r{\Ahttps?://(www\.)?deviantart\.com/#{ARTIST}/?\z}i SUBDOMAIN_PROFILE = %r{\Ahttps?://#{ARTIST}\.deviantart\.com/?\z}i - attr_accessor :api_client - def domains ["deviantart.net", "deviantart.com"] end @@ -211,8 +209,6 @@ module Sources end.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "") end - public - def self.deviation_id_from_url(url) if url =~ ASSET $~[:base36_deviation_id].try(:to_i, 36) diff --git a/app/logical/sources/strategies/nico_seiga.rb b/app/logical/sources/strategies/nico_seiga.rb index 11a324c4f..d4741b283 100644 --- a/app/logical/sources/strategies/nico_seiga.rb +++ b/app/logical/sources/strategies/nico_seiga.rb @@ -130,8 +130,6 @@ module Sources end memoize :tags - public - def api_client if illust_id NicoSeigaApiClient.new(illust_id: illust_id) diff --git a/app/logical/sources/strategies/nijie.rb b/app/logical/sources/strategies/nijie.rb index 5435c229a..0898416d4 100644 --- a/app/logical/sources/strategies/nijie.rb +++ b/app/logical/sources/strategies/nijie.rb @@ -120,9 +120,11 @@ module Sources def tags links = page&.search("div#view-tag a") || [] - links.select do |node| + search_links = links.select do |node| node["href"] =~ /search\.php/ - end.map do |node| + end + + search_links.map do |node| [node.inner_text, "https://nijie.info" + node.attr("href")] end end @@ -131,8 +133,6 @@ module Sources "nijie" + artist_id.to_s end - public - def self.to_dtext(text) text = text.to_s.gsub(/\r\n|\r/, "
    ") DText.from_html(text).strip @@ -196,7 +196,7 @@ module Sources form['password'] = Danbooru.config.nijie_password end.click_button end - session = mech.cookie_jar.cookies.select{|c| c.name == "NIJIEIJIEID"}.first + session = mech.cookie_jar.cookies.select {|c| c.name == "NIJIEIJIEID"}.first Cache.put("nijie-session", session.value, 1.day) if session end @@ -207,7 +207,6 @@ module Sources mech.cookie_jar.add(cookie) mech - rescue Mechanize::ResponseCodeError => x if x.response_code.to_i == 429 sleep(5) diff --git a/app/logical/sources/strategies/pawoo.rb b/app/logical/sources/strategies/pawoo.rb index 037a0903d..3f6c7a3c7 100644 --- a/app/logical/sources/strategies/pawoo.rb +++ b/app/logical/sources/strategies/pawoo.rb @@ -85,8 +85,6 @@ module Sources::Strategies end.strip end - public - def api_response [url, referer_url].each do |x| if client = PawooApiClient.new.get(x) diff --git a/app/logical/sources/strategies/pixiv.rb b/app/logical/sources/strategies/pixiv.rb index d42d38fe5..786c704f4 100644 --- a/app/logical/sources/strategies/pixiv.rb +++ b/app/logical/sources/strategies/pixiv.rb @@ -69,7 +69,7 @@ module Sources if text.nil? return nil end - + text = text.gsub(%r!https?://www\.pixiv\.net/member_illust\.php\?mode=medium&illust_id=([0-9]+)!i) do |match| pixiv_id = $1 %(pixiv ##{pixiv_id} "»":[/posts?tags=pixiv:#{pixiv_id}]) @@ -132,11 +132,10 @@ module Sources end return url - rescue PixivApiClient::BadIDError nil end - + def canonical_url return image_url end @@ -183,7 +182,7 @@ module Sources rescue PixivApiClient::BadIDError nil end - + def headers if fanbox_id.present? # need the session to download fanbox images @@ -236,8 +235,6 @@ module Sources illust_id.present? ? "pixiv:#{illust_id}" : "source:#{canonical_url}" end - public - def image_urls_sub if url =~ FANBOX_IMAGE return [url] diff --git a/app/logical/sources/strategies/tumblr.rb b/app/logical/sources/strategies/tumblr.rb index a434321b4..d3469d9db 100644 --- a/app/logical/sources/strategies/tumblr.rb +++ b/app/logical/sources/strategies/tumblr.rb @@ -131,8 +131,6 @@ module Sources::Strategies DText.from_html(artist_commentary_desc).strip end - public - # Look for the biggest available version on media.tumblr.com. A bigger # version may or may not exist. # @@ -181,7 +179,7 @@ module Sources::Strategies response = Danbooru::Http.cache(1.minute).get( "https://api.tumblr.com/v2/blog/#{blog_name}/posts", - params: { id: post_id, api_key: Danbooru.config.tumblr_consumer_key }, + params: { id: post_id, api_key: Danbooru.config.tumblr_consumer_key } ) return {} if response.code != 200 diff --git a/app/logical/sources/strategies/twitter.rb b/app/logical/sources/strategies/twitter.rb index cebbafe0f..879a4f722 100644 --- a/app/logical/sources/strategies/twitter.rb +++ b/app/logical/sources/strategies/twitter.rb @@ -134,15 +134,13 @@ module Sources::Strategies url_replacements = url_replacements.to_h desc = artist_commentary_desc.unicode_normalize(:nfkc) - desc = CGI::unescapeHTML(desc) + desc = CGI.unescapeHTML(desc) desc = desc.gsub(%r!https?://t\.co/[a-zA-Z0-9]+!i, url_replacements) desc = desc.gsub(%r!#([^[:space:]]+)!, '"#\\1":[https://twitter.com/hashtag/\\1]') desc = desc.gsub(%r!@([a-zA-Z0-9_]+)!, '"@\\1":[https://twitter.com/\\1]') desc.strip end - public - def api_client TwitterApiClient.new(Danbooru.config.twitter_api_key, Danbooru.config.twitter_api_secret) end diff --git a/app/logical/spam_detector.rb b/app/logical/spam_detector.rb index 53eee1fbc..21f0cdbbf 100644 --- a/app/logical/spam_detector.rb +++ b/app/logical/spam_detector.rb @@ -20,7 +20,7 @@ class SpamDetector # rakismet raises an exception if the api key or url aren't configured def self.working? Rakismet.validate_key - rescue + rescue StandardError false end @@ -61,7 +61,7 @@ class SpamDetector end is_spam - rescue => exception + rescue StandardError => exception DanbooruLogger.log(exception) false end diff --git a/app/logical/sqs_service.rb b/app/logical/sqs_service.rb index 95fc7a154..8c354fe49 100644 --- a/app/logical/sqs_service.rb +++ b/app/logical/sqs_service.rb @@ -20,7 +20,8 @@ class SqsService ) end -private + private + def sqs @sqs ||= Aws::SQS::Client.new( credentials: Danbooru.config.aws_credentials, diff --git a/app/logical/storage_manager.rb b/app/logical/storage_manager.rb index 121887a0e..361fab45e 100644 --- a/app/logical/storage_manager.rb +++ b/app/logical/storage_manager.rb @@ -45,7 +45,7 @@ class StorageManager end def open_file(post, type) - open(file_path(post.md5, post.file_ext, type)) + self.open(file_path(post.md5, post.file_ext, type)) end def file_url(post, type, tagged_filenames: false) diff --git a/app/logical/storage_manager/local.rb b/app/logical/storage_manager/local.rb index 881ce7ce0..b0bfcf402 100644 --- a/app/logical/storage_manager/local.rb +++ b/app/logical/storage_manager/local.rb @@ -1,5 +1,5 @@ class StorageManager::Local < StorageManager - DEFAULT_PERMISSIONS = 0644 + DEFAULT_PERMISSIONS = 0o644 def store(io, dest_path) temp_path = dest_path + "-" + SecureRandom.uuid + ".tmp" diff --git a/app/logical/storage_manager/match.rb b/app/logical/storage_manager/match.rb index 564b71d6e..4ed2eb647 100644 --- a/app/logical/storage_manager/match.rb +++ b/app/logical/storage_manager/match.rb @@ -1,35 +1,33 @@ -=begin - -Generalizes the hybrid storage manager to be more declarative in -syntax. Matches are executed in order of appearance so the first -matching manager is returned. You should always add at least one -manager with no constraints as a default case. - +# +# Generalizes the hybrid storage manager to be more declarative in +# syntax. Matches are executed in order of appearance so the first +# matching manager is returned. You should always add at least one +# manager with no constraints as a default case. +# ### Example - - StorageManager::Match.new do |matcher| - matcher.add_manager(type: :crop) do - StorageManager::SFTP.new("raikou3.donmai.us", base_url: "https://raikou3.donmai.us", hierarchical: true, base_dir: "/var/www/raikou3") - end - - matcher.add_manager(id: 1..850_000) do - StorageManager::SFTP.new("raikou1.donmai.us", base_url: "https://raikou1.donmai.us", hierarchical: true, base_dir: "/var/www/raikou1") - end - - matcher.add_manager(id: 850_001..2_000_000) do - StorageManager::SFTP.new("raikou2.donmai.us", base_url: "https://raikou2.donmai.us", hierarchical: true, base_dir: "/var/www/raikou2") - end - - matcher.add_manager(id: 1..3_000_000, type: [:large, :original]) do - StorageManager::SFTP.new(*Danbooru.config.all_server_hosts, base_url: "https://hijiribe.donmai.us/data") - end - - matcher.add_manager({}) do - StorageManager::SFTP.new(*Danbooru.config.all_server_hosts, base_url: "#{CurrentUser.root_url}/data") - end - end - -=end +# +# StorageManager::Match.new do |matcher| +# matcher.add_manager(type: :crop) do +# StorageManager::SFTP.new("raikou3.donmai.us", base_url: "https://raikou3.donmai.us", hierarchical: true, base_dir: "/var/www/raikou3") +# end +# +# matcher.add_manager(id: 1..850_000) do +# StorageManager::SFTP.new("raikou1.donmai.us", base_url: "https://raikou1.donmai.us", hierarchical: true, base_dir: "/var/www/raikou1") +# end +# +# matcher.add_manager(id: 850_001..2_000_000) do +# StorageManager::SFTP.new("raikou2.donmai.us", base_url: "https://raikou2.donmai.us", hierarchical: true, base_dir: "/var/www/raikou2") +# end +# +# matcher.add_manager(id: 1..3_000_000, type: [:large, :original]) do +# StorageManager::SFTP.new(*Danbooru.config.all_server_hosts, base_url: "https://hijiribe.donmai.us/data") +# end +# +# matcher.add_manager({}) do +# StorageManager::SFTP.new(*Danbooru.config.all_server_hosts, base_url: "#{CurrentUser.root_url}/data") +# end +# end +# class StorageManager::Match < StorageManager def initialize @@ -56,7 +54,7 @@ class StorageManager::Match < StorageManager end if params[:type] && constraints[:type] - if constraints[:type].respond_to?(:include?) + if constraints[:type].respond_to?(:include?) if !constraints[:type].include?(params[:type]) match = false end @@ -109,4 +107,3 @@ class StorageManager::Match < StorageManager end end end - diff --git a/app/logical/storage_manager/sftp.rb b/app/logical/storage_manager/sftp.rb index add10d010..1eeb1fdce 100644 --- a/app/logical/storage_manager/sftp.rb +++ b/app/logical/storage_manager/sftp.rb @@ -1,12 +1,12 @@ class StorageManager::SFTP < StorageManager - DEFAULT_PERMISSIONS = 0644 + DEFAULT_PERMISSIONS = 0o644 # http://net-ssh.github.io/net-ssh/Net/SSH.html#method-c-start DEFAULT_SSH_OPTIONS = { timeout: 10, logger: Rails.logger, verbose: :fatal, - non_interactive: true, + non_interactive: true } attr_reader :hosts, :ssh_options @@ -22,22 +22,20 @@ class StorageManager::SFTP < StorageManager dest_backup_path = dest_path + "-" + SecureRandom.uuid + ".bak" each_host do |host, sftp| - begin - sftp.upload!(file.path, temp_upload_path) - sftp.setstat!(temp_upload_path, permissions: DEFAULT_PERMISSIONS) + sftp.upload!(file.path, temp_upload_path) + sftp.setstat!(temp_upload_path, permissions: DEFAULT_PERMISSIONS) - # `rename!` can't overwrite existing files, so if a file already exists - # at dest_path we move it out of the way first. - force { sftp.rename!(dest_path, dest_backup_path) } - force { sftp.rename!(temp_upload_path, dest_path) } - rescue StandardError => e - # if anything fails, try to move the original file back in place (if it was moved). - force { sftp.rename!(dest_backup_path, dest_path) } - raise Error, e - ensure - force { sftp.remove!(temp_upload_path) } - force { sftp.remove!(dest_backup_path) } - end + # `rename!` can't overwrite existing files, so if a file already exists + # at dest_path we move it out of the way first. + force { sftp.rename!(dest_path, dest_backup_path) } + force { sftp.rename!(temp_upload_path, dest_path) } + rescue StandardError => e + # if anything fails, try to move the original file back in place (if it was moved). + force { sftp.rename!(dest_backup_path, dest_path) } + raise Error, e + ensure + force { sftp.remove!(temp_upload_path) } + force { sftp.remove!(dest_backup_path) } end end diff --git a/app/logical/tag_alias_request.rb b/app/logical/tag_alias_request.rb index c911e74bb..f85393785 100644 --- a/app/logical/tag_alias_request.rb +++ b/app/logical/tag_alias_request.rb @@ -1,5 +1,5 @@ class TagAliasRequest - def self.command_string(antecedent_name, consequent_name, id=nil) + def self.command_string(antecedent_name, consequent_name, id = nil) if id return "[ta:#{id}]" end diff --git a/app/logical/tag_autocomplete.rb b/app/logical/tag_autocomplete.rb index 0a4184a31..31f7a473f 100644 --- a/app/logical/tag_autocomplete.rb +++ b/app/logical/tag_autocomplete.rb @@ -1,10 +1,10 @@ module TagAutocomplete - extend self + module_function PREFIX_BOUNDARIES = "(_/:;-" LIMIT = 10 - class Result < Struct.new(:name, :post_count, :category, :antecedent_name, :source) + Result = Struct.new(:name, :post_count, :category, :antecedent_name, :source) do include ActiveModel::Serializers::JSON include ActiveModel::Serializers::Xml @@ -28,7 +28,7 @@ module TagAutocomplete candidates = count_sort( query, search_exact(query, 8) + - search_prefix(query, 4) + + search_prefix(query, 4) + search_correct(query, 2) + search_aliases(query, 3) ) @@ -40,7 +40,7 @@ module TagAutocomplete end.reverse.slice(0, LIMIT) end - def search_exact(query, n=4) + def search_exact(query, n = 4) Tag .where("name like ? escape e'\\\\'", query.to_escaped_for_sql_like + "%") .where("post_count > 0") @@ -50,7 +50,7 @@ module TagAutocomplete .map {|row| Result.new(*row, nil, :exact)} end - def search_correct(query, n=2) + def search_correct(query, n = 2) if query.size <= 3 return [] end @@ -66,7 +66,7 @@ module TagAutocomplete .map {|row| Result.new(*row, nil, :correct)} end - def search_prefix(query, n=3) + def search_prefix(query, n = 3) if query.size >= 5 return [] end @@ -97,7 +97,7 @@ module TagAutocomplete .map {|row| Result.new(*row, nil, :prefix)} end - def search_aliases(query, n=10) + def search_aliases(query, n = 10) wildcard_name = query + "*" TagAlias .select("tags.name, tags.post_count, tags.category, tag_aliases.antecedent_name") @@ -112,4 +112,3 @@ module TagAutocomplete .map {|row| Result.new(*row, :alias)} end end - diff --git a/app/logical/tag_change_notice_service.rb b/app/logical/tag_change_notice_service.rb index c7c5876b1..4d840e637 100644 --- a/app/logical/tag_change_notice_service.rb +++ b/app/logical/tag_change_notice_service.rb @@ -1,5 +1,5 @@ module TagChangeNoticeService - extend self + module_function def get_forum_topic_id(tag) Cache.get("tcn:#{tag}") diff --git a/app/logical/tag_implication_request.rb b/app/logical/tag_implication_request.rb index 548875f86..bfa91c682 100644 --- a/app/logical/tag_implication_request.rb +++ b/app/logical/tag_implication_request.rb @@ -1,5 +1,5 @@ class TagImplicationRequest - def self.command_string(antecedent_name, consequent_name, id=nil) + def self.command_string(antecedent_name, consequent_name, id = nil) if id return "[ti:#{id}]" end diff --git a/app/logical/tag_relationship_retirement_service.rb b/app/logical/tag_relationship_retirement_service.rb index 407b3a0aa..9e637a0d3 100644 --- a/app/logical/tag_relationship_retirement_service.rb +++ b/app/logical/tag_relationship_retirement_service.rb @@ -1,7 +1,6 @@ module TagRelationshipRetirementService - THRESHOLD = 2.year - - extend self + module_function + THRESHOLD = 2.years def forum_topic_title return "Retired tag aliases & implications" diff --git a/app/logical/upload_error_checker.rb b/app/logical/upload_error_checker.rb old mode 100644 new mode 100755 index ec3647519..69595b251 --- a/app/logical/upload_error_checker.rb +++ b/app/logical/upload_error_checker.rb @@ -19,4 +19,3 @@ class UploadErrorChecker end end end - diff --git a/app/logical/upload_service.rb b/app/logical/upload_service.rb index 2d77ff5de..857926ace 100644 --- a/app/logical/upload_service.rb +++ b/app/logical/upload_service.rb @@ -54,7 +54,6 @@ class UploadService @upload.save! @post = create_post_from_upload(@upload) return @upload - rescue Exception => x @upload.update(status: "error: #{x.class} - #{x.message}", backtrace: x.backtrace.join("\n")) @upload diff --git a/app/logical/upload_service/preprocessor.rb b/app/logical/upload_service/preprocessor.rb index 62dea578f..3bb443f27 100644 --- a/app/logical/upload_service/preprocessor.rb +++ b/app/logical/upload_service/preprocessor.rb @@ -62,7 +62,6 @@ class UploadService CurrentUser.as(uploader_id) do start! end - rescue ActiveRecord::RecordNotUnique return end @@ -106,9 +105,9 @@ class UploadService end def finish!(upload = nil) - pred = upload || self.predecessor() + pred = upload || self.predecessor - # regardless of who initialized the upload, credit should + # regardless of who initialized the upload, credit should # goto whoever submitted the form pred.initialize_attributes @@ -124,5 +123,4 @@ class UploadService return pred end end - end diff --git a/app/logical/upload_service/replacer.rb b/app/logical/upload_service/replacer.rb index 09ac16de3..6a956d78e 100644 --- a/app/logical/upload_service/replacer.rb +++ b/app/logical/upload_service/replacer.rb @@ -95,7 +95,7 @@ class UploadService upload = preprocessor.finish!(upload) raise Error, upload.status if upload.is_errored? md5_changed = upload.md5 != post.md5 - + replacement.replacement_url = find_replacement_url(replacement, upload) if md5_changed diff --git a/app/logical/upload_service/utils.rb b/app/logical/upload_service/utils.rb index 202c2b2ec..4bac295d9 100644 --- a/app/logical/upload_service/utils.rb +++ b/app/logical/upload_service/utils.rb @@ -1,6 +1,6 @@ class UploadService module Utils - extend self + module_function class CorruptFileError < RuntimeError; end def file_header_to_file_ext(file) @@ -93,7 +93,7 @@ class UploadService def generate_video_crop_for(video, width) vp = Tempfile.new(["video-preview", ".jpg"], binmode: true) - video.screenshot(vp.path, {:seek_time => 0, :resolution => "#{video.width}x#{video.height}"}) + video.screenshot(vp.path, :seek_time => 0, :resolution => "#{video.width}x#{video.height}") crop = DanbooruImageResizer.crop(vp, width, width, 85) vp.close return crop @@ -108,7 +108,7 @@ class UploadService end output_file = Tempfile.new(["video-preview", ".jpg"], binmode: true) - video.screenshot(output_file.path, {:seek_time => 0, :resolution => "#{width}x#{height}"}) + video.screenshot(output_file.path, :seek_time => 0, :resolution => "#{width}x#{height}") output_file end @@ -140,8 +140,8 @@ class UploadService end end - # these methods are only really used during upload processing even - # though logically they belong on upload. post can rely on the + # these methods are only really used during upload processing even + # though logically they belong on upload. post can rely on the # automatic tag that's added. def is_animated_gif?(upload, file) return false if upload.file_ext != "gif" @@ -179,7 +179,7 @@ class UploadService def get_file_for_upload(upload, file: nil) return file if file.present? - raise RuntimeError, "No file or source URL provided" if upload.source_url.blank? + raise "No file or source URL provided" if upload.source_url.blank? attempts = 0 @@ -190,8 +190,7 @@ class UploadService if !DanbooruImageResizer.validate_shell(file) raise CorruptFileError.new("File is corrupted") end - - rescue + rescue StandardError if attempts == 3 raise end @@ -201,7 +200,7 @@ class UploadService end if download.data[:ugoira_frame_data].present? - upload.context = { + upload.context = { "ugoira" => { "frame_data" => download.data[:ugoira_frame_data], "content_type" => "image/jpeg" diff --git a/app/logical/user_deletion.rb b/app/logical/user_deletion.rb index fd72f1794..210908cf8 100644 --- a/app/logical/user_deletion.rb +++ b/app/logical/user_deletion.rb @@ -1,5 +1,5 @@ class UserDeletion - class ValidationError < Exception ; end + class ValidationError < Exception; end attr_reader :user, :password @@ -18,10 +18,10 @@ class UserDeletion create_mod_action end -private - + private + def create_mod_action - ModAction.log("user ##{user.id} deleted",:user_delete) + ModAction.log("user ##{user.id} deleted", :user_delete) end def clear_saved_searches @@ -55,9 +55,7 @@ private def rename name = "user_#{user.id}" n = 0 - while User.where(:name => name).exists? && (n < 10) - name += "~" - end + name += "~" while User.where(:name => name).exists? && (n < 10) if n == 10 raise ValidationError.new("New name could not be found") diff --git a/app/logical/user_name_validator.rb b/app/logical/user_name_validator.rb index 5281c7664..40a6a3f25 100644 --- a/app/logical/user_name_validator.rb +++ b/app/logical/user_name_validator.rb @@ -1,7 +1,7 @@ class UserNameValidator < ActiveModel::EachValidator def validate_each(rec, attr, value) - name = value - + name = value + rec.errors[attr] << "already exists" if User.find_by_name(name).present? rec.errors[attr] << "must be 2 to 100 characters long" if !name.length.between?(2, 100) rec.errors[attr] << "cannot have whitespace or colons" if name =~ /[[:space:]]|:/ diff --git a/app/logical/user_promotion.rb b/app/logical/user_promotion.rb index 216a7a41b..f5fe9a95f 100644 --- a/app/logical/user_promotion.rb +++ b/app/logical/user_promotion.rb @@ -18,22 +18,22 @@ class UserPromotion user.level = new_level - if options.has_key?(:can_approve_posts) + if options.key?(:can_approve_posts) user.can_approve_posts = options[:can_approve_posts] end - if options.has_key?(:can_upload_free) + if options.key?(:can_upload_free) user.can_upload_free = options[:can_upload_free] end - if options.has_key?(:no_feedback) + if options.key?(:no_feedback) user.no_feedback = options[:no_feedback] end - if options.has_key?(:no_flagging) + if options.key?(:no_flagging) user.no_flagging = options[:no_flagging] end - + user.inviter_id = promoter.id create_user_feedback unless options[:is_upgrade] @@ -43,23 +43,23 @@ class UserPromotion user.save end -private - + private + def create_mod_actions if old_can_approve_posts != user.can_approve_posts? - ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed approval privileges for \"#{user.name}\":/users/#{user.id} from #{old_can_approve_posts} to [b]#{user.can_approve_posts?}[/b]",:user_approval_privilege) + ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed approval privileges for \"#{user.name}\":/users/#{user.id} from #{old_can_approve_posts} to [b]#{user.can_approve_posts?}[/b]", :user_approval_privilege) end if old_can_upload_free != user.can_upload_free? - ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed unlimited upload privileges for \"#{user.name}\":/users/#{user.id} from #{old_can_upload_free} to [b]#{user.can_upload_free?}[/b]",:user_upload_privilege) + ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed unlimited upload privileges for \"#{user.name}\":/users/#{user.id} from #{old_can_upload_free} to [b]#{user.can_upload_free?}[/b]", :user_upload_privilege) end if old_no_flagging != user.no_flagging? - ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed banned from flagging for \"#{user.name}\":/users/#{user.id} from #{old_no_flagging} to [b]#{user.no_flagging?}[/b]",:user_approval_privilege) + ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed banned from flagging for \"#{user.name}\":/users/#{user.id} from #{old_no_flagging} to [b]#{user.no_flagging?}[/b]", :user_approval_privilege) end if old_no_feedback != user.no_feedback? - ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed banned from feedback for \"#{user.name}\":/users/#{user.id} from #{old_no_feedback} to [b]#{user.no_feedback?}[/b]",:user_approval_privilege) + ModAction.log("\"#{promoter.name}\":/users/#{promoter.id} changed banned from feedback for \"#{user.name}\":/users/#{user.id} from #{old_no_feedback} to [b]#{user.no_feedback?}[/b]", :user_approval_privilege) end if user.level_changed? @@ -75,7 +75,7 @@ private # can't promote/demote moderators raise User::PrivilegeError if user.is_moderator? - # can't promote to admin + # can't promote to admin raise User::PrivilegeError if new_level.to_i >= User::Levels::ADMIN end @@ -108,11 +108,11 @@ private messages << "You gained the ability to give user feedback." end - if user.no_flagging? && !old_no_flagging + if user.no_flagging? && !old_no_flagging messages << "You lost the ability to flag posts." elsif !user.no_flagging? && old_no_flagging messages << "You gained the ability to flag posts." - end + end messages.join("\n") end diff --git a/app/models/application_record.rb b/app/models/application_record.rb index 4bc882cb5..90378f8c5 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -356,7 +356,7 @@ class ApplicationRecord < ActiveRecord::Base def belongs_to_creator(options = {}) class_eval do belongs_to :creator, options.merge(class_name: "User") - before_validation(on: :create) do |rec| + before_validation(on: :create) do |rec| if rec.creator_id.nil? rec.creator_id = CurrentUser.id rec.creator_ip_addr = CurrentUser.ip_addr if rec.respond_to?(:creator_ip_addr=) diff --git a/app/models/artist.rb b/app/models/artist.rb index a48001257..783c5f17c 100644 --- a/app/models/artist.rb +++ b/app/models/artist.rb @@ -1,6 +1,6 @@ class Artist < ApplicationRecord extend Memoist - class RevertError < Exception ; end + class RevertError < Exception; end attr_accessor :url_string_changed array_attribute :other_names @@ -140,7 +140,7 @@ class Artist < ApplicationRecord "youtube.com/c", # https://www.youtube.com/c/serafleurArt "youtube.com/channel", # https://www.youtube.com/channel/UCfrCa2Y6VulwHD3eNd3HBRA "youtube.com/user", # https://www.youtube.com/user/148nasuka - "youtu.be", # http://youtu.be/gibeLKKRT-0 + "youtu.be" # http://youtu.be/gibeLKKRT-0 ] SITE_BLACKLIST_REGEXP = Regexp.union(SITE_BLACKLIST.map do |domain| @@ -213,13 +213,13 @@ class Artist < ApplicationRecord def domains Cache.get("artist-domains-#{id}", 1.day) do - Post.raw_tag_match(name).pluck(:source).map do |x| - begin - map_domain(Addressable::URI.parse(x).domain) - rescue Addressable::URI::InvalidURIError - nil - end - end.compact.inject(Hash.new(0)) {|h, x| h[x] += 1; h}.sort {|a, b| b[1] <=> a[1]} + domains = Post.raw_tag_match(name).pluck(:source).map do |x| + map_domain(Addressable::URI.parse(x).domain) + rescue Addressable::URI::InvalidURIError + nil + end + + domains.compact.inject(Hash.new(0)) {|h, x| h[x] += 1; h}.sort {|a, b| b[1] <=> a[1]} end end end @@ -248,7 +248,7 @@ class Artist < ApplicationRecord end module VersionMethods - def create_version(force=false) + def create_version(force = false) if saved_change_to_name? || url_string_changed || saved_change_to_is_active? || saved_change_to_is_banned? || saved_change_to_other_names? || saved_change_to_group_name? || saved_change_to_notes? || force if merge_version? merge_version @@ -401,7 +401,7 @@ class Artist < ApplicationRecord Post.transaction do CurrentUser.without_safe_mode do ti = TagImplication.where(:antecedent_name => name, :consequent_name => "banned_artist").first - ti.destroy if ti + ti&.destroy Post.tag_match(name).where("true /* Artist.unban */").each do |post| post.unban! @@ -410,7 +410,7 @@ class Artist < ApplicationRecord end update_column(:is_banned, false) - ModAction.log("unbanned artist ##{id}",:artist_unban) + ModAction.log("unbanned artist ##{id}", :artist_unban) end end end @@ -429,7 +429,7 @@ class Artist < ApplicationRecord end update_column(:is_banned, true) - ModAction.log("banned artist ##{id}",:artist_ban) + ModAction.log("banned artist ##{id}", :artist_ban) end end end diff --git a/app/models/artist_commentary.rb b/app/models/artist_commentary.rb index 5433f25c0..ed404a8aa 100644 --- a/app/models/artist_commentary.rb +++ b/app/models/artist_commentary.rb @@ -1,5 +1,5 @@ class ArtistCommentary < ApplicationRecord - class RevertError < Exception ; end + class RevertError < Exception; end attr_accessor :remove_commentary_tag, :remove_commentary_request_tag, :remove_commentary_check_tag, :remove_partial_commentary_tag attr_accessor :add_commentary_tag, :add_commentary_request_tag, :add_commentary_check_tag, :add_partial_commentary_tag @@ -109,7 +109,7 @@ class ArtistCommentary < ApplicationRecord original_title: original_title, original_description: original_description, translated_title: translated_title, - translated_description: translated_description, + translated_description: translated_description ) end diff --git a/app/models/artist_url.rb b/app/models/artist_url.rb index c38b0afb7..bfc4582ab 100644 --- a/app/models/artist_url.rb +++ b/app/models/artist_url.rb @@ -29,17 +29,17 @@ class ArtistUrl < ApplicationRecord # the strategy won't always work for twitter because it looks for a status url = url.downcase if url =~ %r!^https?://(?:mobile\.)?twitter\.com! - + begin source = Sources::Strategies.find(url) - + if !source.normalized_for_artist_finder? && source.normalizable_for_artist_finder? url = source.normalize_for_artist_finder end rescue Net::OpenTimeout, PixivApiClient::Error raise if Rails.env.test? end - + url = url.gsub(/\/+\Z/, "") url = url.gsub(%r!^https://!, "http://") url + "/" diff --git a/app/models/ban.rb b/app/models/ban.rb index ff4b5c710..741a8815f 100644 --- a/app/models/ban.rb +++ b/app/models/ban.rb @@ -94,9 +94,7 @@ class Ban < ApplicationRecord @duration = dur end - def duration - @duration - end + attr_reader :duration def humanized_duration ApplicationController.helpers.distance_of_time_in_words(created_at, expires_at) diff --git a/app/models/bulk_update_request.rb b/app/models/bulk_update_request.rb index cad9dc550..04f1216ba 100644 --- a/app/models/bulk_update_request.rb +++ b/app/models/bulk_update_request.rb @@ -1,5 +1,6 @@ class BulkUpdateRequest < ApplicationRecord - attr_accessor :reason, :skip_secondary_validations + attr_accessor :reason + attr_reader :skip_secondary_validations belongs_to :user belongs_to :forum_topic, optional: true @@ -65,8 +66,8 @@ class BulkUpdateRequest < ApplicationRecord nil end ForumUpdater.new( - forum_topic, - forum_post: post, + forum_topic, + forum_post: post, expected_title: title, skip_update: !TagRelationship::SUPPORT_HARD_CODED ) @@ -81,11 +82,10 @@ class BulkUpdateRequest < ApplicationRecord forum_updater.update("The #{bulk_update_request_link} (forum ##{forum_post.id}) has been approved by @#{approver.name}.", "APPROVED") end end - rescue AliasAndImplicationImporter::Error => x self.approver = approver CurrentUser.scoped(approver) do - forum_updater.update("The #{bulk_update_request_link} (forum ##{forum_post.id}) has failed: #{x.to_s}", "FAILED") + forum_updater.update("The #{bulk_update_request_link} (forum ##{forum_post.id}) has failed: #{x}", "FAILED") end end @@ -129,11 +129,9 @@ class BulkUpdateRequest < ApplicationRecord end def validate_script - begin - AliasAndImplicationImporter.new(script, forum_topic_id, "1", skip_secondary_validations).validate! - rescue RuntimeError => e - errors[:base] << e.message - end + AliasAndImplicationImporter.new(script, forum_topic_id, "1", skip_secondary_validations).validate! + rescue RuntimeError => e + errors[:base] << e.message end end diff --git a/app/models/comment.rb b/app/models/comment.rb index eb3779747..e874a41a7 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -10,16 +10,16 @@ class Comment < ApplicationRecord has_many :votes, :class_name => "CommentVote", :dependent => :destroy after_create :update_last_commented_at_on_create after_update(:if => ->(rec) {(!rec.is_deleted? || !rec.saved_change_to_is_deleted?) && CurrentUser.id != rec.creator_id}) do |rec| - ModAction.log("comment ##{rec.id} updated by #{CurrentUser.name}",:comment_update) + ModAction.log("comment ##{rec.id} updated by #{CurrentUser.name}", :comment_update) end after_save :update_last_commented_at_on_destroy, :if => ->(rec) {rec.is_deleted? && rec.saved_change_to_is_deleted?} after_save(:if => ->(rec) {rec.is_deleted? && rec.saved_change_to_is_deleted? && CurrentUser.id != rec.creator_id}) do |rec| - ModAction.log("comment ##{rec.id} deleted by #{CurrentUser.name}",:comment_delete) + ModAction.log("comment ##{rec.id} deleted by #{CurrentUser.name}", :comment_delete) end mentionable( - :message_field => :body, + :message_field => :body, :title => ->(user_name) {"#{creator.name} mentioned you in a comment on post ##{post_id}"}, - :body => ->(user_name) {"@#{creator.name} mentioned you in a \"comment\":/posts/#{post_id}#comment-#{id} on post ##{post_id}:\n\n[quote]\n#{DText.excerpt(body, "@"+user_name)}\n[/quote]\n"}, + :body => ->(user_name) {"@#{creator.name} mentioned you in a \"comment\":/posts/#{post_id}#comment-#{id} on post ##{post_id}:\n\n[quote]\n#{DText.excerpt(body, "@" + user_name)}\n[/quote]\n"} ) api_attributes including: [:creator_name, :updater_name] @@ -56,7 +56,7 @@ class Comment < ApplicationRecord module VoteMethods def vote!(val) - numerical_score = val == "up" ? 1 : -1 + numerical_score = (val == "up") ? 1 : -1 vote = votes.create!(:score => numerical_score) if vote.is_positive? diff --git a/app/models/comment_vote.rb b/app/models/comment_vote.rb index 11efe5ea0..701eead15 100644 --- a/app/models/comment_vote.rb +++ b/app/models/comment_vote.rb @@ -1,5 +1,5 @@ class CommentVote < ApplicationRecord - class Error < Exception ; end + class Error < Exception; end belongs_to :comment belongs_to :user diff --git a/app/models/dmail_filter.rb b/app/models/dmail_filter.rb index 3842b8d3b..0c8d05b28 100644 --- a/app/models/dmail_filter.rb +++ b/app/models/dmail_filter.rb @@ -11,7 +11,7 @@ class DmailFilter < ApplicationRecord end def filtered?(dmail) - dmail.from.level < User::Levels::MODERATOR && has_filter? && (dmail.body =~ regexp || dmail.title =~ regexp || dmail.from.name =~ regexp) + dmail.from.level < User::Levels::MODERATOR && has_filter? && (dmail.body.match?(regexp) || dmail.title.match?(regexp) || dmail.from.name.match?(regexp)) end def has_filter? diff --git a/app/models/favorite.rb b/app/models/favorite.rb index efd05bd14..0d204f707 100644 --- a/app/models/favorite.rb +++ b/app/models/favorite.rb @@ -1,5 +1,5 @@ class Favorite < ApplicationRecord - class Error < Exception ; end + class Error < Exception; end belongs_to :post belongs_to :user @@ -34,7 +34,7 @@ class Favorite < ApplicationRecord return unless Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post_id).exists? Favorite.for_user(user.id).where(post_id: post_id).delete_all Post.where(:id => post_id).update_all("fav_count = fav_count - 1") - post.delete_user_from_fav_string(user.id) if post + post&.delete_user_from_fav_string(user.id) User.where(:id => user.id).update_all("favorite_count = favorite_count - 1") user.favorite_count -= 1 post.fav_count -= 1 if post diff --git a/app/models/favorite_group.rb b/app/models/favorite_group.rb index 6746dfd85..a13003253 100644 --- a/app/models/favorite_group.rb +++ b/app/models/favorite_group.rb @@ -31,7 +31,7 @@ class FavoriteGroup < ApplicationRecord where("name ilike ? escape E'\\\\'", name.to_escaped_for_sql_like) end - def hide_private(user,params) + def hide_private(user, params) if user.hide_favorites? where("is_public = true") elsif params[:is_public].present? @@ -51,14 +51,14 @@ class FavoriteGroup < ApplicationRecord if params[:creator_id].present? user = User.find(params[:creator_id]) - q = q.hide_private(user,params) + q = q.hide_private(user, params) q = q.where("creator_id = ?", user.id) elsif params[:creator_name].present? user = User.find_by_name(params[:creator_name]) - q = q.hide_private(user,params) + q = q.hide_private(user, params) q = q.where("creator_id = ?", user.id) else - q = q.hide_private(CurrentUser.user,params) + q = q.hide_private(CurrentUser.user, params) q = q.where("creator_id = ?", CurrentUser.user.id) end @@ -130,13 +130,11 @@ class FavoriteGroup < ApplicationRecord offset = options[:offset] || 0 limit = options[:limit] || Danbooru.config.posts_per_page slice = post_id_array.slice(offset, limit) - if slice && slice.any? + if slice&.any? slice.map do |id| - begin - Post.find(id) - rescue ActiveRecord::RecordNotFound - # swallow - end + Post.find(id) + rescue ActiveRecord::RecordNotFound + # swallow end.compact else [] diff --git a/app/models/forum_post.rb b/app/models/forum_post.rb index 5c37ac0e7..1f54f9149 100644 --- a/app/models/forum_post.rb +++ b/app/models/forum_post.rb @@ -23,15 +23,15 @@ class ForumPost < ApplicationRecord before_destroy :validate_topic_is_unlocked after_save :delete_topic_if_original_post after_update(:if => ->(rec) {rec.updater_id != rec.creator_id}) do |rec| - ModAction.log("#{CurrentUser.name} updated forum ##{rec.id}",:forum_post_update) + ModAction.log("#{CurrentUser.name} updated forum ##{rec.id}", :forum_post_update) end after_destroy(:if => ->(rec) {rec.updater_id != rec.creator_id}) do |rec| - ModAction.log("#{CurrentUser.name} deleted forum ##{rec.id}",:forum_post_delete) + ModAction.log("#{CurrentUser.name} deleted forum ##{rec.id}", :forum_post_delete) end mentionable( - :message_field => :body, + :message_field => :body, :title => ->(user_name) {%{#{creator.name} mentioned you in topic ##{topic_id} (#{topic.title})}}, - :body => ->(user_name) {%{@#{creator.name} mentioned you in topic ##{topic_id} ("#{topic.title}":[/forum_topics/#{topic_id}?page=#{forum_topic_page}]):\n\n[quote]\n#{DText.excerpt(body, "@"+user_name)}\n[/quote]\n}}, + :body => ->(user_name) {%{@#{creator.name} mentioned you in topic ##{topic_id} ("#{topic.title}":[/forum_topics/#{topic_id}?page=#{forum_topic_page}]):\n\n[quote]\n#{DText.excerpt(body, "@" + user_name)}\n[/quote]\n}} ) module SearchMethods @@ -173,11 +173,11 @@ class ForumPost < ApplicationRecord max = ForumPost.where(:topic_id => topic.id, :is_deleted => false).order("updated_at desc").first if max ForumTopic.where(:id => topic.id).update_all(["response_count = response_count - 1, updated_at = ?, updater_id = ?", max.updated_at, max.updater_id]) - topic.response_count -= 1 else ForumTopic.where(:id => topic.id).update_all("response_count = response_count - 1") - topic.response_count -= 1 end + + topic.response_count -= 1 end def initialize_is_deleted @@ -189,7 +189,7 @@ class ForumPost < ApplicationRecord end def forum_topic_page - ((ForumPost.where("topic_id = ? and created_at <= ?", topic_id, created_at).count) / Danbooru.config.posts_per_page.to_f).ceil + (ForumPost.where("topic_id = ? and created_at <= ?", topic_id, created_at).count / Danbooru.config.posts_per_page.to_f).ceil end def is_original_post?(original_post_id = nil) diff --git a/app/models/forum_topic.rb b/app/models/forum_topic.rb index c57219841..9dd280be3 100644 --- a/app/models/forum_topic.rb +++ b/app/models/forum_topic.rb @@ -8,7 +8,7 @@ class ForumTopic < ApplicationRecord MIN_LEVELS = { None: 0, Moderator: User::Levels::MODERATOR, - Admin: User::Levels::ADMIN, + Admin: User::Levels::ADMIN } belongs_to_creator @@ -25,7 +25,7 @@ class ForumTopic < ApplicationRecord accepts_nested_attributes_for :original_post after_update :update_orignal_post after_save(:if => ->(rec) {rec.is_locked? && rec.saved_change_to_is_locked?}) do |rec| - ModAction.log("locked forum topic ##{id} (title: #{title})",:forum_topic_lock) + ModAction.log("locked forum topic ##{id} (title: #{title})", :forum_topic_lock) end module CategoryMethods @@ -97,7 +97,7 @@ class ForumTopic < ApplicationRecord def mark_as_read!(user = CurrentUser.user) return if user.is_anonymous? - + match = ForumTopicVisit.where(:user_id => user.id, :forum_topic_id => id).first if match match.update_attribute(:last_read_at, updated_at) @@ -105,10 +105,15 @@ class ForumTopic < ApplicationRecord ForumTopicVisit.create(:user_id => user.id, :forum_topic_id => id, :last_read_at => updated_at) end - has_unread_topics = ForumTopic.permitted.active.where("forum_topics.updated_at >= ?", user.last_forum_read_at) - .joins("left join forum_topic_visits on (forum_topic_visits.forum_topic_id = forum_topics.id and forum_topic_visits.user_id = #{user.id})") - .where("(forum_topic_visits.id is null or forum_topic_visits.last_read_at < forum_topics.updated_at)") - .exists? + has_unread_topics = + ForumTopic + .permitted + .active + .where("forum_topics.updated_at >= ?", user.last_forum_read_at) + .joins("left join forum_topic_visits on (forum_topic_visits.forum_topic_id = forum_topics.id and forum_topic_visits.user_id = #{user.id})") + .where("(forum_topic_visits.id is null or forum_topic_visits.last_read_at < forum_topics.updated_at)") + .exists? + unless has_unread_topics user.update_attribute(:last_forum_read_at, Time.now) ForumTopicVisit.prune!(user) @@ -136,11 +141,11 @@ class ForumTopic < ApplicationRecord end def create_mod_action_for_delete - ModAction.log("deleted forum topic ##{id} (title: #{title})",:forum_topic_delete) + ModAction.log("deleted forum topic ##{id} (title: #{title})", :forum_topic_delete) end def create_mod_action_for_undelete - ModAction.log("undeleted forum topic ##{id} (title: #{title})",:forum_topic_undelete) + ModAction.log("undeleted forum topic ##{id} (title: #{title})", :forum_topic_undelete) end def initialize_is_deleted @@ -170,8 +175,6 @@ class ForumTopic < ApplicationRecord end def update_orignal_post - if original_post - original_post.update_columns(:updater_id => CurrentUser.id, :updated_at => Time.now) - end + original_post&.update_columns(:updater_id => CurrentUser.id, :updated_at => Time.now) end end diff --git a/app/models/ip_address.rb b/app/models/ip_address.rb index 33c35fe06..add206bbc 100644 --- a/app/models/ip_address.rb +++ b/app/models/ip_address.rb @@ -36,7 +36,7 @@ class IpAddress < ApplicationRecord def to_s # include the subnet mask only when the IP denotes a subnet. - ip_addr.size > 1 ? ip_addr.to_string : ip_addr.to_s + (ip_addr.size > 1) ? ip_addr.to_string : ip_addr.to_s end def readonly? diff --git a/app/models/mod_action.rb b/app/models/mod_action.rb index 325e69384..fc4534b49 100644 --- a/app/models/mod_action.rb +++ b/app/models/mod_action.rb @@ -4,17 +4,17 @@ class ModAction < ApplicationRecord api_attributes including: [:category_id] - #####DIVISIONS##### - #Groups: 0-999 - #Individual: 1000-1999 - #####Actions##### - #Create: 0 - #Update: 1 - #Delete: 2 - #Undelete: 3 - #Ban: 4 - #Unban: 5 - #Misc: 6-19 + # ####DIVISIONS##### + # Groups: 0-999 + # Individual: 1000-1999 + # ####Actions##### + # Create: 0 + # Update: 1 + # Delete: 2 + # Undelete: 3 + # Ban: 4 + # Unban: 5 + # Misc: 6-19 enum category: { user_delete: 2, user_ban: 4, @@ -77,7 +77,7 @@ class ModAction < ApplicationRecord end def self.log(desc, cat = :other) - create(:description => desc,:category => categories[cat]) + create(:description => desc, :category => categories[cat]) end def initialize_creator diff --git a/app/models/note.rb b/app/models/note.rb index 4ccae7aed..8402a850f 100644 --- a/app/models/note.rb +++ b/app/models/note.rb @@ -1,5 +1,5 @@ class Note < ApplicationRecord - class RevertError < Exception ; end + class RevertError < Exception; end attr_accessor :html_id belongs_to :post diff --git a/app/models/pixiv_ugoira_frame_data.rb b/app/models/pixiv_ugoira_frame_data.rb index f6c749bcb..f6bf07b56 100644 --- a/app/models/pixiv_ugoira_frame_data.rb +++ b/app/models/pixiv_ugoira_frame_data.rb @@ -4,10 +4,10 @@ class PixivUgoiraFrameData < ApplicationRecord def normalize_data return if data.nil? - + if data[0]["delay_msec"] self.data = data.map.with_index do |datum, i| - filename = "%06d.jpg" % [i] + filename = format("%06d.jpg", i) {"delay" => datum["delay_msec"], "file" => filename} end end diff --git a/app/models/pool.rb b/app/models/pool.rb index c9fc5fe98..c00dc2523 100644 --- a/app/models/pool.rb +++ b/app/models/pool.rb @@ -1,5 +1,5 @@ class Pool < ApplicationRecord - class RevertError < Exception ; end + class RevertError < Exception; end POOL_ORDER_LIMIT = 1000 array_attribute :post_ids, parse: /\d+/, cast: :to_i @@ -188,11 +188,11 @@ class Pool < ApplicationRecord end def create_mod_action_for_delete - ModAction.log("deleted pool ##{id} (name: #{name})",:pool_delete) + ModAction.log("deleted pool ##{id} (name: #{name})", :pool_delete) end def create_mod_action_for_undelete - ModAction.log("undeleted pool ##{id} (name: #{name})",:pool_undelete) + ModAction.log("undeleted pool ##{id} (name: #{name})", :pool_undelete) end def add!(post) diff --git a/app/models/pool_archive.rb b/app/models/pool_archive.rb index a75e1eea6..288f12588 100644 --- a/app/models/pool_archive.rb +++ b/app/models/pool_archive.rb @@ -1,5 +1,4 @@ class PoolArchive < ApplicationRecord - belongs_to :updater, :class_name => "User" def self.enabled? diff --git a/app/models/pool_version.rb b/app/models/pool_version.rb index fb5decaea..aeafe22b7 100644 --- a/app/models/pool_version.rb +++ b/app/models/pool_version.rb @@ -1,5 +1,5 @@ class PoolVersion < ApplicationRecord - class Error < Exception ; end + class Error < Exception; end belongs_to :pool belongs_to_updater diff --git a/app/models/post.rb b/app/models/post.rb index 1dd93e9d5..ba1ece4c7 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1,12 +1,12 @@ require 'danbooru/has_bit_flags' class Post < ApplicationRecord - class ApprovalError < Exception ; end - class DisapprovalError < Exception ; end - class RevertError < Exception ; end - class SearchError < Exception ; end - class DeletionError < Exception ; end - class TimeoutError < Exception ; end + class ApprovalError < Exception; end + class DisapprovalError < Exception; end + class RevertError < Exception; end + class SearchError < Exception; end + class DeletionError < Exception; end + class TimeoutError < Exception; end # Tags to copy when copying notes. NOTE_COPY_TAGS = %w[translated partially_translated check_translation translation_request reverse_translation] @@ -222,9 +222,7 @@ class Post < ApplicationRecord is_image? && image_width.present? && image_width > Danbooru.config.large_image_width end - def has_large - !!has_large? - end + alias has_large has_large? def large_image_width if has_large? @@ -344,7 +342,7 @@ class Post < ApplicationRecord when %r{\Ahttps?://twitter.com/[^/]+/status/(\d+)\z}i "https://twitter.com/i/web/status/#{$1}" - when %r{\Ahttps?://lohas\.nicoseiga\.jp/priv/(\d+)\?e=\d+&h=[a-f0-9]+}i, + when %r{\Ahttps?://lohas\.nicoseiga\.jp/priv/(\d+)\?e=\d+&h=[a-f0-9]+}i, %r{\Ahttps?://lohas\.nicoseiga\.jp/priv/[a-f0-9]+/\d+/(\d+)}i "https://seiga.nicovideo.jp/seiga/im#{$1}" @@ -410,7 +408,7 @@ class Post < ApplicationRecord subdomain = $1 filename = $2 "http://#{subdomain}.wikia.com/wiki/File:#{filename}" - + when %r{\Ahttps?://vignette(?:\d*)\.wikia\.nocookie\.net/([^/]+)/images/[a-f0-9]/[a-f0-9]{2}/([^/]+)}i subdomain = $1 filename = $2 @@ -426,28 +424,28 @@ class Post < ApplicationRecord when %r{\Ahttp://jpg\.nijigen-daiaru\.com/(\d+)}i "http://nijigen-daiaru.com/book.php?idb=#{$1}" - + when %r{\Ahttps?://sozai\.doujinantena\.com/contents_jpg/([a-f0-9]{32})/}i "http://doujinantena.com/page.php?id=#{$1}" when %r{\Ahttp://rule34-(?:data-\d{3}|images)\.paheal\.net/(?:_images/)?([a-f0-9]{32})}i "https://rule34.paheal.net/post/list/md5:#{$1}/1" - + when %r{\Ahttp://shimmie\.katawa-shoujo\.com/image/(\d+)}i "https://shimmie.katawa-shoujo.com/post/view/#{$1}" - + when %r{\Ahttp://(?:(?:(?:img\d?|cdn)\.)?rule34\.xxx|img\.booru\.org/(?:rule34|r34))(?:/(?:img/rule34|r34))?/{1,2}images/\d+/(?:[a-f0-9]{32}|[a-f0-9]{40})\.}i "https://rule34.xxx/index.php?page=post&s=list&md5=#{md5}" - + when %r{(\Ahttp://.+)/diarypro/d(?:ata/upfile/|iary\.cgi\?mode=image&upfile=)(\d+)}i base_url = $1 entry_no = $2 "#{base_url}/diarypro/diary.cgi?no=#{entry_no}" - + # XXX site is defunct when %r{\Ahttp://i(?:\d)?\.minus\.com/(?:i|j)([^\.]{12,})}i "http://minus.com/i/#{$1}" - + when %r{\Ahttps?://pic0[1-4]\.nijie\.info/nijie_picture/(?:diff/main/)?\d+_(\d+)_(?:\d+{10}|\d+_\d+{14})}i "https://nijie.info/view.php?id=#{$1}" @@ -475,16 +473,16 @@ class Post < ApplicationRecord # https://gfee_li.artstation.com/projects/asuka-7 when %r{\Ahttps?://\w+\.artstation.com/(?:artwork|projects)/(?[a-z0-9-]+)\z/}i "https://www.artstation.com/artwork/#{$~[:project_id]}" - + when %r{\Ahttps?://(?:o|image-proxy-origin)\.twimg\.com/\d/proxy\.jpg\?t=(\w+)&}i str = Base64.decode64($1) url = URI.extract(str, ['http', 'https']) if url.any? url = url[0] - if (url =~ /^https?:\/\/twitpic.com\/show\/large\/[a-z0-9]+/i) + if url =~ /^https?:\/\/twitpic.com\/show\/large\/[a-z0-9]+/i url.gsub!(/show\/large\//, "") index = url.rindex('.') - url = url[0..index-1] + url = url[0..index - 1] end url else @@ -524,7 +522,7 @@ class Post < ApplicationRecord url = Addressable::URI.parse(normalized_source) url.domain - rescue + rescue StandardError "" end end @@ -558,7 +556,7 @@ class Post < ApplicationRecord decrement_tags = tag_array_was - tag_array decrement_tags_except_requests = decrement_tags.reject {|tag| tag == "tagme" || tag.end_with?("_request")} - if decrement_tags_except_requests.size > 0 && !CurrentUser.is_builder? && CurrentUser.created_at > 1.week.ago + if !decrement_tags_except_requests.empty? && !CurrentUser.is_builder? && CurrentUser.created_at > 1.week.ago self.errors.add(:updater_id, "must have an account at least 1 week old to remove tags") return false end @@ -572,17 +570,17 @@ class Post < ApplicationRecord end end - def set_tag_count(category,tagcount) - self.send("tag_count_#{category}=",tagcount) + def set_tag_count(category, tagcount) + self.send("tag_count_#{category}=", tagcount) end def inc_tag_count(category) - set_tag_count(category,self.send("tag_count_#{category}") + 1) + set_tag_count(category, self.send("tag_count_#{category}") + 1) end def set_tag_counts(disable_cache = true) self.tag_count = 0 - TagCategory.categories.each {|x| set_tag_count(x,0)} + TagCategory.categories.each {|x| set_tag_count(x, 0)} categories = Tag.categories_for(tag_array, :disable_caching => disable_cache) categories.each_value do |category| self.tag_count += 1 @@ -596,8 +594,8 @@ class Post < ApplicationRecord if old_tag_string # If someone else committed changes to this post before we did, # then try to merge the tag changes together. - current_tags = tag_array_was() - new_tags = tag_array() + current_tags = tag_array_was + new_tags = tag_array old_tags = Tag.scan_tags(old_tag_string) kept_tags = current_tags & new_tags @@ -645,7 +643,7 @@ class Post < ApplicationRecord normalized_tags = add_automatic_tags(normalized_tags) normalized_tags = remove_invalid_tags(normalized_tags) normalized_tags = Tag.convert_cosplay_tags(normalized_tags) - normalized_tags = normalized_tags + Tag.create_for_list(TagImplication.automatic_tags_for(normalized_tags)) + normalized_tags += Tag.create_for_list(TagImplication.automatic_tags_for(normalized_tags)) normalized_tags = TagImplication.with_descendants(normalized_tags) normalized_tags = normalized_tags.compact.uniq.sort normalized_tags = Tag.create_for_list(normalized_tags) @@ -732,9 +730,9 @@ class Post < ApplicationRecord def apply_casesensitive_metatags(tags) casesensitive_metatags, tags = tags.partition {|x| x =~ /\A(?:source):/i} - #Reuse the following metatags after the post has been saved + # Reuse the following metatags after the post has been saved casesensitive_metatags += tags.select {|x| x =~ /\A(?:newpool):/i} - if casesensitive_metatags.length > 0 + if !casesensitive_metatags.empty? case casesensitive_metatags[-1] when /^source:none$/i self.source = "" @@ -825,19 +823,19 @@ class Post < ApplicationRecord when /^-favgroup:(\d+)$/i favgroup = FavoriteGroup.where("id = ?", $1.to_i).for_creator(CurrentUser.user.id).first - favgroup.remove!(id) if favgroup + favgroup&.remove!(id) when /^-favgroup:(.+)$/i favgroup = FavoriteGroup.named($1).for_creator(CurrentUser.user.id).first - favgroup.remove!(id) if favgroup + favgroup&.remove!(id) when /^favgroup:(\d+)$/i favgroup = FavoriteGroup.where("id = ?", $1.to_i).for_creator(CurrentUser.user.id).first - favgroup.add!(id) if favgroup + favgroup&.add!(id) when /^favgroup:(.+)$/i favgroup = FavoriteGroup.named($1).for_creator(CurrentUser.user.id).first - favgroup.add!(id) if favgroup + favgroup&.add!(id) end end @@ -866,20 +864,20 @@ class Post < ApplicationRecord self.rating = $1 when /^(-?)locked:notes?$/i - self.is_note_locked = ($1 != "-" ) if CurrentUser.is_builder? + self.is_note_locked = ($1 != "-") if CurrentUser.is_builder? when /^(-?)locked:rating$/i - self.is_rating_locked = ($1 != "-" ) if CurrentUser.is_builder? + self.is_rating_locked = ($1 != "-") if CurrentUser.is_builder? when /^(-?)locked:status$/i - self.is_status_locked = ($1 != "-" ) if CurrentUser.is_admin? + self.is_status_locked = ($1 != "-") if CurrentUser.is_admin? end end end def has_tag?(tag) - !!(tag_string =~ /(?:^| )(?:#{tag})(?:$| )/) + tag_string.match?(/(?:^| )(?:#{tag})(?:$| )/) end def add_tag(tag) @@ -910,7 +908,6 @@ class Post < ApplicationRecord end end - module FavoriteMethods def clean_fav_string? true @@ -925,10 +922,10 @@ class Post < ApplicationRecord end def favorited_by?(user_id = CurrentUser.id) - !!(fav_string =~ /(?:\A| )fav:#{user_id}(?:\Z| )/) + fav_string.match?(/(?:\A| )fav:#{user_id}(?:\Z| )/) end - alias_method :is_favorited?, :favorited_by? + alias is_favorited? favorited_by? def append_user_to_fav_string(user_id) update_column(:fav_string, (fav_string + " fav:#{user_id}").strip) @@ -966,13 +963,13 @@ class Post < ApplicationRecord ordered_users end - def favorite_groups(active_id=nil) + def favorite_groups(active_id = nil) @favorite_groups ||= begin groups = [] if active_id.present? active_group = FavoriteGroup.where(:id => active_id.to_i).first - groups << active_group if active_group && active_group.contains?(self.id) + groups << active_group if active_group&.contains?(self.id) end groups += CurrentUser.user.favorite_groups.select do |favgroup| @@ -1016,7 +1013,7 @@ class Post < ApplicationRecord end def has_active_pools? - pools.undeleted.length > 0 + !pools.undeleted.empty? end def belongs_to_pool?(pool) @@ -1091,7 +1088,7 @@ class Post < ApplicationRecord tags += " -status:deleted" if CurrentUser.hide_deleted_posts? && !Tag.has_metatag?(tags, "status", "-status") tags = Tag.normalize_query(tags) - # optimize some cases. these are just estimates but at these + # Optimize some cases. these are just estimates but at these # quantities being off by a few hundred doesn't matter much if Danbooru.config.estimate_post_counts if tags == "" @@ -1148,7 +1145,7 @@ class Post < ApplicationRecord def fix_post_counts(post) post.set_tag_counts(false) if post.changes_saved? - args = Hash[TagCategory.categories.map {|x| ["tag_count_#{x}",post.send("tag_count_#{x}")]}].update(:tag_count => post.tag_count) + args = Hash[TagCategory.categories.map {|x| ["tag_count_#{x}", post.send("tag_count_#{x}")]}].update(:tag_count => post.tag_count) post.update_columns(args) end end @@ -1207,7 +1204,7 @@ class Post < ApplicationRecord end def update_parent_on_destroy - parent.update_has_children_flag if parent + parent&.update_has_children_flag end def update_children_on_destroy @@ -1239,7 +1236,7 @@ class Post < ApplicationRecord end unless options[:without_mod_action] - ModAction.log("moved favorites from post ##{id} to post ##{parent.id}",:post_move_favorites) + ModAction.log("moved favorites from post ##{id} to post ##{parent.id}", :post_move_favorites) end end @@ -1260,7 +1257,7 @@ class Post < ApplicationRecord def children_ids if has_children? - children.map{|p| p.id}.join(' ') + children.map {|p| p.id}.join(' ') end end end @@ -1274,7 +1271,7 @@ class Post < ApplicationRecord transaction do Post.without_timeout do - ModAction.log("permanently deleted post ##{id}",:post_permanent_delete) + ModAction.log("permanently deleted post ##{id}", :post_permanent_delete) give_favorites_to_parent update_children_on_destroy @@ -1290,12 +1287,12 @@ class Post < ApplicationRecord def ban! update_column(:is_banned, true) - ModAction.log("banned post ##{id}",:post_ban) + ModAction.log("banned post ##{id}", :post_ban) end def unban! update_column(:is_banned, false) - ModAction.log("unbanned post ##{id}",:post_unban) + ModAction.log("unbanned post ##{id}", :post_unban) end def delete!(reason, options = {}) @@ -1318,7 +1315,7 @@ class Post < ApplicationRecord give_favorites_to_parent(options) if options[:move_favorites] unless options[:without_mod_action] - ModAction.log("deleted post ##{id}, reason: #{reason}",:post_delete) + ModAction.log("deleted post ##{id}, reason: #{reason}", :post_delete) end end end @@ -1329,7 +1326,7 @@ class Post < ApplicationRecord return false end - if !CurrentUser.is_admin? + if !CurrentUser.is_admin? if approved_by?(CurrentUser.user) raise ApprovalError.new("You have previously approved this post and cannot undelete it") elsif uploader_id == CurrentUser.id @@ -1341,7 +1338,7 @@ class Post < ApplicationRecord self.approver_id = CurrentUser.id flags.each {|x| x.resolve!} save - ModAction.log("undeleted post ##{id}",:post_undelete) + ModAction.log("undeleted post ##{id}", :post_undelete) end def replace!(params) @@ -1445,7 +1442,7 @@ class Post < ApplicationRecord end def associated_attributes - [ :pixiv_ugoira_frame_data ] + [:pixiv_ugoira_frame_data] end def as_json(options = {}) @@ -1645,7 +1642,7 @@ class Post < ApplicationRecord PostQueryBuilder.new(query).build end end - + module PixivMethods def parse_pixiv_id self.pixiv_id = nil @@ -1713,18 +1710,18 @@ class Post < ApplicationRecord if new_general_tags.present? n = new_general_tags.size tag_wiki_links = new_general_tags.map { |tag| "[[#{tag.name}]]" } - self.warnings[:base] << "Created #{n} new #{n == 1 ? "tag" : "tags"}: #{tag_wiki_links.join(", ")}" + self.warnings[:base] << "Created #{n} new #{(n == 1) ? "tag" : "tags"}: #{tag_wiki_links.join(", ")}" end if repopulated_tags.present? n = repopulated_tags.size tag_wiki_links = repopulated_tags.map { |tag| "[[#{tag.name}]]" } - self.warnings[:base] << "Repopulated #{n} old #{n == 1 ? "tag" : "tags"}: #{tag_wiki_links.join(", ")}" + self.warnings[:base] << "Repopulated #{n} old #{(n == 1) ? "tag" : "tags"}: #{tag_wiki_links.join(", ")}" end new_artist_tags.each do |tag| if tag.artist.blank? - self.warnings[:base] << "Artist [[#{tag.name}]] requires an artist entry. \"Create new artist entry\":[/artists/new?artist%5Bname%5D=#{CGI::escape(tag.name)}]" + self.warnings[:base] << "Artist [[#{tag.name}]] requires an artist entry. \"Create new artist entry\":[/artists/new?artist%5Bname%5D=#{CGI.escape(tag.name)}]" end end end @@ -1746,7 +1743,7 @@ class Post < ApplicationRecord return if tags.any? { |t| t.category == Tag.categories.artist } return if Sources::Strategies.find(source).is_a?(Sources::Strategies::Null) - self.warnings[:base] << "Artist tag is required. \"Create new artist tag\":[/artists/new?artist%5Bsource%5D=#{CGI::escape(source)}]. Ask on the forum if you need naming help" + self.warnings[:base] << "Artist tag is required. \"Create new artist tag\":[/artists/new?artist%5Bsource%5D=#{CGI.escape(source)}]. Ask on the forum if you need naming help" end def has_copyright_tag @@ -1764,7 +1761,7 @@ class Post < ApplicationRecord end end end - + include FileMethods include ImageMethods include ApprovalMethods diff --git a/app/models/post_appeal.rb b/app/models/post_appeal.rb index e55dac75b..b4fea7607 100644 --- a/app/models/post_appeal.rb +++ b/app/models/post_appeal.rb @@ -1,5 +1,5 @@ class PostAppeal < ApplicationRecord - class Error < Exception ; end + class Error < Exception; end belongs_to :creator, :class_name => "User" belongs_to :post diff --git a/app/models/post_approval.rb b/app/models/post_approval.rb index e5f5e6123..1cb2d4654 100644 --- a/app/models/post_approval.rb +++ b/app/models/post_approval.rb @@ -26,7 +26,7 @@ class PostApproval < ApplicationRecord end def approve_post - ModAction.log("undeleted post ##{post_id}",:post_undelete) if post.is_deleted + ModAction.log("undeleted post ##{post_id}", :post_undelete) if post.is_deleted post.flags.each(&:resolve!) post.update(approver: user, is_flagged: false, is_pending: false, is_deleted: false) diff --git a/app/models/post_archive.rb b/app/models/post_archive.rb index 68e960bbe..afc47e30e 100644 --- a/app/models/post_archive.rb +++ b/app/models/post_archive.rb @@ -1,5 +1,5 @@ class PostArchive < ApplicationRecord - class RevertError < Exception ; end + class RevertError < Exception; end extend Memoist belongs_to :post @@ -102,7 +102,7 @@ class PostArchive < ApplicationRecord end def visible? - post && post.visible? + post&.visible? end def diff(version = nil) @@ -135,10 +135,10 @@ class PostArchive < ApplicationRecord :removed_tags => removed_tags, :obsolete_added_tags => added_tags - latest_tags, :obsolete_removed_tags => removed_tags & latest_tags, - :unchanged_tags => new_tags & old_tags, + :unchanged_tags => new_tags & old_tags } end - + def changes delta = { :added_tags => added_tags, diff --git a/app/models/post_event.rb b/app/models/post_event.rb index 5b46fde6b..a3dffc352 100644 --- a/app/models/post_event.rb +++ b/app/models/post_event.rb @@ -58,7 +58,7 @@ class PostEvent "created_at": nil, "reason": nil, "is_resolved": nil, - "type": nil, + "type": nil } end diff --git a/app/models/post_flag.rb b/app/models/post_flag.rb index 3257fc036..55395244b 100644 --- a/app/models/post_flag.rb +++ b/app/models/post_flag.rb @@ -1,5 +1,5 @@ class PostFlag < ApplicationRecord - class Error < Exception ; end + class Error < Exception; end module Reasons UNAPPROVED = "Unapproved in three days" diff --git a/app/models/post_replacement.rb b/app/models/post_replacement.rb index 514980007..49323bccc 100644 --- a/app/models/post_replacement.rb +++ b/app/models/post_replacement.rb @@ -33,5 +33,4 @@ class PostReplacement < ApplicationRecord tags = tags.map { |tag| "-#{tag}" } tags.join(" ") end - end diff --git a/app/models/post_version.rb b/app/models/post_version.rb index b64af481c..a2d0c43ff 100644 --- a/app/models/post_version.rb +++ b/app/models/post_version.rb @@ -85,7 +85,7 @@ class PostVersion < ApplicationRecord :removed_tags => removed_tags, :obsolete_added_tags => added_tags - latest_tags, :obsolete_removed_tags => removed_tags & latest_tags, - :unchanged_tags => new_tags & old_tags, + :unchanged_tags => new_tags & old_tags } end diff --git a/app/models/post_vote.rb b/app/models/post_vote.rb index d5e56c4a8..cf91e3824 100644 --- a/app/models/post_vote.rb +++ b/app/models/post_vote.rb @@ -1,5 +1,5 @@ class PostVote < ApplicationRecord - class Error < Exception ; end + class Error < Exception; end belongs_to :post belongs_to :user diff --git a/app/models/saved_search.rb b/app/models/saved_search.rb index 2e7cc7cbf..87b093000 100644 --- a/app/models/saved_search.rb +++ b/app/models/saved_search.rb @@ -46,11 +46,11 @@ class SavedSearch < ApplicationRecord concerning :Labels do class_methods do def normalize_label(label) - label. - to_s. - strip. - downcase. - gsub(/[[:space:]]/, "_") + label + .to_s + .strip + .downcase + .gsub(/[[:space:]]/, "_") end def search_labels(user_id, params) @@ -67,17 +67,15 @@ class SavedSearch < ApplicationRecord end def labels_for(user_id) - SavedSearch. - where(user_id: user_id). - order("label"). - pluck(Arel.sql("distinct unnest(labels) as label")) + SavedSearch + .where(user_id: user_id) + .order("label") + .pluck(Arel.sql("distinct unnest(labels) as label")) end end def normalize_labels - self.labels = labels. - map {|x| SavedSearch.normalize_label(x)}. - reject {|x| x.blank?} + self.labels = labels.map {|x| SavedSearch.normalize_label(x)}.reject(&:blank?) end def label_string @@ -137,13 +135,13 @@ class SavedSearch < ApplicationRecord concerning :Queries do class_methods do def queries_for(user_id, label: nil, options: {}) - SavedSearch. - where(user_id: user_id). - labeled(label). - pluck(:query). - map {|x| Tag.normalize_query(x, sort: true)}. - sort. - uniq + SavedSearch + .where(user_id: user_id) + .labeled(label) + .pluck(:query) + .map {|x| Tag.normalize_query(x, sort: true)} + .sort + .uniq end end @@ -156,7 +154,7 @@ class SavedSearch < ApplicationRecord end end - attr_accessor :disable_labels + attr_reader :disable_labels belongs_to :user validates :query, presence: true validate :validate_count diff --git a/app/models/tag.rb b/app/models/tag.rb index 40b104b19..a856f7f75 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -40,9 +40,9 @@ class Tag < ApplicationRecord random custom ] + - COUNT_METATAGS + - COUNT_METATAG_SYNONYMS.flat_map { |str| [str, "#{str}_asc"] } + - TagCategory.short_name_list.flat_map { |str| ["#{str}tags", "#{str}tags_asc"] } + COUNT_METATAGS + + COUNT_METATAG_SYNONYMS.flat_map { |str| [str, "#{str}_asc"] } + + TagCategory.short_name_list.flat_map { |str| ["#{str}tags", "#{str}tags_asc"] } has_one :wiki_page, :foreign_key => "title", :primary_key => "name" has_one :artist, :foreign_key => "name", :primary_key => "name" @@ -130,7 +130,7 @@ class Tag < ApplicationRecord module CategoryMethods module ClassMethods def categories - @category_mapping ||= CategoryMapping.new + @categories ||= CategoryMapping.new end def select_category_for(tag_name) @@ -170,11 +170,11 @@ class Tag < ApplicationRecord end def update_category_post_counts - Post.with_timeout(30_000, nil, {:tags => name}) do + Post.with_timeout(30_000, nil, :tags => name) do Post.raw_tag_match(name).where("true /* Tag#update_category_post_counts */").find_each do |post| post.reload post.set_tag_counts(false) - args = TagCategory.categories.map {|x| ["tag_count_#{x}",post.send("tag_count_#{x}")]}.to_h.update(:tag_count => post.tag_count) + args = TagCategory.categories.map {|x| ["tag_count_#{x}", post.send("tag_count_#{x}")]}.to_h.update(:tag_count => post.tag_count) Post.where(:id => post.id).update_all(args) end end @@ -314,11 +314,7 @@ class Tag < ApplicationRecord object.to_f when :date, :datetime - begin - Time.zone.parse(object) - rescue Exception - nil - end + Time.zone.parse(object) rescue nil when :age DurationParser.parse(object).ago @@ -327,7 +323,7 @@ class Tag < ApplicationRecord object =~ /\A(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)\Z/i if $1 && $2.to_f != 0.0 - ($1.to_f / $2.to_f).round(2) + ($1.to_f / $2.to_f).round(2) else object.to_f.round(2) end @@ -750,7 +746,7 @@ class Tag < ApplicationRecord when "order" g2 = g2.downcase - order, suffix, _ = g2.partition(/_(asc|desc)\z/i) + order, suffix, _tail = g2.partition(/_(asc|desc)\z/i) if order.in?(COUNT_METATAG_SYNONYMS) g2 = order.singularize + "_count" + suffix end @@ -898,10 +894,14 @@ class Tag < ApplicationRecord name = normalize_name(name) wildcard_name = name + '*' - query1 = Tag.select("tags.name, tags.post_count, tags.category, null AS antecedent_name") + query1 = + Tag + .select("tags.name, tags.post_count, tags.category, null AS antecedent_name") .search(:name_matches => wildcard_name, :order => "count").limit(limit) - query2 = TagAlias.select("tags.name, tags.post_count, tags.category, tag_aliases.antecedent_name") + query2 = + TagAlias + .select("tags.name, tags.post_count, tags.category, tag_aliases.antecedent_name") .joins("INNER JOIN tags ON tags.name = tag_aliases.consequent_name") .where("tag_aliases.antecedent_name LIKE ? ESCAPE E'\\\\'", wildcard_name.to_escaped_for_sql_like) .active @@ -922,7 +922,7 @@ class Tag < ApplicationRecord end def self.convert_cosplay_tags(tags) - cosplay_tags,other_tags = tags.partition {|tag| tag.match(/\A(.+)_\(cosplay\)\Z/) } + cosplay_tags, other_tags = tags.partition {|tag| tag.match(/\A(.+)_\(cosplay\)\Z/) } cosplay_tags.grep(/\A(.+)_\(cosplay\)\Z/) { "#{TagAlias.to_aliased([$1]).first}_(cosplay)" } + other_tags end diff --git a/app/models/tag_alias.rb b/app/models/tag_alias.rb index 719a800dd..c4c33699c 100644 --- a/app/models/tag_alias.rb +++ b/app/models/tag_alias.rb @@ -21,7 +21,7 @@ class TagAlias < TagRelationship nil end ForumUpdater.new( - forum_topic, + forum_topic, forum_post: post, expected_title: "Tag alias: #{antecedent_name} -> #{consequent_name}", skip_update: !TagRelationship::SUPPORT_HARD_CODED @@ -69,7 +69,7 @@ class TagAlias < TagRelationship rescue Exception => e if tries < 5 tries += 1 - sleep 2 ** tries + sleep 2**tries retry end @@ -148,7 +148,7 @@ class TagAlias < TagRelationship def rename_wiki_and_artist antecedent_wiki = WikiPage.titled(antecedent_name).first - if antecedent_wiki.present? + if antecedent_wiki.present? if WikiPage.titled(consequent_name).blank? antecedent_wiki.update!(title: consequent_name, skip_secondary_validations: true) else @@ -178,22 +178,22 @@ class TagAlias < TagRelationship end def create_mod_action - alias_desc = %Q("tag alias ##{id}":[#{Rails.application.routes.url_helpers.tag_alias_path(self)}]: [[#{antecedent_name}]] -> [[#{consequent_name}]]) + alias_desc = %("tag alias ##{id}":[#{Rails.application.routes.url_helpers.tag_alias_path(self)}]: [[#{antecedent_name}]] -> [[#{consequent_name}]]) if saved_change_to_id? - ModAction.log("created #{status} #{alias_desc}",:tag_alias_create) + ModAction.log("created #{status} #{alias_desc}", :tag_alias_create) else # format the changes hash more nicely. change_desc = saved_changes.except(:updated_at).map do |attribute, values| old, new = values[0], values[1] if old.nil? - %Q(set #{attribute} to "#{new}") + %(set #{attribute} to "#{new}") else - %Q(changed #{attribute} from "#{old}" to "#{new}") + %(changed #{attribute} from "#{old}" to "#{new}") end end.join(", ") - ModAction.log("updated #{alias_desc}\n#{change_desc}",:tag_alias_update) + ModAction.log("updated #{alias_desc}\n#{change_desc}", :tag_alias_update) end end end diff --git a/app/models/tag_implication.rb b/app/models/tag_implication.rb index 6b4324f4e..04d2c2ec8 100644 --- a/app/models/tag_implication.rb +++ b/app/models/tag_implication.rb @@ -144,7 +144,7 @@ class TagImplication < TagRelationship rescue Exception => e if tries < 5 tries += 1 - sleep 2 ** tries + sleep 2**tries retry end @@ -170,22 +170,22 @@ class TagImplication < TagRelationship end def create_mod_action - implication = %Q("tag implication ##{id}":[#{Rails.application.routes.url_helpers.tag_implication_path(self)}]: [[#{antecedent_name}]] -> [[#{consequent_name}]]) + implication = %("tag implication ##{id}":[#{Rails.application.routes.url_helpers.tag_implication_path(self)}]: [[#{antecedent_name}]] -> [[#{consequent_name}]]) if saved_change_to_id? - ModAction.log("created #{status} #{implication}",:tag_implication_create) + ModAction.log("created #{status} #{implication}", :tag_implication_create) else # format the changes hash more nicely. change_desc = saved_changes.except(:updated_at).map do |attribute, values| old, new = values[0], values[1] if old.nil? - %Q(set #{attribute} to "#{new}") + %(set #{attribute} to "#{new}") else - %Q(changed #{attribute} from "#{old}" to "#{new}") + %(changed #{attribute} from "#{old}" to "#{new}") end end.join(", ") - ModAction.log("updated #{implication}\n#{change_desc}",:tag_implication_update) + ModAction.log("updated #{implication}\n#{change_desc}", :tag_implication_update) end end @@ -196,8 +196,8 @@ class TagImplication < TagRelationship nil end ForumUpdater.new( - forum_topic, - forum_post: post, + forum_topic, + forum_post: post, expected_title: "Tag implication: #{antecedent_name} -> #{consequent_name}", skip_update: !TagRelationship::SUPPORT_HARD_CODED ) diff --git a/app/models/tag_relationship.rb b/app/models/tag_relationship.rb index 91cce96d6..5467453cd 100644 --- a/app/models/tag_relationship.rb +++ b/app/models/tag_relationship.rb @@ -16,13 +16,13 @@ class TagRelationship < ApplicationRecord has_one :antecedent_wiki, through: :antecedent_tag, source: :wiki_page has_one :consequent_wiki, through: :consequent_tag, source: :wiki_page - scope :active, ->{approved} - scope :approved, ->{where(status: %w[active processing queued])} - scope :deleted, ->{where(status: "deleted")} - scope :expired, ->{where("created_at < ?", EXPIRY.days.ago)} - scope :old, ->{where("created_at >= ? and created_at < ?", EXPIRY.days.ago, EXPIRY_WARNING.days.ago)} - scope :pending, ->{where(status: "pending")} - scope :retired, ->{where(status: "retired")} + scope :active, -> {approved} + scope :approved, -> {where(status: %w[active processing queued])} + scope :deleted, -> {where(status: "deleted")} + scope :expired, -> {where("created_at < ?", EXPIRY.days.ago)} + scope :old, -> {where("created_at >= ? and created_at < ?", EXPIRY.days.ago, EXPIRY_WARNING.days.ago)} + scope :pending, -> {where(status: "pending")} + scope :retired, -> {where(status: "retired")} before_validation :initialize_creator, :on => :create before_validation :normalize_names diff --git a/app/models/upload.rb b/app/models/upload.rb index e931aac27..aa210271b 100644 --- a/app/models/upload.rb +++ b/app/models/upload.rb @@ -1,7 +1,7 @@ require "tmpdir" class Upload < ApplicationRecord - class Error < Exception ; end + class Error < Exception; end class FileValidator < ActiveModel::Validator def validate(record) @@ -54,7 +54,6 @@ class Upload < ApplicationRecord end end - attr_accessor :as_pending, :replaced_post, :file belongs_to :uploader, :class_name => "User" belongs_to :post, optional: true @@ -64,7 +63,7 @@ class Upload < ApplicationRecord validate :uploader_is_not_limited, on: :create # validates :source, format: { with: /\Ahttps?/ }, if: ->(record) {record.file.blank?}, on: :create validates :rating, inclusion: { in: %w(q e s) }, allow_nil: true - validates :md5, confirmation: true, if: -> (rec) { rec.md5_confirmation.present? } + validates :md5, confirmation: true, if: ->(rec) { rec.md5_confirmation.present? } validates_with FileValidator, on: :file serialize :context, JSON diff --git a/app/models/user.rb b/app/models/user.rb index cf46338a9..db59924e5 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -2,8 +2,8 @@ require 'digest/sha1' require 'danbooru/has_bit_flags' class User < ApplicationRecord - class Error < Exception ; end - class PrivilegeError < Exception ; end + class Error < Exception; end + class PrivilegeError < Exception; end module Levels ANONYMOUS = 0 @@ -20,7 +20,7 @@ class User < ApplicationRecord :banned, :approver, :voter, - :super_voter, + :super_voter ] # candidates for removal: @@ -199,7 +199,7 @@ class User < ApplicationRecord end def reset_password_and_deliver_notice - new_password = reset_password() + new_password = reset_password Maintenance::User::PasswordResetMailer.confirmation(self, new_password).deliver_now end end @@ -296,7 +296,7 @@ class User < ApplicationRecord when Levels::ADMIN "Admin" - + else "" end @@ -570,23 +570,23 @@ class User < ApplicationRecord module ApiMethods def api_attributes - attributes = [ - :id, :created_at, :name, :inviter_id, :level, :base_upload_limit, - :post_upload_count, :post_update_count, :note_update_count, :is_banned, - :can_approve_posts, :can_upload_free, :is_super_voter, :level_string, + attributes = %i[ + id created_at name inviter_id level base_upload_limit + post_upload_count post_update_count note_update_count is_banned + can_approve_posts can_upload_free is_super_voter level_string ] if id == CurrentUser.user.id attributes += BOOLEAN_ATTRIBUTES - attributes += [ - :updated_at, :email, :last_logged_in_at, :last_forum_read_at, - :comment_threshold, :default_image_size, - :favorite_tags, :blacklisted_tags, :time_zone, :per_page, - :custom_style, :favorite_count, :api_regen_multiplier, - :api_burst_limit, :remaining_api_limit, :statement_timeout, - :favorite_group_limit, :favorite_limit, :tag_query_limit, - :can_comment_vote?, :can_remove_from_pools?, :is_comment_limited?, - :can_comment?, :can_upload?, :max_saved_searches, :theme + attributes += %i[ + updated_at email last_logged_in_at last_forum_read_at + comment_threshold default_image_size + favorite_tags blacklisted_tags time_zone per_page + custom_style favorite_count api_regen_multiplier + api_burst_limit remaining_api_limit statement_timeout + favorite_group_limit favorite_limit tag_query_limit + can_comment_vote? can_remove_from_pools? is_comment_limited? + can_comment? can_upload? max_saved_searches theme ] end @@ -595,13 +595,13 @@ class User < ApplicationRecord # extra attributes returned for /users/:id.json but not for /users.json. def full_attributes - [ - :wiki_page_version_count, :artist_version_count, - :artist_commentary_version_count, :pool_version_count, - :forum_post_count, :comment_count, :favorite_group_count, - :appeal_count, :flag_count, :positive_feedback_count, - :neutral_feedback_count, :negative_feedback_count, :upload_limit, - :max_upload_limit + %i[ + wiki_page_version_count artist_version_count + artist_commentary_version_count pool_version_count + forum_post_count comment_count favorite_group_count + appeal_count flag_count positive_feedback_count + neutral_feedback_count negative_feedback_count upload_limit + max_upload_limit ] end @@ -731,10 +731,10 @@ class User < ApplicationRecord if params[x].present? attr_idx = BOOLEAN_ATTRIBUTES.index(x.to_s) if params[x].to_s.truthy? - bitprefs_include ||= "0"*bitprefs_length + bitprefs_include ||= "0" * bitprefs_length bitprefs_include[attr_idx] = '1' elsif params[x].to_s.falsy? - bitprefs_exclude ||= "0"*bitprefs_length + bitprefs_exclude ||= "0" * bitprefs_length bitprefs_exclude[attr_idx] = '1' end end @@ -743,13 +743,13 @@ class User < ApplicationRecord if bitprefs_include bitprefs_include.reverse! q = q.where("bit_prefs::bit(:len) & :bits::bit(:len) = :bits::bit(:len)", - {:len => bitprefs_length, :bits => bitprefs_include}) + :len => bitprefs_length, :bits => bitprefs_include) end if bitprefs_exclude bitprefs_exclude.reverse! q = q.where("bit_prefs::bit(:len) & :bits::bit(:len) = 0::bit(:len)", - {:len => bitprefs_length, :bits => bitprefs_exclude}) + :len => bitprefs_length, :bits => bitprefs_exclude) end if params[:current_user_first].to_s.truthy? && !CurrentUser.is_anonymous? diff --git a/app/models/user_feedback.rb b/app/models/user_feedback.rb index a15bcbd04..85f302b34 100644 --- a/app/models/user_feedback.rb +++ b/app/models/user_feedback.rb @@ -9,10 +9,10 @@ class UserFeedback < ApplicationRecord validate :user_is_not_creator after_create :create_dmail, unless: :disable_dmail_notification after_update(:if => ->(rec) { CurrentUser.id != rec.creator_id}) do |rec| - ModAction.log(%{#{CurrentUser.name} updated user feedback for "#{rec.user.name}":/users/#{rec.user_id}},:user_feedback_update) + ModAction.log(%{#{CurrentUser.name} updated user feedback for "#{rec.user.name}":/users/#{rec.user_id}}, :user_feedback_update) end after_destroy(:if => ->(rec) { CurrentUser.id != rec.creator_id}) do |rec| - ModAction.log(%{#{CurrentUser.name} deleted user feedback for "#{rec.user.name}":/users/#{rec.user_id}},:user_feedback_delete) + ModAction.log(%{#{CurrentUser.name} deleted user feedback for "#{rec.user.name}":/users/#{rec.user_id}}, :user_feedback_delete) end module SearchMethods @@ -77,7 +77,7 @@ class UserFeedback < ApplicationRecord errors[:creator] << "cannot submit feedback" end end - + def user_is_not_creator if user_id == creator_id errors[:creator] << "cannot submit feedback for yourself" diff --git a/app/models/wiki_page.rb b/app/models/wiki_page.rb index ec70f2049..ef88dea28 100644 --- a/app/models/wiki_page.rb +++ b/app/models/wiki_page.rb @@ -1,5 +1,5 @@ class WikiPage < ApplicationRecord - class RevertError < Exception ; end + class RevertError < Exception; end META_WIKIS = ["list_of_", "tag_group:", "pool_group:", "howto:", "about:", "help:", "template:"] @@ -128,13 +128,13 @@ class WikiPage < ApplicationRecord tag_was = Tag.find_by_name(Tag.normalize_name(title_was)) if tag_was.present? && tag_was.post_count > 0 - warnings[:base] << %Q!Warning: {{#{title_was}}} still has #{tag_was.post_count} #{"post".pluralize(tag_was.post_count)}. Be sure to move the posts! + warnings[:base] << %!Warning: {{#{title_was}}} still has #{tag_was.post_count} #{"post".pluralize(tag_was.post_count)}. Be sure to move the posts! end broken_wikis = WikiPage.linked_to(title_was) if broken_wikis.count > 0 broken_wiki_search = Rails.application.routes.url_helpers.wiki_pages_path(search: { linked_to: title_was }) - warnings[:base] << %Q!Warning: [[#{title_was}]] is still linked from "#{broken_wikis.count} #{"other wiki page".pluralize(broken_wikis.count)}":[#{broken_wiki_search}]. Update #{broken_wikis.count > 1 ? "these wikis" : "this wiki"} to link to [[#{title}]] instead! + warnings[:base] << %!Warning: [[#{title_was}]] is still linked from "#{broken_wikis.count} #{"other wiki page".pluralize(broken_wikis.count)}":[#{broken_wiki_search}]. Update #{(broken_wikis.count > 1) ? "these wikis" : "this wiki"} to link to [[#{title}]] instead! end end diff --git a/app/presenters/post_presenter.rb b/app/presenters/post_presenter.rb index 48a3aa11c..430b2c33a 100644 --- a/app/presenters/post_presenter.rb +++ b/app/presenters/post_presenter.rb @@ -173,12 +173,12 @@ class PostPresenter < Presenter end def has_nav_links?(template) - has_sequential_navigation?(template.params) || @post.pools.undeleted.any? || @post.favorite_groups(active_id=template.params[:favgroup_id]).any? + has_sequential_navigation?(template.params) || @post.pools.undeleted.any? || @post.favorite_groups(active_id = template.params[:favgroup_id]).any? end def has_sequential_navigation?(params) return false if Tag.has_metatag?(params[:q], :order, :ordfav, :ordpool) return false if params[:pool_id].present? || params[:favgroup_id].present? - return CurrentUser.user.enable_sequential_post_navigation + return CurrentUser.user.enable_sequential_post_navigation end end diff --git a/app/presenters/presenter.rb b/app/presenters/presenter.rb index bbf7c0512..86a2f7363 100644 --- a/app/presenters/presenter.rb +++ b/app/presenters/presenter.rb @@ -4,7 +4,7 @@ class Presenter end def self.u(s) - URI.escape(s) + CGI.escape(s) end def h(s) diff --git a/app/presenters/tag_set_presenter.rb b/app/presenters/tag_set_presenter.rb index e244c323d..3e50dedd7 100644 --- a/app/presenters/tag_set_presenter.rb +++ b/app/presenters/tag_set_presenter.rb @@ -1,8 +1,7 @@ -=begin rdoc - A tag set represents a set of tags that are displayed together. - This class makes it easy to fetch the categories for all the - tags in one call instead of fetching them sequentially. -=end +# rdoc +# A tag set represents a set of tags that are displayed together. +# This class makes it easy to fetch the categories for all the +# tags in one call instead of fetching them sequentially. class TagSetPresenter < Presenter extend Memoist @@ -77,7 +76,7 @@ class TagSetPresenter < Presenter artists = "drawn by #{artists}" if artists.present? strings = "#{characters} #{copyrights} #{artists}" - strings.blank? ? default : strings + strings.presence || default end private @@ -133,7 +132,7 @@ class TagSetPresenter < Presenter if count >= 10_000 post_count = "#{count / 1_000}k" elsif count >= 1_000 - post_count = "%.1fk" % (count / 1_000.0) + post_count = format("%.1fk", (count / 1_000.0)) else post_count = count end diff --git a/app/presenters/user_presenter.rb b/app/presenters/user_presenter.rb index 1e16701b1..963ddab0c 100644 --- a/app/presenters/user_presenter.rb +++ b/app/presenters/user_presenter.rb @@ -51,9 +51,9 @@ class UserPresenter slots_tooltip = "Next free slot: #{template.time_ago_in_words(user.next_free_upload_slot)}" limit_tooltip = <<-EOS.strip_heredoc Base: #{user.base_upload_limit} - Del. Rate: #{"%.2f" % user.adjusted_deletion_confidence} - Multiplier: (1 - (#{"%.2f" % user.adjusted_deletion_confidence} / 15)) = #{user.upload_limit_multiplier} - Upload Limit: #{user.base_upload_limit} * #{"%.2f" % user.upload_limit_multiplier} = #{user.max_upload_limit} + Del. Rate: #{format("%.2f", user.adjusted_deletion_confidence)} + Multiplier: (1 - (#{format("%.2f", user.adjusted_deletion_confidence)} / 15)) = #{user.upload_limit_multiplier} + Upload Limit: #{user.base_upload_limit} * #{format("%.2f", user.upload_limit_multiplier)} = #{user.max_upload_limit} EOS %{#{user.used_upload_slots} / #{user.max_upload_limit}}.html_safe @@ -164,7 +164,7 @@ class UserPresenter [] end end - + def previous_names(template) user.user_name_change_requests.map { |req| template.link_to req.original_name, req }.join(", ").html_safe end diff --git a/app/presenters/wiki_page_presenter.rb b/app/presenters/wiki_page_presenter.rb index 690dbecf5..cfd51d266 100644 --- a/app/presenters/wiki_page_presenter.rb +++ b/app/presenters/wiki_page_presenter.rb @@ -19,15 +19,15 @@ class WikiPagePresenter cbo = Diff::LCS::ContextDiffCallbacks.new diffs = thisarr.diff(otharr, cbo) - escape_html = ->(str) {str.gsub(/&/,'&').gsub(//,'>')} + escape_html = ->(str) {str.gsub(/&/, '&').gsub(//, '>')} - output = thisarr; + output = thisarr output.each { |q| q.replace(CGI.escape_html(q)) } diffs.reverse_each do |hunk| - newchange = hunk.max{|a,b| a.old_position <=> b.old_position} + newchange = hunk.max {|a, b| a.old_position <=> b.old_position} newstart = newchange.old_position - oldstart = hunk.min{|a,b| a.old_position <=> b.old_position}.old_position + oldstart = hunk.min {|a, b| a.old_position <=> b.old_position}.old_position if newchange.action == '+' output.insert(newstart, "") @@ -42,7 +42,7 @@ class WikiPagePresenter if chg.new_element.match(/^\r?\n$/) output.insert(chg.old_position, "[nl]") else - output.insert(chg.old_position, "#{escape_html[chg.new_element]}") + output.insert(chg.old_position, (escape_html[chg.new_element]).to_s) end end end @@ -52,7 +52,7 @@ class WikiPagePresenter end if hunk[0].action == '-' - output.insert((newstart == oldstart || newchange.action != '+') ? newstart+1 : newstart, "
    ") + output.insert((newstart == oldstart || newchange.action != '+') ? newstart + 1 : newstart, "") output.insert(oldstart, "") end end diff --git a/config.ru b/config.ru index 5aeb3fac7..401c7482f 100644 --- a/config.ru +++ b/config.ru @@ -1,6 +1,6 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) if defined?(Unicorn) && Rails.env.production? # Unicorn self-process killer @@ -10,7 +10,7 @@ if defined?(Unicorn) && Rails.env.production? use Unicorn::WorkerKiller::MaxRequests, 5_000, 10_000 # Max memory size (RSS) per worker - #use Unicorn::WorkerKiller::Oom, (192*(1024**2)), (256*(1024**2)) + # use Unicorn::WorkerKiller::Oom, (192*(1024**2)), (256*(1024**2)) end run Rails.application diff --git a/config/application.rb b/config/application.rb index e4941b226..0b05cff10 100644 --- a/config/application.rb +++ b/config/application.rb @@ -1,16 +1,16 @@ require_relative 'boot' require "rails" require "active_record/railtie" -#require "active_storage/engine" +# require "active_storage/engine" require "action_controller/railtie" require "action_view/railtie" require "action_mailer/railtie" require "active_job/railtie" -#require "action_cable/engine" -#require "action_mailbox/engine" -#require "action_text/engine" +# require "action_cable/engine" +# require "action_mailbox/engine" +# require "action_text/engine" require "rails/test_unit/railtie" -#require "sprockets/railtie" +# require "sprockets/railtie" Bundler.require(*Rails.groups) @@ -27,8 +27,8 @@ module Danbooru config.active_record.schema_format = :sql config.encoding = "utf-8" config.filter_parameters += [:password, :password_confirmation, :password_hash, :api_key] - #config.assets.enabled = true - #config.assets.version = '1.0' + # config.assets.enabled = true + # config.assets.version = '1.0' config.autoload_paths += %W(#{config.root}/app/presenters #{config.root}/app/logical #{config.root}/app/mailers) config.plugins = [:all] config.time_zone = 'Eastern Time (US & Canada)' @@ -58,17 +58,17 @@ module Danbooru } end - if File.exists?("#{config.root}/REVISION") + if File.exist?("#{config.root}/REVISION") config.x.git_hash = File.read("#{config.root}/REVISION").strip elsif system("type git > /dev/null && git rev-parse --show-toplevel > /dev/null") - config.x.git_hash = %x(git rev-parse --short HEAD).strip + config.x.git_hash = `git rev-parse --short HEAD`.strip else config.x.git_hash = nil end config.after_initialize do Rails.application.routes.default_url_options = { - host: Danbooru.config.hostname, + host: Danbooru.config.hostname } end end diff --git a/config/danbooru_default_config.rb b/config/danbooru_default_config.rb index a22c166d3..c209b14e3 100644 --- a/config/danbooru_default_config.rb +++ b/config/danbooru_default_config.rb @@ -1,4 +1,6 @@ module Danbooru + module_function + class Configuration # A secret key used to encrypt session cookies, among other things. If this # token is changed, existing login sessions will become invalid. If this @@ -136,7 +138,7 @@ module Danbooru # Return true if the given tag shouldn't count against the user's tag search limit. def is_unlimited_tag?(tag) - !!(tag =~ /\A(-?status:deleted|rating:s.*|limit:.+)\z/i) + tag.match?(/\A(-?status:deleted|rating:s.*|limit:.+)\z/i) end # After this many pages, the paginator will switch to sequential mode. @@ -195,8 +197,8 @@ module Danbooru hsts: { expires: 1.year, preload: true, - subdomains: false, - }, + subdomains: false + } } end @@ -224,7 +226,7 @@ module Danbooru # base_url - where to serve files from (default: http://#{hostname}/data) # hierarchical: false - store files in a single directory # hierarchical: true - store files in a hierarchical directory structure, based on the MD5 hash - StorageManager::Local.new(base_url: "#{CurrentUser.root_url}/data", base_dir: "#{Rails.root}/public/data", hierarchical: false) + StorageManager::Local.new(base_url: "#{CurrentUser.root_url}/data", base_dir: Rails.root.join("/public/data"), hierarchical: false) # Store files on one or more remote host(s). Configure SSH settings in # ~/.ssh_config or in the ssh_options param (ref: http://net-ssh.github.io/net-ssh/Net/SSH.html#method-c-start) @@ -259,9 +261,9 @@ module Danbooru # StorageManager::SFTP.new("www.example.com", base_dir: "/mnt/backup", ssh_options: {}) end -#TAG CONFIGURATION + # TAG CONFIGURATION - #Full tag configuration info for all tags + # Full tag configuration info for all tags def full_tag_config_info @full_tag_category_mapping ||= { "general" => { @@ -322,24 +324,24 @@ module Danbooru } end -#TAG ORDERS + # TAG ORDERS - #Sets the order of the split tag header list (presenters/tag_set_presenter.rb) + # Sets the order of the split tag header list (presenters/tag_set_presenter.rb) def split_tag_header_list - @split_tag_header_list ||= ["copyright","character","artist","general","meta"] + @split_tag_header_list ||= ["copyright", "character", "artist", "general", "meta"] end - #Sets the order of the categorized tag string (presenters/post_presenter.rb) + # Sets the order of the categorized tag string (presenters/post_presenter.rb) def categorized_tag_list - @categorized_tag_list ||= ["copyright","character","artist","meta","general"] + @categorized_tag_list ||= ["copyright", "character", "artist", "meta", "general"] end - #Sets the order of the related tag buttons (javascripts/related_tag.js) + # Sets the order of the related tag buttons (javascripts/related_tag.js) def related_tag_button_list - @related_tag_button_list ||= ["general","artist","character","copyright"] + @related_tag_button_list ||= ["general", "artist", "character", "copyright"] end -#END TAG + # END TAG # Any custom code you want to insert into the default layout without # having to modify the templates. @@ -377,7 +379,7 @@ module Danbooru end def can_user_see_post?(user, post) - if is_user_restricted?(user) && is_post_restricted?(post) + if is_user_restricted?(user) && is_post_restricted?(post) false else true @@ -479,7 +481,7 @@ module Danbooru # services will fail if you don't set a valid User-Agent. def http_headers { - "User-Agent" => "#{Danbooru.config.canonical_app_name}/#{Rails.application.config.x.git_hash}", + "User-Agent" => "#{Danbooru.config.canonical_app_name}/#{Rails.application.config.x.git_hash}" } end @@ -487,7 +489,7 @@ module Danbooru # proxy example: # {http_proxyaddr: "", http_proxyport: "", http_proxyuser: nil, http_proxypass: nil} { - headers: Danbooru.config.http_headers, + headers: Danbooru.config.http_headers } end @@ -646,17 +648,11 @@ module Danbooru def method_missing(method, *args) var = ENV["DANBOORU_#{method.to_s.upcase.chomp("?")}"] - if var.present? - var - else - custom_configuration.send(method, *args) - end + var.presence || custom_configuration.send(method, *args) end end def config - @configuration ||= EnvironmentConfiguration.new + @config ||= EnvironmentConfiguration.new end - - module_function :config end diff --git a/config/environments/production.rb b/config/environments/production.rb index 7e8f71c86..b8f21f705 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -51,7 +51,7 @@ Rails.application.configure do config.log_level = :error # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] + config.log_tags = [:request_id] # Use a different cache store in production. # config.cache_store = :mem_cache_store diff --git a/config/environments/test.rb b/config/environments/test.rb index 47e5f5ea6..eebb71d5e 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -5,7 +5,7 @@ Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. - + config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application diff --git a/config/initializers/cache_store.rb b/config/initializers/cache_store.rb index 7417464e9..1c9f1eed2 100644 --- a/config/initializers/cache_store.rb +++ b/config/initializers/cache_store.rb @@ -7,11 +7,11 @@ Rails.application.configure do { url: Danbooru.config.redis_url, namespace: nil, - connect_timeout: 30, # default: 20 seconds - write_timeout: 0.5, # default: 1 second - read_timeout: 0.5, # default: 1 second + connect_timeout: 30, # default: 20 seconds + write_timeout: 0.5, # default: 1 second + read_timeout: 0.5, # default: 1 second reconnect_attempts: 0, # default: 0 - error_handler: ->(method:, returning:, exception:) { + error_handler: lambda { |method:, returning:, exception:| DanbooruLogger.log(exception, method: method, returning: returning) } } diff --git a/config/initializers/mechanize_patch.rb b/config/initializers/mechanize_patch.rb index a8b830610..875c28b9d 100644 --- a/config/initializers/mechanize_patch.rb +++ b/config/initializers/mechanize_patch.rb @@ -31,7 +31,7 @@ if Rails.env.test? referer = current_page, redirects = 0 ) - action = "#{method.to_s.upcase} #{uri.to_s}" + action = "#{method.to_s.upcase} #{uri}" retry_count = 0 begin @@ -43,13 +43,13 @@ if Rails.env.test? # Pass on the error if we've tried too many times. if retry_count >= MAX_RESET_RETRIES print "R" - #puts "**** WARN: Mechanize retried connection reset #{MAX_RESET_RETRIES} times and never succeeded: #{action}" + # puts "**** WARN: Mechanize retried connection reset #{MAX_RESET_RETRIES} times and never succeeded: #{action}" raise end # Otherwise, shutdown the persistent HTTP connection and try again. print "R" - #puts "**** WARN: Mechanize retrying connection reset error: #{action}" + # puts "**** WARN: Mechanize retrying connection reset error: #{action}" retry_count += 1 self.http.shutdown retry @@ -58,7 +58,7 @@ if Rails.env.test? # Alias so #fetch actually uses our new #fetch_with_retry to wrap the # old one aliased as #fetch_without_retry. - alias_method :fetch_without_retry, :fetch - alias_method :fetch, :fetch_with_retry + alias fetch_without_retry fetch + alias fetch fetch_with_retry end -end \ No newline at end of file +end diff --git a/config/initializers/simple_form.rb b/config/initializers/simple_form.rb index e2d5de04f..65c15ba19 100644 --- a/config/initializers/simple_form.rb +++ b/config/initializers/simple_form.rb @@ -5,8 +5,7 @@ SimpleForm.setup do |config| # wrapper, change the order or even add your own to the # stack. The options given below are used to wrap the # whole input. - config.wrappers :default, class: :input, - hint_class: :field_with_hint, error_class: :field_with_errors do |b| + config.wrappers :default, class: :input, hint_class: :field_with_hint, error_class: :field_with_errors do |b| ## Extensions enabled by default # Any of these extensions can be disabled for a # given input by passing: `f.input EXTENSION_NAME => false`. diff --git a/config/initializers/unicorn.rb b/config/initializers/unicorn.rb index 6fe2062c6..a0f7d5106 100644 --- a/config/initializers/unicorn.rb +++ b/config/initializers/unicorn.rb @@ -2,6 +2,6 @@ # This is needed when using Unicorn and preload_app is not set to true. # See https://newrelic.com/docs/ruby/no-data-with-unicorn if defined? ::NewRelic - ::NewRelic::Agent.manual_start() + ::NewRelic::Agent.manual_start ::NewRelic::Agent.after_fork(:force_reconnect => true) end diff --git a/config/routes.rb b/config/routes.rb index 3d95f51d9..a86547c29 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,4 @@ Rails.application.routes.draw do - namespace :admin do resources :users, :only => [:edit, :update] resource :alias_and_implication_import, :only => [:new, :create] @@ -155,7 +154,7 @@ Rails.application.routes.draw do end resources :ip_bans resources :ip_addresses, only: [:index] - resource :iqdb_queries, :only => [:show, :create] do + resource :iqdb_queries, :only => [:show, :create] do collection do get :preview get :check, to: redirect {|path_params, req| "/iqdb_queries?#{req.query_string}"} @@ -183,7 +182,7 @@ Rails.application.routes.draw do end resource :order, :only => [:edit], :controller => "pool_orders" end - resource :pool_element, :only => [:create, :destroy] do + resource :pool_element, :only => [:create, :destroy] do collection do get :all_select end @@ -303,12 +302,12 @@ Rails.application.routes.draw do resources :fposts, :controller => "forum_posts" # legacy aliases - get "/artist" => redirect {|params, req| "/artists?page=#{req.params[:page]}&search[name]=#{CGI::escape(req.params[:name].to_s)}"} + get "/artist" => redirect {|params, req| "/artists?page=#{req.params[:page]}&search[name]=#{CGI.escape(req.params[:name].to_s)}"} get "/artist/index.xml", :controller => "legacy", :action => "artists", :format => "xml" get "/artist/index.json", :controller => "legacy", :action => "artists", :format => "json" get "/artist/index" => redirect {|params, req| "/artists?page=#{req.params[:page]}"} get "/artist/show/:id" => redirect("/artists/%{id}") - get "/artist/show" => redirect {|params, req| "/artists?name=#{CGI::escape(req.params[:name].to_s)}"} + get "/artist/show" => redirect {|params, req| "/artists?name=#{CGI.escape(req.params[:name].to_s)}"} get "/artist/history/:id" => redirect("/artist_versions?search[artist_id]=%{id}") get "/artist/recent_changes" => redirect("/artist_versions") @@ -318,7 +317,7 @@ Rails.application.routes.draw do get "/comment/new" => redirect("/comments") get("/comment/search" => redirect do |params, req| if req.params[:query] =~ /^user:(.+)/i - "/comments?group_by=comment&search[creator_name]=#{CGI::escape($1)}" + "/comments?group_by=comment&search[creator_name]=#{CGI.escape($1)}" else "/comments/search" end @@ -333,7 +332,7 @@ Rails.application.routes.draw do get "/forum/show/:id" => redirect {|params, req| "/forum_posts/#{req.params[:id]}?page=#{req.params[:page]}"} get "/forum/search" => redirect("/forum_posts/search") - get "/help/:title" => redirect {|params, req| ("/wiki_pages?title=#{CGI::escape('help:' + req.params[:title])}")} + get "/help/:title" => redirect {|params, req| "/wiki_pages?title=#{CGI.escape('help:' + req.params[:title])}"} get "/note" => redirect {|params, req| "/notes?page=#{req.params[:page]}"} get "/note/index" => redirect {|params, req| "/notes?page=#{req.params[:page]}"} @@ -348,12 +347,12 @@ Rails.application.routes.draw do get "/post/index.xml", :controller => "legacy", :action => "posts", :format => "xml" get "/post/index.json", :controller => "legacy", :action => "posts", :format => "json" get "/post/piclens", :controller => "legacy", :action => "unavailable" - get "/post/index" => redirect {|params, req| "/posts?tags=#{CGI::escape(req.params[:tags].to_s)}&page=#{req.params[:page]}"} - get "/post" => redirect {|params, req| "/posts?tags=#{CGI::escape(req.params[:tags].to_s)}&page=#{req.params[:page]}"} + get "/post/index" => redirect {|params, req| "/posts?tags=#{CGI.escape(req.params[:tags].to_s)}&page=#{req.params[:page]}"} + get "/post" => redirect {|params, req| "/posts?tags=#{CGI.escape(req.params[:tags].to_s)}&page=#{req.params[:page]}"} get "/post/upload" => redirect("/uploads/new") get "/post/moderate" => redirect("/moderator/post/queue") - get "/post/atom" => redirect {|params, req| "/posts.atom?tags=#{CGI::escape(req.params[:tags].to_s)}"} - get "/post/atom.feed" => redirect {|params, req| "/posts.atom?tags=#{CGI::escape(req.params[:tags].to_s)}"} + get "/post/atom" => redirect {|params, req| "/posts.atom?tags=#{CGI.escape(req.params[:tags].to_s)}"} + get "/post/atom.feed" => redirect {|params, req| "/posts.atom?tags=#{CGI.escape(req.params[:tags].to_s)}"} get "/post/popular_by_day" => redirect("/explore/posts/popular") get "/post/popular_by_week" => redirect("/explore/posts/popular") get "/post/popular_by_month" => redirect("/explore/posts/popular") @@ -372,10 +371,10 @@ Rails.application.routes.draw do get "/tag/index.xml", :controller => "legacy", :action => "tags", :format => "xml" get "/tag/index.json", :controller => "legacy", :action => "tags", :format => "json" - get "/tag" => redirect {|params, req| "/tags?page=#{req.params[:page]}&search[name_matches]=#{CGI::escape(req.params[:name].to_s)}&search[order]=#{req.params[:order]}&search[category]=#{req.params[:type]}"} - get "/tag/index" => redirect {|params, req| "/tags?page=#{req.params[:page]}&search[name_matches]=#{CGI::escape(req.params[:name].to_s)}&search[order]=#{req.params[:order]}"} + get "/tag" => redirect {|params, req| "/tags?page=#{req.params[:page]}&search[name_matches]=#{CGI.escape(req.params[:name].to_s)}&search[order]=#{req.params[:order]}&search[category]=#{req.params[:type]}"} + get "/tag/index" => redirect {|params, req| "/tags?page=#{req.params[:page]}&search[name_matches]=#{CGI.escape(req.params[:name].to_s)}&search[order]=#{req.params[:order]}"} - get "/tag_implication" => redirect {|params, req| "/tag_implications?search[name_matches]=#{CGI::escape(req.params[:query].to_s)}"} + get "/tag_implication" => redirect {|params, req| "/tag_implications?search[name_matches]=#{CGI.escape(req.params[:query].to_s)}"} get "/user/index.xml", :controller => "legacy", :action => "users", :format => "xml" get "/user/index.json", :controller => "legacy", :action => "users", :format => "json" @@ -392,7 +391,7 @@ Rails.application.routes.draw do get "/wiki" => redirect {|params, req| "/wiki_pages?page=#{req.params[:page]}"} get "/wiki/index" => redirect {|params, req| "/wiki_pages?page=#{req.params[:page]}"} get "/wiki/rename" => redirect("/wiki_pages") - get "/wiki/show" => redirect {|params, req| "/wiki_pages?title=#{CGI::escape(req.params[:title].to_s)}"} + get "/wiki/show" => redirect {|params, req| "/wiki_pages?title=#{CGI.escape(req.params[:title].to_s)}"} get "/wiki/recent_changes" => redirect {|params, req| "/wiki_page_versions?search[updater_id]=#{req.params[:user_id]}"} get "/wiki/history/:title" => redirect("/wiki_page_versions?title=%{title}") diff --git a/config/unicorn/development.rb b/config/unicorn/development.rb index a1f7a7517..2003277cc 100644 --- a/config/unicorn/development.rb +++ b/config/unicorn/development.rb @@ -14,7 +14,7 @@ user 'danbooru', 'danbooru' # Fill path to your app working_directory app_path -# Should be 'production' by default, otherwise use other env +# Should be 'production' by default, otherwise use other env rails_env = ENV['RAILS_ENV'] || 'production' # Log everything to one file diff --git a/config/unicorn/production.rb b/config/unicorn/production.rb index 778792fa7..e53d8a24f 100644 --- a/config/unicorn/production.rb +++ b/config/unicorn/production.rb @@ -5,7 +5,7 @@ app_path = "/var/www/danbooru2/current" worker_processes 20 timeout 180 -#listen "127.0.0.1:9000", :tcp_nopush => true +# listen "127.0.0.1:9000", :tcp_nopush => true listen "/tmp/.unicorn.sock", :backlog => 512 # Spawn unicorn master worker for user apps (group: apps) @@ -41,7 +41,7 @@ run_once = true before_fork do |server, worker| # the following is highly recomended for Rails + "preload_app true" # as there's no need for the master process to hold a connection - defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! + defined?(ActiveRecord::Base) && ActiveRecord::Base.connection.disconnect! # Occasionally, it may be necessary to run non-idempotent code in the # master before forking. Keep in mind the above disconnect! example diff --git a/config/unicorn/staging.rb b/config/unicorn/staging.rb index 4bb84cebe..7164d159d 100644 --- a/config/unicorn/staging.rb +++ b/config/unicorn/staging.rb @@ -14,7 +14,7 @@ user 'danbooru', 'danbooru' # Fill path to your app working_directory app_path -# Should be 'production' by default, otherwise use other env +# Should be 'production' by default, otherwise use other env rails_env = ENV['RAILS_ENV'] || 'staging' # Log everything to one file @@ -26,8 +26,8 @@ pid "#{app_path}/tmp/pids/unicorn.pid" before_fork do |server, worker| old_pid = "#{server.config[:pid]}.oldbin" - - if File.exists?(old_pid) && server.pid != old_pid + + if File.exist?(old_pid) && server.pid != old_pid begin Process.kill("QUIT", File.read(old_pid).to_i) rescue Errno::ENOENT, Errno::ESRCH @@ -44,4 +44,4 @@ after_fork do |server, worker| if defined?(ActiveRecord::Base) ActiveRecord::Base.establish_connection end -end \ No newline at end of file +end diff --git a/db/migrate/20130326035904_create_user_name_change_requests.rb b/db/migrate/20130326035904_create_user_name_change_requests.rb index 38f76e392..99ebe44ef 100644 --- a/db/migrate/20130326035904_create_user_name_change_requests.rb +++ b/db/migrate/20130326035904_create_user_name_change_requests.rb @@ -10,7 +10,7 @@ class CreateUserNameChangeRequests < ActiveRecord::Migration[4.2] t.text :rejection_reason t.timestamps end - + add_index :user_name_change_requests, :user_id add_index :user_name_change_requests, :original_name end diff --git a/db/migrate/20130331180246_create_key_values.rb b/db/migrate/20130331180246_create_key_values.rb index 09faa312c..0c7254cb0 100644 --- a/db/migrate/20130331180246_create_key_values.rb +++ b/db/migrate/20130331180246_create_key_values.rb @@ -5,7 +5,7 @@ class CreateKeyValues < ActiveRecord::Migration[4.2] t.text :value t.timestamps end - + add_index :key_values, :key, :unique => true end end diff --git a/db/migrate/20130331182719_add_pixiv_id_to_posts.rb b/db/migrate/20130331182719_add_pixiv_id_to_posts.rb index 6c0fe1433..71daee532 100644 --- a/db/migrate/20130331182719_add_pixiv_id_to_posts.rb +++ b/db/migrate/20130331182719_add_pixiv_id_to_posts.rb @@ -5,7 +5,7 @@ class AddPixivIdToPosts < ActiveRecord::Migration[4.2] execute "drop index index_posts_on_pixiv_id" execute "create index index_posts_on_pixiv_id on posts (pixiv_id) where pixiv_id is not null" end - + def down execute "set statement_timeout = 0" remove_column :posts, :pixiv_id diff --git a/db/migrate/20130914175431_change_tag_subscription_tag_query_delimiter.rb b/db/migrate/20130914175431_change_tag_subscription_tag_query_delimiter.rb index 201f6fd6b..3784e6ca3 100644 --- a/db/migrate/20130914175431_change_tag_subscription_tag_query_delimiter.rb +++ b/db/migrate/20130914175431_change_tag_subscription_tag_query_delimiter.rb @@ -1,8 +1,8 @@ class ChangeTagSubscriptionTagQueryDelimiter < ActiveRecord::Migration[4.2] def change execute "set statement_timeout = 0" - #TagSubscription.find_each do |tag_subscription| + # TagSubscription.find_each do |tag_subscription| # tag_subscription.update_column(:tag_query, tag_subscription.tag_query.scan(/\S+/).join("\n")) - #end + # end end end diff --git a/db/migrate/20150120005624_remove_unused_indexes.rb b/db/migrate/20150120005624_remove_unused_indexes.rb index afdde3dd9..0db530ab6 100644 --- a/db/migrate/20150120005624_remove_unused_indexes.rb +++ b/db/migrate/20150120005624_remove_unused_indexes.rb @@ -1,7 +1,7 @@ class RemoveUnusedIndexes < ActiveRecord::Migration[4.2] def change execute "set statement_timeout = 0" - #remove_index :posts, :source + # remove_index :posts, :source remove_index :posts, :uploader_ip_addr end end diff --git a/db/migrate/20161024220345_add_min_level_to_forum_topics.rb b/db/migrate/20161024220345_add_min_level_to_forum_topics.rb index 9ea6b40b0..adb18ab12 100644 --- a/db/migrate/20161024220345_add_min_level_to_forum_topics.rb +++ b/db/migrate/20161024220345_add_min_level_to_forum_topics.rb @@ -1,5 +1,5 @@ class AddMinLevelToForumTopics < ActiveRecord::Migration[4.2] def change - add_column :forum_topics, :min_level, :integer, :default => 0, :null => false + add_column :forum_topics, :min_level, :integer, :default => 0, :null => false end end diff --git a/db/migrate/20161101003139_create_post_approvals.rb b/db/migrate/20161101003139_create_post_approvals.rb index e60e924f5..130833677 100644 --- a/db/migrate/20161101003139_create_post_approvals.rb +++ b/db/migrate/20161101003139_create_post_approvals.rb @@ -1,8 +1,8 @@ class CreatePostApprovals < ActiveRecord::Migration[4.2] def change create_table :post_approvals do |t| - t.integer :user_id, null: false - t.integer :post_id, null: false + t.integer :user_id, null: false + t.integer :post_id, null: false t.timestamps null: false end diff --git a/db/migrate/20161221225849_drop_transaction_log_items.rb b/db/migrate/20161221225849_drop_transaction_log_items.rb index 4e8dbabde..b7af2bbfd 100644 --- a/db/migrate/20161221225849_drop_transaction_log_items.rb +++ b/db/migrate/20161221225849_drop_transaction_log_items.rb @@ -1,5 +1,5 @@ class DropTransactionLogItems < ActiveRecord::Migration[4.2] def up - drop_table :transaction_log_items + drop_table :transaction_log_items end end diff --git a/db/migrate/20161229001201_drop_pool_versions.rb b/db/migrate/20161229001201_drop_pool_versions.rb index 082a1e770..3f4fad377 100644 --- a/db/migrate/20161229001201_drop_pool_versions.rb +++ b/db/migrate/20161229001201_drop_pool_versions.rb @@ -1,9 +1,9 @@ class DropPoolVersions < ActiveRecord::Migration[4.2] def up - drop_table :pool_versions + drop_table :pool_versions end def down - raise NotImplementedError + raise NotImplementedError end end diff --git a/db/migrate/20170106012138_create_token_buckets.rb b/db/migrate/20170106012138_create_token_buckets.rb index 09823f1e1..a41a7067a 100644 --- a/db/migrate/20170106012138_create_token_buckets.rb +++ b/db/migrate/20170106012138_create_token_buckets.rb @@ -1,10 +1,10 @@ class CreateTokenBuckets < ActiveRecord::Migration[4.2] def up - execute "create unlogged table token_buckets (user_id integer, last_touched_at timestamp not null, token_count real not null)" - add_index :token_buckets, :user_id, :unique => true + execute "create unlogged table token_buckets (user_id integer, last_touched_at timestamp not null, token_count real not null)" + add_index :token_buckets, :user_id, :unique => true end def down - raise NotImplementedError + raise NotImplementedError end end diff --git a/db/migrate/20170117233040_add_trigram_index_to_users.rb b/db/migrate/20170117233040_add_trigram_index_to_users.rb index e780305b8..235b7da1c 100644 --- a/db/migrate/20170117233040_add_trigram_index_to_users.rb +++ b/db/migrate/20170117233040_add_trigram_index_to_users.rb @@ -1,6 +1,6 @@ class AddTrigramIndexToUsers < ActiveRecord::Migration[4.2] def change - execute "set statement_timeout = 0" + execute "set statement_timeout = 0" execute "create index index_users_on_name_trgm on users using gin (lower(name) gin_trgm_ops)" end end diff --git a/db/migrate/20170314235626_add_tags_to_saved_searches.rb b/db/migrate/20170314235626_add_tags_to_saved_searches.rb index d4f8f024a..1aeae70b3 100644 --- a/db/migrate/20170314235626_add_tags_to_saved_searches.rb +++ b/db/migrate/20170314235626_add_tags_to_saved_searches.rb @@ -1,8 +1,8 @@ class AddTagsToSavedSearches < ActiveRecord::Migration[4.2] def change - execute "set statement_timeout = 0" - add_column :saved_searches, :labels, "text", array: true, null: false, default: [] - add_index :saved_searches, :labels, using: :gin - rename_column :saved_searches, :tag_query, :query + execute "set statement_timeout = 0" + add_column :saved_searches, :labels, "text", array: true, null: false, default: [] + add_index :saved_searches, :labels, using: :gin + rename_column :saved_searches, :tag_query, :query end end diff --git a/db/migrate/20170316224630_drop_post_versions.rb b/db/migrate/20170316224630_drop_post_versions.rb index 7f4d4aa9a..92519808d 100644 --- a/db/migrate/20170316224630_drop_post_versions.rb +++ b/db/migrate/20170316224630_drop_post_versions.rb @@ -1,6 +1,6 @@ class DropPostVersions < ActiveRecord::Migration[4.2] def change - execute "set statement_timeout = 0" - drop_table :post_versions + execute "set statement_timeout = 0" + drop_table :post_versions end end diff --git a/db/migrate/20170330230231_add_forum_post_id_to_tag_requests.rb b/db/migrate/20170330230231_add_forum_post_id_to_tag_requests.rb index 8293cd0b3..699207bed 100644 --- a/db/migrate/20170330230231_add_forum_post_id_to_tag_requests.rb +++ b/db/migrate/20170330230231_add_forum_post_id_to_tag_requests.rb @@ -1,9 +1,9 @@ class AddForumPostIdToTagRequests < ActiveRecord::Migration[4.2] def change - ApplicationRecord.without_timeout do - add_column :tag_aliases, :forum_post_id, :integer - add_column :tag_implications, :forum_post_id, :integer - add_column :bulk_update_requests, :forum_post_id, :integer - end + ApplicationRecord.without_timeout do + add_column :tag_aliases, :forum_post_id, :integer + add_column :tag_implications, :forum_post_id, :integer + add_column :bulk_update_requests, :forum_post_id, :integer + end end end diff --git a/db/migrate/20170413000209_add_title_to_bulk_update_requests.rb b/db/migrate/20170413000209_add_title_to_bulk_update_requests.rb index 35da93031..ae98096d1 100644 --- a/db/migrate/20170413000209_add_title_to_bulk_update_requests.rb +++ b/db/migrate/20170413000209_add_title_to_bulk_update_requests.rb @@ -1,5 +1,5 @@ class AddTitleToBulkUpdateRequests < ActiveRecord::Migration[4.2] def change - add_column :bulk_update_requests, :title, :text + add_column :bulk_update_requests, :title, :text end end diff --git a/db/migrate/20170414005856_add_unique_name_constraint_to_users.rb b/db/migrate/20170414005856_add_unique_name_constraint_to_users.rb index 96df82d36..70244ae75 100644 --- a/db/migrate/20170414005856_add_unique_name_constraint_to_users.rb +++ b/db/migrate/20170414005856_add_unique_name_constraint_to_users.rb @@ -1,8 +1,8 @@ class AddUniqueNameConstraintToUsers < ActiveRecord::Migration[4.2] def up - User.without_timeout do - remove_index :users, name: "index_users_on_name" - execute "create unique index index_users_on_name on users(lower(name))" - end + User.without_timeout do + remove_index :users, name: "index_users_on_name" + execute "create unique index index_users_on_name on users(lower(name))" + end end end diff --git a/db/migrate/20170414233617_add_updated_at_index_to_pools.rb b/db/migrate/20170414233617_add_updated_at_index_to_pools.rb index 8c06a5183..86e34faf7 100644 --- a/db/migrate/20170414233617_add_updated_at_index_to_pools.rb +++ b/db/migrate/20170414233617_add_updated_at_index_to_pools.rb @@ -1,5 +1,5 @@ class AddUpdatedAtIndexToPools < ActiveRecord::Migration[4.2] def change - add_index :pools, :updated_at + add_index :pools, :updated_at end end diff --git a/db/migrate/20170512221200_create_post_replacements.rb b/db/migrate/20170512221200_create_post_replacements.rb index 166cd7098..1499f7d10 100644 --- a/db/migrate/20170512221200_create_post_replacements.rb +++ b/db/migrate/20170512221200_create_post_replacements.rb @@ -1,10 +1,10 @@ class CreatePostReplacements < ActiveRecord::Migration[4.2] def change create_table :post_replacements do |t| - t.integer :post_id, null: false - t.integer :creator_id, null: false - t.text :original_url, null: false - t.text :replacement_url, null: false + t.integer :post_id, null: false + t.integer :creator_id, null: false + t.text :original_url, null: false + t.text :replacement_url, null: false t.timestamps null: false end diff --git a/db/migrate/20170515235205_add_sort_indexes_to_forum_topics.rb b/db/migrate/20170515235205_add_sort_indexes_to_forum_topics.rb index 99ddd8e0e..4d4ddf7fc 100644 --- a/db/migrate/20170515235205_add_sort_indexes_to_forum_topics.rb +++ b/db/migrate/20170515235205_add_sort_indexes_to_forum_topics.rb @@ -1,5 +1,5 @@ class AddSortIndexesToForumTopics < ActiveRecord::Migration[4.2] def change - add_index :forum_topics, [:is_sticky, :updated_at] + add_index :forum_topics, [:is_sticky, :updated_at] end end diff --git a/db/migrate/20170519204506_fix_last_noted_at_index_on_posts.rb b/db/migrate/20170519204506_fix_last_noted_at_index_on_posts.rb index 4cb5b6ffa..497ebad4d 100644 --- a/db/migrate/20170519204506_fix_last_noted_at_index_on_posts.rb +++ b/db/migrate/20170519204506_fix_last_noted_at_index_on_posts.rb @@ -6,7 +6,7 @@ class FixLastNotedAtIndexOnPosts < ActiveRecord::Migration[4.2] remove_index :posts, column: :last_noted_at add_index :posts, :last_noted_at, order: "DESC NULLS LAST" - + execute "analyze posts" end end diff --git a/db/migrate/20170914200122_add_is_spam_to_dmails.rb b/db/migrate/20170914200122_add_is_spam_to_dmails.rb index 2db3592cf..e109b09ca 100644 --- a/db/migrate/20170914200122_add_is_spam_to_dmails.rb +++ b/db/migrate/20170914200122_add_is_spam_to_dmails.rb @@ -1,7 +1,7 @@ class AddIsSpamToDmails < ActiveRecord::Migration[4.2] def change - Dmail.without_timeout do - add_column :dmails, :is_spam, :boolean, default: false - end + Dmail.without_timeout do + add_column :dmails, :is_spam, :boolean, default: false + end end end diff --git a/db/migrate/20171127195124_add_trigram_index_to_tags.rb b/db/migrate/20171127195124_add_trigram_index_to_tags.rb index 6b468a4fc..b0b3c2085 100644 --- a/db/migrate/20171127195124_add_trigram_index_to_tags.rb +++ b/db/migrate/20171127195124_add_trigram_index_to_tags.rb @@ -1,13 +1,13 @@ class AddTrigramIndexToTags < ActiveRecord::Migration[4.2] def up - Tag.without_timeout do - execute "create index index_tags_on_name_trgm on tags using gin (name gin_trgm_ops)" - end + Tag.without_timeout do + execute "create index index_tags_on_name_trgm on tags using gin (name gin_trgm_ops)" + end end def down - Tag.without_timeout do - execute "drop index index_tags_on_name_trgm" - end + Tag.without_timeout do + execute "drop index index_tags_on_name_trgm" + end end end diff --git a/db/migrate/20180916002448_add_trigram_index_to_artist_urls.rb b/db/migrate/20180916002448_add_trigram_index_to_artist_urls.rb index e3178901e..f832ecaba 100644 --- a/db/migrate/20180916002448_add_trigram_index_to_artist_urls.rb +++ b/db/migrate/20180916002448_add_trigram_index_to_artist_urls.rb @@ -1,7 +1,7 @@ class AddTrigramIndexToArtistUrls < ActiveRecord::Migration[5.2] def change execute "set statement_timeout = 0" - + change_table :artist_urls do |t| t.remove_index column: :url, name: :index_artist_urls_on_url t.remove_index column: :url, name: :index_artist_urls_on_url_pattern, opclass: :text_pattern_ops diff --git a/db/populate.rb b/db/populate.rb index f7babee42..12dd40213 100644 --- a/db/populate.rb +++ b/db/populate.rb @@ -2,14 +2,14 @@ require 'set' CurrentUser.ip_addr = "127.0.0.1" Delayed::Worker.delay_jobs = false -$used_names = Set.new([""]) +used_names = Set.new([""]) def rand_string(n, unique = false) string = "" n = rand(n) + 1 - while $used_names.include?(string) + while used_names.include?(string) consonants = "bcdfghjklmnpqrstvwxz".scan(/./) vowels = "aeiouy".scan(/./) string = "" @@ -20,7 +20,7 @@ def rand_string(n, unique = false) return string unless unique end - $used_names.add(string) + used_names.add(string) string end @@ -47,36 +47,35 @@ if User.count == 0 ) CurrentUser.user = user - User::Levels.constants.reject{ |x| x == :ADMIN }.each do |level| + User::Levels.constants.reject { |x| x == :ADMIN }.each do |level| newuser = User.create( - :name => level.to_s.downcase, - :password => "password1", - :password_confirmation => "password1" + name: level.to_s.downcase, + password: "password1", + password_confirmation: "password1" ) - newuser.promote_to!(User::Levels.const_get(level), {:is_upgrade => true, :skip_dmail => true}) + newuser.promote_to!(User::Levels.const_get(level), :is_upgrade => true, :skip_dmail => true) end newuser = User.create( :name => "banned", :password => "password1", :password_confirmation => "password1" - ) + ) Ban.create(:user_id => newuser.id, :reason => "from the start", :duration => 99999) newuser = User.create( :name => "uploader", :password => "password1", :password_confirmation => "password1" - ) - newuser.promote_to!(User::Levels::BUILDER, {:can_upload_free => true, :is_upgrade => true, :skip_dmail => true}) + ) + newuser.promote_to!(User::Levels::BUILDER, :can_upload_free => true, :is_upgrade => true, :skip_dmail => true) newuser = User.create( :name => "approver", :password => "password1", :password_confirmation => "password1" - ) - newuser.promote_to!(User::Levels::BUILDER, {:can_approve_posts => true, :is_upgrade => true, :skip_dmail => true}) - + ) + newuser.promote_to!(User::Levels::BUILDER, :can_approve_posts => true, :is_upgrade => true, :skip_dmail => true) end 0.upto(10) do |i| @@ -86,7 +85,7 @@ if User.count == 0 :password_confirmation => "password1" ) end - $used_names = Set.new([""]) + used_names = Set.new([""]) else puts "Skipping users" user = User.find_by_name("albert") @@ -101,7 +100,7 @@ if Upload.count == 0 1.upto(50) do |i| color1 = rand(4096).to_s(16) color2 = rand(4096).to_s(16) - width = rand(2000) + 100 + width = rand(100..2099) height = (width * (rand(0.5) + 1)).to_i url = "http://ipsumimage.appspot.com/#{width}x#{height},#{color1}" tags = rand(1_000_000_000).to_s.scan(/../).join(" ") @@ -144,7 +143,7 @@ if Artist.count == 0 20.times do |i| Artist.create(:name => rand_string(9, true)) end - $used_names = Set.new([""]) + used_names = Set.new([""]) else puts "Skipping artists" end @@ -155,7 +154,7 @@ if TagAlias.count == 0 20.times do |i| TagAlias.create(:antecedent_name => rand_string(9, true), :consequent_name => rand_string(9, true)) end - $used_names = Set.new([""]) + used_names = Set.new([""]) else puts "Skipping tag aliases" end @@ -166,7 +165,7 @@ if TagImplication.count == 0 20.times do |i| TagImplication.create(:antecedent_name => rand_string(9, true), :consequent_name => rand_string(9, true)) end - $used_names = Set.new([""]) + used_names = Set.new([""]) else puts "Skipping tag implications" end @@ -180,7 +179,7 @@ if Pool.count == 0 pool.add!(Post.order("random()").first) end end - $used_names = Set.new([""]) + used_names = Set.new([""]) end if Favorite.count == 0 diff --git a/lib/capistrano/tasks/nginx.rake b/lib/capistrano/tasks/nginx.rake index f31225f2d..e42dc1467 100644 --- a/lib/capistrano/tasks/nginx.rake +++ b/lib/capistrano/tasks/nginx.rake @@ -25,4 +25,4 @@ namespace :nginx do end end end -end \ No newline at end of file +end diff --git a/lib/tasks/images.rake b/lib/tasks/images.rake index 11524bb41..cd2597d2e 100644 --- a/lib/tasks/images.rake +++ b/lib/tasks/images.rake @@ -16,7 +16,7 @@ namespace :images do upload.generate_resizes(post.file_path) post.distribute_files end - + desc "Generate thumbnail-sized images of posts" task :generate_preview => :environment do width = 150 @@ -33,7 +33,7 @@ namespace :images do end end end - + desc "Generate large-sized images of posts" task :generate_large => :environment do post_id = ENV["id"] @@ -51,4 +51,3 @@ namespace :images do end end end - diff --git a/lib/tasks/iqdb.rake b/lib/tasks/iqdb.rake new file mode 100644 index 000000000..2e156e26d --- /dev/null +++ b/lib/tasks/iqdb.rake @@ -0,0 +1,9 @@ +namespace :iqdb do + task reindex_posts: :environment do + STDIN.each_line do |post_id| + puts post_id + post.remove_iqdb_async + post.update_iqdb_async + end + end +end diff --git a/script/fixes/004.rb b/script/fixes/004.rb old mode 100644 new mode 100755 diff --git a/script/fixes/005.rb b/script/fixes/005.rb old mode 100644 new mode 100755 index 29e2543a8..16e512b3d --- a/script/fixes/005.rb +++ b/script/fixes/005.rb @@ -7,7 +7,7 @@ Post.where("image_width > 850").find_each do |post| next end - if !File.exists?(post.file_path) + if !File.exist?(post.file_path) puts "NOT FOUND: #{post.id}" next end @@ -19,7 +19,7 @@ Post.where("image_width > 850").find_each do |post| resize = false - if !File.exists?(post.large_file_path) + if !File.exist?(post.large_file_path) puts "LARGE NOT FOUND: #{post.id}" resize = true end diff --git a/script/fixes/006.rb b/script/fixes/006.rb old mode 100644 new mode 100755 diff --git a/script/fixes/007.rb b/script/fixes/007.rb old mode 100644 new mode 100755 diff --git a/script/fixes/008.rb b/script/fixes/008.rb old mode 100644 new mode 100755 diff --git a/script/fixes/009.rb b/script/fixes/009.rb old mode 100644 new mode 100755 diff --git a/script/fixes/010.rb b/script/fixes/010.rb old mode 100644 new mode 100755 diff --git a/script/fixes/011.rb b/script/fixes/011.rb old mode 100644 new mode 100755 diff --git a/script/fixes/012.rb b/script/fixes/012.rb old mode 100644 new mode 100755 diff --git a/script/fixes/013.rb b/script/fixes/013.rb old mode 100644 new mode 100755 index d68ef3c56..6ec990de2 --- a/script/fixes/013.rb +++ b/script/fixes/013.rb @@ -9,26 +9,26 @@ Comment.find_each do |comment| puts "deleting comment #{comment.id}" comment.destroy end -end ; true +end; true Ban.find_each do |ban| puts "updating ban for user #{ban.user.id}" ban.user.update_attribute(:is_banned, true) -end ; true +end; true ArtistVersion.update_all "is_banned = false" Artist.where("is_banned = true").find_each do |artist| puts "updating artist #{artist.id}" artist.versions.last.update_column(:is_banned, true) -end ; true +end; true danbooru_conn = PGconn.connect(dbname: 'danbooru') danbooru2_conn = PGconn.connect(dbname: "danbooru2") danbooru_conn.exec("set statement_timeout = 0") -danbooru_conn.exec( "SELECT * FROM comments WHERE id < 29130" ) do |result| +danbooru_conn.exec("SELECT * FROM comments WHERE id < 29130") do |result| result.each do |row| # puts row["id"], row["created_at"], row["post_id"], row["user_id"], row["body"], row["ip_addr"], row["score"] - danbooru2_conn.exec "insert into comments (id, created_at, updated_at, post_id, creator_id, body, ip_addr, score, updater_id, updater_ip_addr) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", [row["id"], row["created_at"], row["created_at"], row["post_id"], row["user_id"], row["body"], row["ip_addr"], row["score"], row["user_id"], row["ip_addr"]] + danbooru2_conn.exec "insert into comments (id, created_at, updated_at, post_id, creator_id, body, ip_addr, score, updater_id, updater_ip_addr) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", [row["id"], row["created_at"], row["created_at"], row["post_id"], row["user_id"], row["body"], row["ip_addr"], row["score"], row["user_id"], row["ip_addr"]] end end diff --git a/script/fixes/014_note_ranges.rb b/script/fixes/014_note_ranges.rb old mode 100644 new mode 100755 index dc8899712..cecfc8ff5 --- a/script/fixes/014_note_ranges.rb +++ b/script/fixes/014_note_ranges.rb @@ -22,7 +22,7 @@ Post.where("created_at >= '2013-02-01'").select("id, score, up_score, down_score revised_score = post.up_score + post.down_score + fav_count puts "#{post.id}: #{post.score} -> #{revised_score}" if post.score != revised_score post.update_column(:score, revised_score) -end ; true +end; true Post.where("is_deleted = true and created_at >= '2013-02-01'").find_each do |post| if post.flags.empty? diff --git a/script/fixes/015.rb b/script/fixes/015.rb old mode 100644 new mode 100755 diff --git a/script/fixes/016_fix_swf_dimensions.rb b/script/fixes/016_fix_swf_dimensions.rb old mode 100644 new mode 100755 diff --git a/script/fixes/017_fix_md5.rb b/script/fixes/017_fix_md5.rb old mode 100644 new mode 100755 index afb861cc7..5379bdac8 --- a/script/fixes/017_fix_md5.rb +++ b/script/fixes/017_fix_md5.rb @@ -16,6 +16,6 @@ Post.where("id in (?)", Pool.find(203).post_id_array).find_each do |post| FileUtils.mv(post.real_preview_file_path, post.real_preview_file_path.sub(post.md5, correct_md5)) FileUtils.mv(post.ssd_preview_file_path, post.ssd_preview_file_path.sub(post.md5, correct_md5)) end - + FileUtils.mv(post.file_path, post.file_path.sub(post.md5, correct_md5)) end diff --git a/script/fixes/018_fix_md5.rb b/script/fixes/018_fix_md5.rb old mode 100644 new mode 100755 diff --git a/script/fixes/019_fix_pool_names.rb b/script/fixes/019_fix_pool_names.rb old mode 100644 new mode 100755 diff --git a/script/fixes/020_retrieve_bad_md5_posts.rb b/script/fixes/020_retrieve_bad_md5_posts.rb old mode 100644 new mode 100755 diff --git a/script/fixes/021_fix_deleted_pool_strings.rb b/script/fixes/021_fix_deleted_pool_strings.rb old mode 100644 new mode 100755 diff --git a/script/fixes/022_expunge_missing_images.rb b/script/fixes/022_expunge_missing_images.rb old mode 100644 new mode 100755 diff --git a/script/fixes/023_remove_expunged_posts_from_pools.rb b/script/fixes/023_remove_expunged_posts_from_pools.rb old mode 100644 new mode 100755 diff --git a/script/fixes/024_move_favorites_to_parent.rb b/script/fixes/024_move_favorites_to_parent.rb old mode 100644 new mode 100755 index 684909ce6..d8b8bfde0 --- a/script/fixes/024_move_favorites_to_parent.rb +++ b/script/fixes/024_move_favorites_to_parent.rb @@ -9,7 +9,7 @@ CurrentUser.ip_addr = "127.0.0.1" CurrentUser.without_safe_mode do sample_tags = %w(pixiv_manga_sample pixiv_thumbnail deviantart_thumbnail thumbnail nico_nico_thumbnail twitpic_thumbnail tumblr_sample imageboard_sample nijie_sample) - Post.tag_match(sample_tags.map{|tag| "~" + tag}.join(" ")).where("is_deleted = true and parent_id is not null and fav_count > 0").find_each do |post| + Post.tag_match(sample_tags.map {|tag| "~" + tag}.join(" ")).where("is_deleted = true and parent_id is not null and fav_count > 0").find_each do |post| if (post.parent.tag_array & sample_tags).any? next else diff --git a/script/fixes/025_last_commented_at.rb b/script/fixes/025_last_commented_at.rb old mode 100644 new mode 100755 index f73b36c6b..882920958 --- a/script/fixes/025_last_commented_at.rb +++ b/script/fixes/025_last_commented_at.rb @@ -4,8 +4,8 @@ require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'config', ActiveRecord::Base.connection.execute("set statement_timeout = 0") 0.upto(1585206 / 1000) do |i| - puts "updating posts #{i * 1000} to #{(i+1) * 1000}" - ActiveRecord::Base.connection.execute("update posts set last_commented_at = (select c.created_at from comments c where c.post_id = posts.id order by c.id desc limit 1) where posts.id between #{i * 1000} and #{(i+1) * 1000}") + puts "updating posts #{i * 1000} to #{(i + 1) * 1000}" + ActiveRecord::Base.connection.execute("update posts set last_commented_at = (select c.created_at from comments c where c.post_id = posts.id order by c.id desc limit 1) where posts.id between #{i * 1000} and #{(i + 1) * 1000}") end TagImplication.find_each do |ti| @@ -13,7 +13,7 @@ TagImplication.find_each do |ti| if ta puts "testing alias #{ta.antecedent_name} -> #{ta.consequent_name}" existing_ti = TagImplication.where("antecedent_name = ? AND consequent_name = ?", ta.consequent_name, ti.consequent_name).first - existing_ti.destroy if existing_ti + existing_ti&.destroy if ta.consequent_name == ti.consequent_name puts " deleting implication #{ti.antecedent_name} -> #{ti.consequent_name}" diff --git a/script/fixes/026_fix_unicode_capitals.rb b/script/fixes/026_fix_unicode_capitals.rb old mode 100644 new mode 100755 diff --git a/script/fixes/027_fix_banned_artists.rb b/script/fixes/027_fix_banned_artists.rb old mode 100644 new mode 100755 diff --git a/script/fixes/028_fix_has_children.rb b/script/fixes/028_fix_has_children.rb old mode 100644 new mode 100755 diff --git a/script/fixes/029_iqdb_import.rb b/script/fixes/029_iqdb_import.rb old mode 100644 new mode 100755 diff --git a/script/fixes/030_calculate_has_active_children.rb b/script/fixes/030_calculate_has_active_children.rb old mode 100644 new mode 100755 diff --git a/script/fixes/031_fix_ugoira_dimensions.rb b/script/fixes/031_fix_ugoira_dimensions.rb old mode 100644 new mode 100755 diff --git a/script/fixes/032_add_pool_category_pseudo_tags.rb b/script/fixes/032_add_pool_category_pseudo_tags.rb old mode 100644 new mode 100755 diff --git a/script/fixes/033_enable_can_approve_posts_flag.rb b/script/fixes/033_enable_can_approve_posts_flag.rb old mode 100644 new mode 100755 diff --git a/script/fixes/034_fix_dmail_filters.rb b/script/fixes/034_fix_dmail_filters.rb old mode 100644 new mode 100755 diff --git a/script/fixes/035_fix_nico_seiga_artist_urls.rb b/script/fixes/035_fix_nico_seiga_artist_urls.rb old mode 100644 new mode 100755 diff --git a/script/fixes/036_fix_hentai_foundry_artist_urls.rb b/script/fixes/036_fix_hentai_foundry_artist_urls.rb old mode 100644 new mode 100755 diff --git a/script/fixes/037_enable_can_upload_free.rb b/script/fixes/037_enable_can_upload_free.rb old mode 100644 new mode 100755 diff --git a/script/fixes/038_reset_categorized_saved_search_setting.rb b/script/fixes/038_reset_categorized_saved_search_setting.rb old mode 100644 new mode 100755 diff --git a/script/fixes/039_fix_saved_search_categories.rb b/script/fixes/039_fix_saved_search_categories.rb old mode 100644 new mode 100755 diff --git a/script/fixes/040_fix_post_scores.rb b/script/fixes/040_fix_post_scores.rb old mode 100644 new mode 100755 diff --git a/script/fixes/041_remove_expunged_posts_from_iqdb.rb b/script/fixes/041_remove_expunged_posts_from_iqdb.rb old mode 100644 new mode 100755 diff --git a/script/fixes/042_fix_user_cache_counters.rb b/script/fixes/042_fix_user_cache_counters.rb old mode 100644 new mode 100755 diff --git a/script/fixes/043_fix_whitespace_usernames.rb b/script/fixes/043_fix_whitespace_usernames.rb old mode 100644 new mode 100755 diff --git a/script/fixes/044_initialized_saved_search_tags.rb b/script/fixes/044_initialized_saved_search_tags.rb old mode 100644 new mode 100755 diff --git a/script/fixes/045_dedup_users.rb b/script/fixes/045_dedup_users.rb old mode 100644 new mode 100755 diff --git a/script/fixes/046_fix_nicovideo_artist_urls.rb b/script/fixes/046_fix_nicovideo_artist_urls.rb old mode 100644 new mode 100755 index b2830d5b1..40accd3f2 --- a/script/fixes/046_fix_nicovideo_artist_urls.rb +++ b/script/fixes/046_fix_nicovideo_artist_urls.rb @@ -6,6 +6,6 @@ ArtistUrl.without_timeout do ArtistUrl.where("normalized_url like ?", "\%nicovideo\%").find_each do |url| before = url.normalized_url url.normalize - puts "#{before} -> #{url.normalized_url}" if before != url.normalized_url unless ArtistUrl.where(normalized_url: url.normalized_url).exists? + puts "#{before} -> #{url.normalized_url}" unless ArtistUrl.where(normalized_url: url.normalized_url).exists? || before == url.normalized_url end end diff --git a/script/fixes/048_remove_expunged_favorites.rb b/script/fixes/048_remove_expunged_favorites.rb old mode 100644 new mode 100755 index 79bee23ed..a84fc5d2e --- a/script/fixes/048_remove_expunged_favorites.rb +++ b/script/fixes/048_remove_expunged_favorites.rb @@ -5,7 +5,7 @@ require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'config', CurrentUser.user = User.system CurrentUser.ip_addr = "127.0.0.1" -ModAction.without_timeout do +ModAction.without_timeout do ModAction.where(creator_id: 1).where("created_at > ? and description like ?", "2017-07-18", "permanently deleted post%").find_each do |ma| post_id = ma.description.scan(/\d+/).first puts "deleting favorites for #{post_id}" diff --git a/script/fixes/049_spam_1.rb b/script/fixes/049_spam_1.rb old mode 100644 new mode 100755 index 902e0b381..3fff14329 --- a/script/fixes/049_spam_1.rb +++ b/script/fixes/049_spam_1.rb @@ -13,7 +13,7 @@ BAD_TITLES = ["My collection", "hi", "My private videos", "My video", "hey", "My spammers = Set.new(Dmail.where("dmails.from_id >= ? and dmails.created_at >= ? and is_spam = ?", MIN_USER_ID, MIN_DATE, true).joins("join users on users.id = dmails.from_id").where("users.name ~ '^[a-z0-9]+[0-9]{3,}$'").pluck("users.id").map(&:to_i).uniq) new_spammers = Set.new -User.without_timeout do +User.without_timeout do Dmail.where("created_at >= ? and is_spam = ?", MIN_DATE, false).find_each do |dmail| from_name = dmail.from_name if dmail.from_id >= MIN_USER_ID && from_name =~ NAME_REGEXP diff --git a/script/fixes/050_fix_post_tagcount.rb b/script/fixes/050_fix_post_tagcount.rb old mode 100644 new mode 100755 diff --git a/script/fixes/051_purge_invalid_tags.rb b/script/fixes/051_purge_invalid_tags.rb index 1c168ab7f..850f1f67b 100755 --- a/script/fixes/051_purge_invalid_tags.rb +++ b/script/fixes/051_purge_invalid_tags.rb @@ -10,7 +10,7 @@ Tag.transaction do total = empty_gentags.count empty_gentags.find_each.with_index do |tag, i| - STDERR.puts %{validating "#{tag.name}" (#{i}/#{total})} if i % 1000 == 0 + warn %{validating "#{tag.name}" (#{i}/#{total})} if i % 1000 == 0 if tag.invalid?(:create) # puts ({ name: tag.name, id: tag.id }).to_json diff --git a/script/fixes/053_normalize_ugoira_data.rb b/script/fixes/053_normalize_ugoira_data.rb old mode 100644 new mode 100755 diff --git a/script/fixes/055_reindex_replacements_in_iqdb.rb b/script/fixes/055_reindex_replacements_in_iqdb.rb old mode 100644 new mode 100755 diff --git a/script/fixes/056_message_nonascii_usernames.rb b/script/fixes/056_message_nonascii_usernames.rb old mode 100644 new mode 100755 diff --git a/script/fixes/059_fix_favorites.rb b/script/fixes/059_fix_favorites.rb new file mode 100755 index 000000000..3ffc3c27e --- /dev/null +++ b/script/fixes/059_fix_favorites.rb @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby + +require_relative "../../config/environment" + +def fix_favorites + Favorite.without_timeout do + # delete favorites with a nonexistent post_id + Favorite.where("NOT EXISTS (SELECT 1 FROM posts WHERE posts.id = favorites.post_id)").delete_all + end +end + +def fix_migrations + ApplicationRecord.connection.execute("DELETE FROM scheme_migrations WHERE version = '201704142336170'") +end diff --git a/script/mock_services/iqdbs.rb b/script/mock_services/iqdbs.rb index 03e8ea3f6..a3cca08c3 100644 --- a/script/mock_services/iqdbs.rb +++ b/script/mock_services/iqdbs.rb @@ -5,7 +5,7 @@ require_relative './mock_service_helper' set :port, 3002 configure do - POST_IDS = MockServiceHelper.fetch_post_ids() + POST_IDS = MockServiceHelper.fetch_post_ids end get '/similar' do diff --git a/script/mock_services/mock_service_helper.rb b/script/mock_services/mock_service_helper.rb index 40b04da22..2b259bc4c 100644 --- a/script/mock_services/mock_service_helper.rb +++ b/script/mock_services/mock_service_helper.rb @@ -3,11 +3,11 @@ require 'timeout' require 'httparty' module MockServiceHelper - extend self + module_function DANBOORU_PORT = 3000 - def fetch_post_ids() + def fetch_post_ids begin s = TCPSocket.new("localhost", DANBOORU_PORT) s.close diff --git a/script/mock_services/recommender.rb b/script/mock_services/recommender.rb index 77b30ed9d..cb5f2b317 100644 --- a/script/mock_services/recommender.rb +++ b/script/mock_services/recommender.rb @@ -5,7 +5,7 @@ require_relative './mock_service_helper' set :port, 3001 configure do - POST_IDS = MockServiceHelper.fetch_post_ids() + POST_IDS = MockServiceHelper.fetch_post_ids end get '/recommend/:user_id' do @@ -15,5 +15,5 @@ end get '/similar/:post_id' do content_type :json - POST_IDS[0..6].map {|x| [x, "1.000"]}.to_json + POST_IDS[0..6].map {|x| [x, "1.000"]}.to_json end diff --git a/test/factories/artist.rb b/test/factories/artist.rb index 3761bd554..7137e3845 100644 --- a/test/factories/artist.rb +++ b/test/factories/artist.rb @@ -5,4 +5,3 @@ FactoryBot.define do association :creator, factory: :user end end - diff --git a/test/factories/pool.rb b/test/factories/pool.rb index e2c68bf03..cff7ea112 100644 --- a/test/factories/pool.rb +++ b/test/factories/pool.rb @@ -1,6 +1,6 @@ FactoryBot.define do factory(:pool) do - name {"pool_" + (rand(1_000_000) + 100).to_s} + name {"pool_" + rand(100..1000099).to_s} association :creator, :factory => :user description {FFaker::Lorem.sentences.join(" ")} end diff --git a/test/factories/upload.rb b/test/factories/upload.rb index 69da6490f..1468c17b6 100644 --- a/test/factories/upload.rb +++ b/test/factories/upload.rb @@ -39,4 +39,3 @@ FactoryBot.define do end end end - diff --git a/test/factories/user.rb b/test/factories/user.rb index efce25266..3d6741c43 100644 --- a/test/factories/user.rb +++ b/test/factories/user.rb @@ -59,4 +59,3 @@ FactoryBot.define do end end end - diff --git a/test/functional/admin/dashboards_controller_test.rb b/test/functional/admin/dashboards_controller_test.rb index dae369dff..853081138 100644 --- a/test/functional/admin/dashboards_controller_test.rb +++ b/test/functional/admin/dashboards_controller_test.rb @@ -5,7 +5,7 @@ class Admin::DashboardsControllerTest < ActionDispatch::IntegrationTest setup do @admin = create(:admin_user) end - + context "show action" do should "render" do get_auth admin_dashboard_path, @admin diff --git a/test/functional/artist_commentaries_controller_test.rb b/test/functional/artist_commentaries_controller_test.rb index 1e2f50713..27e7c3dca 100644 --- a/test/functional/artist_commentaries_controller_test.rb +++ b/test/functional/artist_commentaries_controller_test.rb @@ -21,10 +21,10 @@ class ArtistCommentariesControllerTest < ActionDispatch::IntegrationTest params = { search: { text_matches: @commentary1.original_title, - post_id: @commentary1.post_id, + post_id: @commentary1.post_id, original_present: "yes", translated_present: "yes", - post_tags_match: @commentary1.post.tag_array.first, + post_tags_match: @commentary1.post.tag_array.first } } @@ -48,7 +48,7 @@ class ArtistCommentariesControllerTest < ActionDispatch::IntegrationTest params = { artist_commentary: { original_title: "foo", - post_id: FactoryBot.create(:post).id, + post_id: FactoryBot.create(:post).id }, format: "js" } @@ -63,7 +63,7 @@ class ArtistCommentariesControllerTest < ActionDispatch::IntegrationTest params = { artist_commentary: { post_id: @commentary1.post_id, - original_title: "foo", + original_title: "foo" }, format: "js" } diff --git a/test/functional/artist_urls_controller_test.rb b/test/functional/artist_urls_controller_test.rb index 124f13a73..dc009fb79 100644 --- a/test/functional/artist_urls_controller_test.rb +++ b/test/functional/artist_urls_controller_test.rb @@ -12,7 +12,7 @@ class ArtistUrlsControllerTest < ActionDispatch::IntegrationTest @artist = FactoryBot.create(:artist, name: "bkub", url_string: "-http://bkub.com") get artist_urls_path(search: { - artist: { name: "bkub", }, + artist: { name: "bkub" }, url_matches: "*bkub*", is_active: "false", order: "created_at" diff --git a/test/functional/comments_controller_test.rb b/test/functional/comments_controller_test.rb index ea2a197fe..c69c40d0a 100644 --- a/test/functional/comments_controller_test.rb +++ b/test/functional/comments_controller_test.rb @@ -185,7 +185,7 @@ class CommentsControllerTest < ActionDispatch::IntegrationTest end end - context "create action"do + context "create action" do should "create a comment" do assert_difference("Comment.count", 1) do post_auth comments_path, @user, params: {comment: FactoryBot.attributes_for(:comment, post_id: @post.id)} diff --git a/test/functional/forum_topics_controller_test.rb b/test/functional/forum_topics_controller_test.rb index c6e33cfec..a8b35b79d 100644 --- a/test/functional/forum_topics_controller_test.rb +++ b/test/functional/forum_topics_controller_test.rb @@ -117,16 +117,16 @@ class ForumTopicsControllerTest < ActionDispatch::IntegrationTest get forum_topics_path, params: {:search => {:title_matches => "forum"}} assert_response :success assert_select "a.forum-post-link", @forum_topic.title - assert_select "a.forum-post-link", {count: 0, text: @topic1.title} - assert_select "a.forum-post-link", {count: 0, text: @topic2.title} + assert_select "a.forum-post-link", count: 0, text: @topic1.title + assert_select "a.forum-post-link", count: 0, text: @topic2.title end should "list nothing for when the search matches nothing" do get forum_topics_path, params: {:search => {:title_matches => "bababa"}} assert_response :success - assert_select "a.forum-post-link", {count: 0, text: @forum_topic.title} - assert_select "a.forum-post-link", {count: 0, text: @topic1.title} - assert_select "a.forum-post-link", {count: 0, text: @topic2.title} + assert_select "a.forum-post-link", count: 0, text: @forum_topic.title + assert_select "a.forum-post-link", count: 0, text: @topic1.title + assert_select "a.forum-post-link", count: 0, text: @topic2.title end end end diff --git a/test/functional/maintenance/user/deletions_controller_test.rb b/test/functional/maintenance/user/deletions_controller_test.rb index a303343e9..6f2adbbf1 100644 --- a/test/functional/maintenance/user/deletions_controller_test.rb +++ b/test/functional/maintenance/user/deletions_controller_test.rb @@ -24,4 +24,4 @@ module Maintenance end end end -end \ No newline at end of file +end diff --git a/test/functional/maintenance/user/email_changes_controller_test.rb b/test/functional/maintenance/user/email_changes_controller_test.rb index 0b4c51b3b..d26807ae7 100644 --- a/test/functional/maintenance/user/email_changes_controller_test.rb +++ b/test/functional/maintenance/user/email_changes_controller_test.rb @@ -36,4 +36,4 @@ module Maintenance end end end -end \ No newline at end of file +end diff --git a/test/functional/moderator/dashboards_controller_test.rb b/test/functional/moderator/dashboards_controller_test.rb index c6a62da10..9475e8ad4 100644 --- a/test/functional/moderator/dashboards_controller_test.rb +++ b/test/functional/moderator/dashboards_controller_test.rb @@ -64,7 +64,7 @@ module Moderator end end - context "for notes"do + context "for notes" do setup do as(@user) do @post = create(:post) diff --git a/test/functional/moderator/ip_addrs_controller_test.rb b/test/functional/moderator/ip_addrs_controller_test.rb index 2a36592e7..76d62d284 100644 --- a/test/functional/moderator/ip_addrs_controller_test.rb +++ b/test/functional/moderator/ip_addrs_controller_test.rb @@ -6,7 +6,7 @@ module Moderator setup do PoolArchive.delete_all PostArchive.delete_all - + travel_to(1.month.ago) do @user = create(:moderator_user) end diff --git a/test/functional/moderator/post/disapprovals_controller_test.rb b/test/functional/moderator/post/disapprovals_controller_test.rb index 6c8c0c718..a3395f5f3 100644 --- a/test/functional/moderator/post/disapprovals_controller_test.rb +++ b/test/functional/moderator/post/disapprovals_controller_test.rb @@ -26,7 +26,7 @@ module Moderator assert_difference("PostDisapproval.count", 1) do post_auth moderator_post_disapprovals_path, @admin, params: { post_disapproval: { post_id: @post.id, reason: "breaks_rules" }, format: "json" } end - assert_response :success + assert_response :success end end end diff --git a/test/functional/moderator/post/posts_controller_test.rb b/test/functional/moderator/post/posts_controller_test.rb index 5873e7b41..165ec3146 100644 --- a/test/functional/moderator/post/posts_controller_test.rb +++ b/test/functional/moderator/post/posts_controller_test.rb @@ -9,7 +9,7 @@ module Moderator travel_to(1.month.ago) do @user = create(:gold_user) end - + as_user do @post = create(:post) end @@ -69,7 +69,7 @@ module Moderator @child = create(:post, parent: @parent) end users = FactoryBot.create_list(:user, 2) - users.each do |u| + users.each do |u| @child.add_favorite!(u) @child.reload end diff --git a/test/functional/notes_controller_test.rb b/test/functional/notes_controller_test.rb index 5ef42e452..b65bf812e 100644 --- a/test/functional/notes_controller_test.rb +++ b/test/functional/notes_controller_test.rb @@ -24,7 +24,7 @@ class NotesControllerTest < ActionDispatch::IntegrationTest post_id: @note.post_id, post_tags_match: @note.post.tag_array.first, creator_name: @note.creator.name, - creator_id: @note.creator_id, + creator_id: @note.creator_id } } diff --git a/test/functional/post_replacements_controller_test.rb b/test/functional/post_replacements_controller_test.rb index 865e5e7f8..f940090e4 100644 --- a/test/functional/post_replacements_controller_test.rb +++ b/test/functional/post_replacements_controller_test.rb @@ -16,7 +16,7 @@ class PostReplacementsControllerTest < ActionDispatch::IntegrationTest format: :json, post_id: @post.id, post_replacement: { - replacement_url: "https://raikou1.donmai.us/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg", + replacement_url: "https://raikou1.donmai.us/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg" } } @@ -42,7 +42,7 @@ class PostReplacementsControllerTest < ActionDispatch::IntegrationTest id: @post_replacement.id, post_replacement: { file_size_was: 23, - file_size: 42, + file_size: 42 } } diff --git a/test/functional/uploads_controller_test.rb b/test/functional/uploads_controller_test.rb index 8658257ea..97e1b8c21 100644 --- a/test/functional/uploads_controller_test.rb +++ b/test/functional/uploads_controller_test.rb @@ -32,7 +32,7 @@ class UploadsControllerTest < ActionDispatch::IntegrationTest end end - context "preprocess action" do + context "preprocess action" do should "prefer the file over the source when preprocessing" do file = Rack::Test::UploadedFile.new("#{Rails.root}/test/files/test.jpg", "image/jpeg") post_auth preprocess_uploads_path, @user, params: {:upload => {:source => "https://raikou1.donmai.us/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg", :file => file}} @@ -154,7 +154,7 @@ class UploadsControllerTest < ActionDispatch::IntegrationTest source_matches: @upload.source, rating: @upload.rating, status: @upload.status, - server: @upload.server, + server: @upload.server } get uploads_path, params: { search: search_params } @@ -192,13 +192,13 @@ class UploadsControllerTest < ActionDispatch::IntegrationTest end should "update the predecessor" do - assert_difference(->{ Post.count }, 1) do - assert_difference(->{ Upload.count }, 0) do + assert_difference(-> { Post.count }, 1) do + assert_difference(-> { Upload.count }, 0) do post_auth uploads_path, @user, params: {:upload => {:tag_string => "aaa", :rating => "q", :source => @source, :referer_url => @ref}} end end post = Post.last - assert_match(/aaa/, post.tag_string) + assert_match(/aaa/, post.tag_string) end end @@ -212,13 +212,13 @@ class UploadsControllerTest < ActionDispatch::IntegrationTest end should "update the predecessor" do - assert_difference(->{ Post.count }, 1) do - assert_difference(->{ Upload.count }, 0) do + assert_difference(-> { Post.count }, 1) do + assert_difference(-> { Upload.count }, 0) do post_auth uploads_path, @user, params: {:upload => {:tag_string => "aaa", :rating => "q", :source => @source, :referer_url => @ref}} end end post = Post.last - assert_match(/aaa/, post.tag_string) + assert_match(/aaa/, post.tag_string) end end end diff --git a/test/functional/users_controller_test.rb b/test/functional/users_controller_test.rb index 92f081f66..ac7acab25 100644 --- a/test/functional/users_controller_test.rb +++ b/test/functional/users_controller_test.rb @@ -105,7 +105,7 @@ class UsersControllerTest < ActionDispatch::IntegrationTest setup do Danbooru.config.stubs(:enable_recaptcha?).returns(false) end - + should "render" do get new_user_path assert_response :success @@ -121,7 +121,7 @@ class UsersControllerTest < ActionDispatch::IntegrationTest context "with sockpuppet validation enabled" do setup do - Danbooru.config.unstub(:enable_sock_puppet_validation?) + Danbooru.config.unstub(:enable_sock_puppet_validation?) @user.update(last_ip_addr: "127.0.0.1") end diff --git a/test/jobs/application_job_test.rb b/test/jobs/application_job_test.rb index a40a77324..6779abdaa 100644 --- a/test/jobs/application_job_test.rb +++ b/test/jobs/application_job_test.rb @@ -1,7 +1,8 @@ require 'test_helper' class TestJob < ApplicationJob - def perform(record); end + def perform(record) + end end class ApplicationJobTest < ActiveJob::TestCase diff --git a/test/models/tag_autocomplete_test.rb b/test/models/tag_autocomplete_test.rb index 71663570a..337a147d8 100644 --- a/test/models/tag_autocomplete_test.rb +++ b/test/models/tag_autocomplete_test.rb @@ -96,7 +96,7 @@ class TagAutocompleteTest < ActiveSupport::TestCase @tags = [ create(:tag, name: "/abc", post_count: 0), create(:tag, name: "abcdef", post_count: 1), - create(:tag, name: "zzzzzz", post_count: 1), + create(:tag, name: "zzzzzz", post_count: 1) ] as_user do @aliases = [ diff --git a/test/models/tag_relationship_retirement_service_test.rb b/test/models/tag_relationship_retirement_service_test.rb index cdede5c66..13d34d4bb 100644 --- a/test/models/tag_relationship_retirement_service_test.rb +++ b/test/models/tag_relationship_retirement_service_test.rb @@ -68,8 +68,7 @@ class TagRelationshipRetirementServiceTest < ActiveSupport::TestCase end should "return false if a recent post exists" do - refute(subject.is_unused?("bbb")) + refute(subject.is_unused?("bbb")) end end end - diff --git a/test/models/upload_service_test.rb b/test/models/upload_service_test.rb index 9d5c28a9b..a3fd4d00c 100644 --- a/test/models/upload_service_test.rb +++ b/test/models/upload_service_test.rb @@ -20,7 +20,7 @@ class UploadServiceTest < ActiveSupport::TestCase context "#get_file_for_upload" do context "for a non-source site" do setup do - @source = "https://upload.wikimedia.org/wikipedia/commons/c/c5/Moraine_Lake_17092005.jpg" + @source = "https://upload.wikimedia.org/wikipedia/commons/c/c5/Moraine_Lake_17092005.jpg" @upload = Upload.new @upload.source = @source end @@ -163,7 +163,7 @@ class UploadServiceTest < ActiveSupport::TestCase end end - context "for an image" do + context "for an image" do setup do @file = File.open("test/files/test.jpg", "rb") @upload = Upload.new(file_ext: "jpg") @@ -211,7 +211,7 @@ class UploadServiceTest < ActiveSupport::TestCase setup do context = UGOIRA_CONTEXT @file = File.open("test/fixtures/ugoira.zip", "rb") - @upload = mock() + @upload = mock @upload.stubs(:is_video?).returns(false) @upload.stubs(:is_ugoira?).returns(true) @upload.stubs(:context).returns(context) @@ -243,7 +243,7 @@ class UploadServiceTest < ActiveSupport::TestCase context "for an mp4" do setup do @file = File.open("test/files/test-300x300.mp4", "rb") - @upload = mock() + @upload = mock @upload.stubs(:is_video?).returns(true) @upload.stubs(:is_ugoira?).returns(false) end @@ -266,7 +266,7 @@ class UploadServiceTest < ActiveSupport::TestCase context "for a webm" do setup do @file = File.open("test/files/test-512x512.webm", "rb") - @upload = mock() + @upload = mock @upload.stubs(:is_video?).returns(true) @upload.stubs(:is_ugoira?).returns(false) end @@ -293,7 +293,7 @@ class UploadServiceTest < ActiveSupport::TestCase end setup do - @upload = mock() + @upload = mock @upload.stubs(:is_video?).returns(false) @upload.stubs(:is_ugoira?).returns(false) @upload.stubs(:is_image?).returns(true) @@ -414,8 +414,8 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal(9800, @upload.file_size) assert_equal("png", @upload.file_ext) assert_equal("f5fe24f3a3a13885285f6627e04feec9", @upload.md5) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "png", :original))) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "png", :preview))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "png", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "png", :preview))) end end @@ -436,8 +436,8 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal(294591, @upload.file_size) assert_equal("jpg", @upload.file_ext) assert_equal("3cb1ef624714c15dbb2d6e7b1d57faef", @upload.md5) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :preview))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :preview))) end end @@ -459,8 +459,8 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal(2804, @upload.file_size) assert_equal("zip", @upload.file_ext) assert_equal("cad1da177ef309bf40a117c17b8eecf5", @upload.md5) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "zip", :original))) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "zip", :large))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "zip", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "zip", :large))) end end @@ -480,9 +480,9 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal(181309, @upload.file_size) assert_equal("jpg", @upload.file_ext) assert_equal("93f4dd66ef1eb11a89e56d31f9adc8d0", @upload.md5) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :large))) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :preview))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :large))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :preview))) end end @@ -499,8 +499,8 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal("mp4", @upload.file_ext) assert_operator(@upload.file_size, :>, 0) assert_not_nil(@upload.source) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "mp4", :original))) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "mp4", :preview))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "mp4", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "mp4", :preview))) end end @@ -509,7 +509,7 @@ class UploadServiceTest < ActiveSupport::TestCase @source = "https://raikou1.donmai.us/93/f4/93f4dd66ef1eb11a89e56d31f9adc8d0.jpg" HTTParty.stubs(:get).raises(Net::ReadTimeout) end - + should "leave the upload in an error state" do @service = subject.new(source: @source) @upload = @service.start! @@ -536,7 +536,7 @@ class UploadServiceTest < ActiveSupport::TestCase should "overwrite the attributes" do @service = subject.new(source: @source, rating: 'e') - @upload = @service.start! + @upload = @service.start! @service.finish! @upload.reload assert_equal('e', @upload.rating) @@ -558,7 +558,7 @@ class UploadServiceTest < ActiveSupport::TestCase @post.stubs(:queue_delete_files) @replacement = FactoryBot.create(:post_replacement, post: @post, replacement_url: "", replacement_file: @new_file) end - end + end subject { UploadService::Replacer.new(post: @post, replacement: @replacement) } @@ -614,7 +614,7 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal(28086, @post.file_size) assert_equal("jpg", @post.file_ext) assert_equal("ecef68c44edb8a0d6a3070b5f8e8ee76", @post.md5) - assert(File.exists?(@post.file.path)) + assert(File.exist?(@post.file.path)) end end @@ -856,7 +856,7 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal("cad1da177ef309bf40a117c17b8eecf5", Digest::MD5.file(@post.file).hexdigest) assert_equal("https://i.pximg.net/img-zip-ugoira/img/2017/04/04/08/57/38/62247364_ugoira1920x1080.zip", @post.source) - assert_equal([{"delay"=>125, "file"=>"000000.jpg"}, {"delay"=>125,"file"=>"000001.jpg"}], @post.pixiv_ugoira_frame_data.data) + assert_equal([{"delay" => 125, "file" => "000000.jpg"}, {"delay" => 125, "file" => "000001.jpg"}], @post.pixiv_ugoira_frame_data.data) rescue Net::OpenTimeout skip "Remote connection to Pixiv failed" end @@ -870,7 +870,7 @@ class UploadServiceTest < ActiveSupport::TestCase @post.unstub(:queue_delete_files) # this is called thrice to delete the file for 62247364 - FileUtils.expects(:rm_f).times(3) + FileUtils.expects(:rm_f).times(3) as_user do @post.replace!(replacement_url: "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=62247350") @@ -1018,7 +1018,7 @@ class UploadServiceTest < ActiveSupport::TestCase context "that is too large" do setup do - Danbooru.config.stubs(:max_image_resolution).returns(31*31) + Danbooru.config.stubs(:max_image_resolution).returns(31 * 31) end should "should fail validation" do @@ -1068,7 +1068,6 @@ class UploadServiceTest < ActiveSupport::TestCase assert_equal("error: ActiveRecord::RecordInvalid - Validation failed: Md5 duplicate: #{@post.id}", @predecessor.status) end end - end context "with no predecessor" do @@ -1178,7 +1177,7 @@ class UploadServiceTest < ActiveSupport::TestCase should "record the canonical source" do post = subject.new({}).create_post_from_upload(@upload) assert_equal(@ref, post.source) - end + end end context "for a pixiv ugoira" do @@ -1213,7 +1212,7 @@ class UploadServiceTest < ActiveSupport::TestCase should "create a commentary record" do assert_difference(-> { ArtistCommentary.count }) do - subject.new({include_artist_commentary: true, artist_commentary_title: "blah", artist_commentary_desc: "blah"}).create_post_from_upload(@upload) + subject.new(include_artist_commentary: true, artist_commentary_title: "blah", artist_commentary_desc: "blah").create_post_from_upload(@upload) end end @@ -1223,7 +1222,6 @@ class UploadServiceTest < ActiveSupport::TestCase assert_not_nil(post.id) end end - end context "Upload#prune!" do @@ -1239,31 +1237,31 @@ class UploadServiceTest < ActiveSupport::TestCase should "delete unused files after deleting the upload" do @upload = as(@user) { UploadService::Preprocessor.new(file: upload_file("test/files/test.jpg")).start! } - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) @upload.destroy! - refute(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + refute(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) end should "not delete files that are still in use by a post" do @upload = as(@user) { UploadService.new(file: upload_file("test/files/test.jpg")).start! } - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) @upload.destroy! - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) end should "not delete files if they're still in use by another upload" do @upload1 = as(@user) { UploadService::Preprocessor.new(file: upload_file("test/files/test.jpg")).start! } @upload2 = as(@user) { UploadService::Preprocessor.new(file: upload_file("test/files/test.jpg")).start! } assert_equal(@upload1.md5, @upload2.md5) - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload1.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload1.md5, "jpg", :original))) @upload1.destroy! - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload1.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload1.md5, "jpg", :original))) @upload2.destroy! - refute(File.exists?(Danbooru.config.storage_manager.file_path(@upload2.md5, "jpg", :original))) + refute(File.exist?(Danbooru.config.storage_manager.file_path(@upload2.md5, "jpg", :original))) end should "not delete files that were replaced after upload and are still pending deletion" do @@ -1276,11 +1274,11 @@ class UploadServiceTest < ActiveSupport::TestCase # after replacement the uploaded file is no longer in use, but it shouldn't be # deleted yet. it should only be deleted by the replacer after the grace period. @upload.destroy! - assert(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + assert(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) travel (PostReplacement::DELETION_GRACE_PERIOD + 1).days perform_enqueued_jobs - refute(File.exists?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) + refute(File.exist?(Danbooru.config.storage_manager.file_path(@upload.md5, "jpg", :original))) end should "work on uploads without a file" do diff --git a/test/test_helper.rb b/test/test_helper.rb index b327177e2..f4f6fe0d8 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -8,14 +8,14 @@ if ENV["SIMPLECOV"] end end -require File.expand_path('../../config/environment', __FILE__) +require File.expand_path('../config/environment', __dir__) require 'rails/test_help' require 'cache' require 'webmock/minitest' require 'mocha/minitest' -Dir[File.expand_path(File.dirname(__FILE__) + "/factories/*.rb")].each {|file| require file} -Dir[File.expand_path(File.dirname(__FILE__) + "/test_helpers/*.rb")].each {|file| require file} +Dir[File.expand_path(File.dirname(__FILE__) + "/factories/*.rb")].sort.each {|file| require file} +Dir[File.expand_path(File.dirname(__FILE__) + "/test_helpers/*.rb")].sort.each {|file| require file} Shoulda::Matchers.configure do |config| config.integrate do |with| diff --git a/test/test_helpers/download_test_helper.rb b/test/test_helpers/download_test_helper.rb index 30965a191..72805cf9b 100644 --- a/test/test_helpers/download_test_helper.rb +++ b/test/test_helpers/download_test_helper.rb @@ -1,5 +1,5 @@ module DownloadTestHelper - def assert_downloaded(expected_filesize, source, referer=nil) + def assert_downloaded(expected_filesize, source, referer = nil) download = Downloads::File.new(source, referer) tempfile, strategy = download.download! assert_equal(expected_filesize, tempfile.size, "Tested source URL: #{source}") @@ -7,13 +7,13 @@ module DownloadTestHelper skip "Remote connection to #{source} failed" end - def assert_rewritten(expected_source, test_source, test_referer=nil) + def assert_rewritten(expected_source, test_source, test_referer = nil) strategy = Sources::Strategies.find(test_source, test_referer) rewritten_source = strategy.image_url assert_match(expected_source, rewritten_source, "Tested source URL: #{test_source}") end - def assert_not_rewritten(source, referer=nil) + def assert_not_rewritten(source, referer = nil) assert_rewritten(source, source, referer) end diff --git a/test/unit/apng_inspector_test.rb b/test/unit/apng_inspector_test.rb index 6332d72bc..1f69a9d43 100644 --- a/test/unit/apng_inspector_test.rb +++ b/test/unit/apng_inspector_test.rb @@ -59,6 +59,5 @@ class APNGInspectorTest < ActiveSupport::TestCase assert_equal(false, apng.animated?) assert_equal(true, apng.corrupted?) end - end end diff --git a/test/unit/artist_commentary_test.rb b/test/unit/artist_commentary_test.rb index e41ee5be6..9d9e67cc3 100644 --- a/test/unit/artist_commentary_test.rb +++ b/test/unit/artist_commentary_test.rb @@ -93,7 +93,7 @@ class ArtistCommentaryTest < ActiveSupport::TestCase original_title: " foo\u00A0\t\n", original_description: " foo\u00A0\t\n", translated_title: " foo\u00A0\t\n", - translated_description: " foo\u00A0\n", + translated_description: " foo\u00A0\n" ) assert_equal("foo", @artcomm.original_title) diff --git a/test/unit/artist_test.rb b/test/unit/artist_test.rb index ffad76247..37d137b75 100644 --- a/test/unit/artist_test.rb +++ b/test/unit/artist_test.rb @@ -39,7 +39,7 @@ class ArtistTest < ActiveSupport::TestCase @artist = Artist.create(name: "blah", url_string: "-http://monet.com\nhttp://monet.com") assert_equal(1, @artist.urls.count) assert_equal(["-http://monet.com"], @artist.urls.map(&:to_s)) - refute(@artist.urls[0].is_active?) + refute(@artist.urls[0].is_active?) end should "allow deactivating a url" do @@ -237,7 +237,7 @@ class ArtistTest < ActiveSupport::TestCase context "when finding pixiv artists" do setup do - FactoryBot.create(:artist, :name => "masao",:url_string => "http://www.pixiv.net/member.php?id=32777") + FactoryBot.create(:artist, :name => "masao", :url_string => "http://www.pixiv.net/member.php?id=32777") FactoryBot.create(:artist, :name => "bkub", :url_string => "http://www.pixiv.net/member.php?id=9948") FactoryBot.create(:artist, :name => "ryuura", :url_string => "http://www.pixiv.net/member.php?id=8678371") end @@ -297,7 +297,7 @@ class ArtistTest < ActiveSupport::TestCase setup do skip "Twitter key is not set" unless Danbooru.config.twitter_api_key FactoryBot.create(:artist, :name => "hammer_(sunset_beach)", :url_string => "http://twitter.com/hamaororon") - FactoryBot.create(:artist, :name => "haruyama_kazunori", :url_string => "https://twitter.com/kazuharoom") + FactoryBot.create(:artist, :name => "haruyama_kazunori", :url_string => "https://twitter.com/kazuharoom") end should "find the correct artist for twitter.com sources" do diff --git a/test/unit/artist_url_test.rb b/test/unit/artist_url_test.rb index feb6b31f8..ad10a6741 100644 --- a/test/unit/artist_url_test.rb +++ b/test/unit/artist_url_test.rb @@ -121,7 +121,7 @@ class ArtistUrlTest < ActiveSupport::TestCase should "normalize deviant art artist urls" do url = FactoryBot.create(:artist_url, :url => "https://www.deviantart.com/aeror404/art/Holiday-Elincia-424551484") - assert_equal("http://www.deviantart.com/aeror404/", url.normalized_url) + assert_equal("http://www.deviantart.com/aeror404/", url.normalized_url) end should "normalize nico seiga artist urls" do diff --git a/test/unit/bulk_update_request_test.rb b/test/unit/bulk_update_request_test.rb index 30ecf6752..668dc5df9 100644 --- a/test/unit/bulk_update_request_test.rb +++ b/test/unit/bulk_update_request_test.rb @@ -64,11 +64,11 @@ class BulkUpdateRequestTest < ActiveSupport::TestCase context "on approval" do setup do @post = create(:post, tag_string: "foo aaa") - @script = %q( + @script = ' create alias foo -> bar create implication bar -> baz mass update aaa -> bbb - ) + ' @bur = FactoryBot.create(:bulk_update_request, :script => @script) @bur.approve!(@admin) diff --git a/test/unit/cloudflare_service_test.rb b/test/unit/cloudflare_service_test.rb index 4dd914eda..9b64435a7 100644 --- a/test/unit/cloudflare_service_test.rb +++ b/test/unit/cloudflare_service_test.rb @@ -19,7 +19,7 @@ class CloudflareServiceTest < ActiveSupport::TestCase should "make calls to cloudflare's api" do subject.delete("md5", "png") - assert_requested(:delete, "https://api.cloudflare.com/client/v4/zones/123/purge_cache", times: 1) do |req| + assert_requested(:delete, "https://api.cloudflare.com/client/v4/zones/123/purge_cache", times: 1) do |req| req.body =~ /danbooru\.donmai\.us/ && req.body =~ /safebooru\.donmai\.us/ && req.body =~ /sample/ && req.body =~ /preview/ end end diff --git a/test/unit/dmail_test.rb b/test/unit/dmail_test.rb index 7bffa9a23..98b4a5909 100644 --- a/test/unit/dmail_test.rb +++ b/test/unit/dmail_test.rb @@ -23,7 +23,7 @@ class DmailTest < ActiveSupport::TestCase end should "not validate" do - assert_difference("Dmail.count", 2)do + assert_difference("Dmail.count", 2) do Dmail.create_split(from: @spammer, to: @recipient, title: "spam", body: "wonderful spam") assert(@recipient.dmails.last.is_spam?) end @@ -70,7 +70,7 @@ class DmailTest < ActiveSupport::TestCase @dmail = FactoryBot.create(:dmail, :owner => @recipient, :body => "banned word here", :to => @recipient) end - assert_equal(false, !!@recipient.dmail_filter.filtered?(@dmail)) + assert_equal(false, @recipient.dmail_filter.filtered?(@dmail)) assert_equal(false, @dmail.is_read?) assert_equal(true, @recipient.has_mail?) end diff --git a/test/unit/downloads/file_test.rb b/test/unit/downloads/file_test.rb index 9c8db4d25..43b965f53 100644 --- a/test/unit/downloads/file_test.rb +++ b/test/unit/downloads/file_test.rb @@ -10,7 +10,7 @@ module Downloads end teardown do - ENV["SKIP_CLOUDFLARE_CHECK"] = nil + ENV["SKIP_CLOUDFLARE_CHECK"] = nil end context "for a banned IP" do @@ -59,7 +59,7 @@ module Downloads HTTParty.expects(:get).twice.multiple_yields(chunk, bomb).then.multiple_yields(chunk, chunk).returns(resp) @download.stubs(:is_cloudflare?).returns(false) - tempfile, _ = @download.download! + tempfile, _strategy = @download.download! assert_equal("aa", tempfile.read) end @@ -78,7 +78,7 @@ module Downloads should "correctly save the file when following 302 redirects" do download = Downloads::File.new("https://yande.re/post/show/578014") - file, strategy = download.download!(url: download.preview_url) + file, strategy = download.download!(url: download.preview_url) assert_equal(19134, file.size) end end diff --git a/test/unit/downloads/pixiv_test.rb b/test/unit/downloads/pixiv_test.rb index 25c4e2248..503617bf6 100644 --- a/test/unit/downloads/pixiv_test.rb +++ b/test/unit/downloads/pixiv_test.rb @@ -109,7 +109,6 @@ module Downloads assert_not_rewritten(@file_url) assert_downloaded(@file_size, @file_url) end - end context "downloading a background image" do @@ -157,9 +156,9 @@ module Downloads should "capture the data" do assert_equal(2, @download.data[:ugoira_frame_data].size) if @download.data[:ugoira_frame_data][0]["file"] - assert_equal([{"file"=>"000000.jpg", "delay"=>125}, {"file"=>"000001.jpg", "delay"=>125}], @download.data[:ugoira_frame_data]) + assert_equal([{"file" => "000000.jpg", "delay" => 125}, {"file" => "000001.jpg", "delay" => 125}], @download.data[:ugoira_frame_data]) else - assert_equal([{"delay_msec"=>125}, {"delay_msec"=>125}], @download.data[:ugoira_frame_data]) + assert_equal([{"delay_msec" => 125}, {"delay_msec" => 125}], @download.data[:ugoira_frame_data]) end end end diff --git a/test/unit/downloads/tumblr_test.rb b/test/unit/downloads/tumblr_test.rb index 8d2b27dda..35f6f23dd 100644 --- a/test/unit/downloads/tumblr_test.rb +++ b/test/unit/downloads/tumblr_test.rb @@ -4,7 +4,7 @@ module Downloads class TumblrTest < ActiveSupport::TestCase # Currently there's no way to obtain the raw version of these images, # so we have to change the tests to validate against the 1280 version - + context "a download for a tumblr 500 sample" do should "instead download the 1280 version" do skip "Tumblr keys are not set" unless Danbooru.config.tumblr_consumer_key diff --git a/test/unit/favorite_group_test.rb b/test/unit/favorite_group_test.rb index dae620b37..5f9e6dfd4 100644 --- a/test/unit/favorite_group_test.rb +++ b/test/unit/favorite_group_test.rb @@ -35,7 +35,7 @@ class FavoriteTest < ActiveSupport::TestCase should "return the fav group" do assert_equal(@fav_group.id, FavoriteGroup.for_post(1).first.try(:id)) - end + end end context "when the id is in the middle" do @@ -57,7 +57,7 @@ class FavoriteTest < ActiveSupport::TestCase should "return the fav group" do assert_equal(@fav_group.id, FavoriteGroup.for_post(1).first.try(:id)) - end + end end end @@ -68,7 +68,7 @@ class FavoriteTest < ActiveSupport::TestCase end should "remove it from all favorite groups" do - assert_equal("#{@post.id}", @fav_group.post_ids) + assert_equal(@post.id.to_s, @fav_group.post_ids) @post.expunge! @fav_group.reload assert_equal("", @fav_group.post_ids) diff --git a/test/unit/forum_post_test.rb b/test/unit/forum_post_test.rb index 296723068..6f21dbc3f 100644 --- a/test/unit/forum_post_test.rb +++ b/test/unit/forum_post_test.rb @@ -89,7 +89,7 @@ class ForumPostTest < ActiveSupport::TestCase setup do CurrentUser.user = FactoryBot.create(:moderator_user) end - + should "update the topic's updated_at timestamp" do @topic.reload assert_equal(@posts[-1].updated_at.to_i, @topic.updated_at.to_i) @@ -147,7 +147,7 @@ class ForumPostTest < ActiveSupport::TestCase 3.times do posts << FactoryBot.create(:forum_post, :topic_id => @topic.id, :body => rand(100_000)) end - + # updating the original post travel(1.second) do posts.first.update(body: "xxx") diff --git a/test/unit/forum_topic_test.rb b/test/unit/forum_topic_test.rb index 109c4a446..a5e491774 100644 --- a/test/unit/forum_topic_test.rb +++ b/test/unit/forum_topic_test.rb @@ -49,7 +49,7 @@ class ForumTopicTest < ActiveSupport::TestCase context "that postdates the topic" do setup do FactoryBot.create(:forum_topic_visit, user: @user, forum_topic: @topic, last_read_at: 2.days.from_now) - end + end should "return true" do assert_equal(true, @topic.read_by?(@user)) @@ -78,7 +78,7 @@ class ForumTopicTest < ActiveSupport::TestCase context "that postdates the topic" do setup do - FactoryBot.create(:forum_topic_visit, user: @user, forum_topic: @topic, last_read_at: 1.days.from_now) + FactoryBot.create(:forum_topic_visit, user: @user, forum_topic: @topic, last_read_at: 1.day.from_now) end should "return true" do @@ -128,7 +128,7 @@ class ForumTopicTest < ActiveSupport::TestCase should "create a matching forum post" do assert_difference(["ForumTopic.count", "ForumPost.count"], 1) do @topic = FactoryBot.create(:forum_topic, :title => "abc", :original_post_attributes => {:body => "abc"}) - end + end end end diff --git a/test/unit/pool_test.rb b/test/unit/pool_test.rb index aef8ab2b1..5710439fa 100644 --- a/test/unit/pool_test.rb +++ b/test/unit/pool_test.rb @@ -1,5 +1,3 @@ -# encoding: utf-8 - require 'test_helper' class PoolTest < ActiveSupport::TestCase diff --git a/test/unit/post_archive_test.rb b/test/unit/post_archive_test.rb index 883fc6304..b4247214f 100644 --- a/test/unit/post_archive_test.rb +++ b/test/unit/post_archive_test.rb @@ -62,7 +62,7 @@ class PostArchiveTest < ActiveSupport::TestCase should "also create a version" do assert_equal(1, @post.versions.size) - @version = @post.versions.sort_by(&:id).last + @version = @post.versions.max_by(&:id) assert_equal("aaa bbb ccc", @version.tags) assert_equal(@post.rating, @version.rating) assert_equal(@post.parent_id, @version.parent_id) @@ -109,7 +109,7 @@ class PostArchiveTest < ActiveSupport::TestCase should "also create a version" do assert_equal(2, @post.versions.size) - @version = @post.versions.sort_by(&:id).last + @version = @post.versions.max_by(&:id) assert_equal("bbb ccc xxx", @version.tags) assert_equal("q", @version.rating) assert_equal("", @version.source) @@ -127,14 +127,14 @@ class PostArchiveTest < ActiveSupport::TestCase should "should create a version if the rating changes" do assert_difference("@post.versions.size", 1) do @post.update(rating: "s") - assert_equal("s", @post.versions.sort_by(&:id).last.rating) + assert_equal("s", @post.versions.max_by(&:id).rating) end end should "should create a version if the source changes" do assert_difference("@post.versions.size", 1) do @post.update(source: "blah") - assert_equal("blah", @post.versions.sort_by(&:id).last.source) + assert_equal("blah", @post.versions.max_by(&:id).source) end end @@ -142,14 +142,14 @@ class PostArchiveTest < ActiveSupport::TestCase assert_difference("@post.versions.size", 1) do @parent = FactoryBot.create(:post) @post.update(parent_id: @parent.id) - assert_equal(@parent.id, @post.versions.sort_by(&:id).last.parent_id) + assert_equal(@parent.id, @post.versions.max_by(&:id).parent_id) end end should "should create a version if the tags change" do assert_difference("@post.versions.size", 1) do @post.update(tag_string: "blah") - assert_equal("blah", @post.versions.sort_by(&:id).last.tags) + assert_equal("blah", @post.versions.max_by(&:id).tags) end end end diff --git a/test/unit/post_flag_test.rb b/test/unit/post_flag_test.rb index 43d1efc07..090597e1a 100644 --- a/test/unit/post_flag_test.rb +++ b/test/unit/post_flag_test.rb @@ -38,7 +38,7 @@ class PostFlagTest < ActiveSupport::TestCase should "not be able to flag a post more than twice" do assert_difference(-> { PostFlag.count }, 1) do as(@bob) do - @post_flag = PostFlag.create(post: @post, reason: "aaa", is_resolved: false) + @post_flag = PostFlag.create(post: @post, reason: "aaa", is_resolved: false) end end diff --git a/test/unit/post_pruner_test.rb b/test/unit/post_pruner_test.rb index a8cdeec4e..5ba413419 100644 --- a/test/unit/post_pruner_test.rb +++ b/test/unit/post_pruner_test.rb @@ -25,7 +25,7 @@ class PostPrunerTest < ActiveSupport::TestCase def teardown super - + CurrentUser.user = nil CurrentUser.ip_addr = nil end diff --git a/test/unit/post_test.rb b/test/unit/post_test.rb index a648aecd6..1443bf5b7 100644 --- a/test/unit/post_test.rb +++ b/test/unit/post_test.rb @@ -301,7 +301,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "Deleting a post with" do context "a parent" do should "not reassign favorites to the parent by default" do @@ -716,7 +716,6 @@ class PostTest < ActiveSupport::TestCase end context "tagged with a metatag" do - context "for typing a tag" do setup do @post = FactoryBot.create(:post, tag_string: "char:hoge") @@ -828,14 +827,14 @@ class PostTest < ActiveSupport::TestCase should "add the post to the favgroup" do assert_equal(1, @favgroup.reload.post_count) - assert_equal(true, !!@favgroup.contains?(@post.id)) + assert_equal(true, @favgroup.contains?(@post.id)) end should "remove the post from the favgroup" do @post.update(:tag_string => "-favgroup:#{@favgroup.id}") assert_equal(0, @favgroup.reload.post_count) - assert_equal(false, !!@favgroup.contains?(@post.id)) + assert_equal(false, @favgroup.contains?(@post.id)) end end @@ -1814,7 +1813,7 @@ class PostTest < ActiveSupport::TestCase setup do mock_pool_archive_service! end - + should "return posts for the age:<1minute tag" do post = FactoryBot.create(:post) assert_tag_match([post], "age:<1minute") @@ -2261,7 +2260,7 @@ class PostTest < ActiveSupport::TestCase context "labeled" do should "work" do SavedSearch.expects(:post_ids_for).with(CurrentUser.id, label: "zzz").returns([@post1.id]) - assert_tag_match([@post1], "search:zzz") + assert_tag_match([@post1], "search:zzz") end end @@ -2275,7 +2274,7 @@ class PostTest < ActiveSupport::TestCase context "all" do should "work" do SavedSearch.expects(:post_ids_for).with(CurrentUser.id).returns([@post1.id, @post2.id]) - assert_tag_match([@post2, @post1], "search:all") + assert_tag_match([@post2, @post1], "search:all") end end end @@ -2348,9 +2347,9 @@ class PostTest < ActiveSupport::TestCase fav_count: n, file_size: 1.megabyte * n, # posts[0] is portrait, posts[1] is landscape. posts[1].mpixels > posts[0].mpixels. - image_height: 100*n*n, - image_width: 100*(3-n)*n, - tag_string: tags[n-1], + image_height: 100 * n * n, + image_width: 100 * (3 - n) * n, + tag_string: tags[n - 1] ) FactoryBot.create(:artist_commentary, post: p) @@ -2480,7 +2479,7 @@ class PostTest < ActiveSupport::TestCase FactoryBot.create(:super_voter, user: @user) @post = FactoryBot.create(:post) end - + should "account for magnitude" do CurrentUser.scoped(@user, "127.0.0.1") do assert_nothing_raised {@post.vote!("up")} diff --git a/test/unit/post_view_count_service_test.rb b/test/unit/post_view_count_service_test.rb index e50fbde2f..ce9b856ac 100644 --- a/test/unit/post_view_count_service_test.rb +++ b/test/unit/post_view_count_service_test.rb @@ -24,7 +24,7 @@ class PostViewCountServiceTest < ActiveSupport::TestCase setup do subject.stubs(:fetch_rank).returns([[@post.id, 1]]) end - + should "return the posts" do posts = subject.popular_posts assert_equal(@post.id, posts[0].id) diff --git a/test/unit/related_tag_query_test.rb b/test/unit/related_tag_query_test.rb index 6023313fa..b2e3f06b8 100644 --- a/test/unit/related_tag_query_test.rb +++ b/test/unit/related_tag_query_test.rb @@ -122,4 +122,3 @@ class RelatedTagQueryTest < ActiveSupport::TestCase end end end - diff --git a/test/unit/sources/nico_seiga_test.rb b/test/unit/sources/nico_seiga_test.rb index 0365d90eb..8ff4d2eec 100644 --- a/test/unit/sources/nico_seiga_test.rb +++ b/test/unit/sources/nico_seiga_test.rb @@ -35,11 +35,11 @@ module Sources end should "get the tags" do - assert(@site_1.tags.size > 0) + assert_not(@site_1.tags.empty?) first_tag = @site_1.tags.first assert_equal(["アニメ", "https://seiga.nicovideo.jp/tag/%E3%82%A2%E3%83%8B%E3%83%A1"], first_tag) - assert(@site_2.tags.size > 0) + assert_not(@site_2.tags.empty?) first_tag = @site_2.tags.first assert_equal(["アニメ", "https://seiga.nicovideo.jp/tag/%E3%82%A2%E3%83%8B%E3%83%A1"], first_tag) end diff --git a/test/unit/sources/pawoo_test.rb b/test/unit/sources/pawoo_test.rb index 9fd569f26..9458d7d66 100644 --- a/test/unit/sources/pawoo_test.rb +++ b/test/unit/sources/pawoo_test.rb @@ -2,7 +2,7 @@ require 'test_helper' module Sources class PawooTest < ActiveSupport::TestCase - context "The source site for a https://pawoo.net/web/status/$id url" do + context "The source site for a https://pawoo.net/web/status/$id url" do setup do skip "Pawoo keys not set" unless Danbooru.config.pawoo_client_id @site = Sources::Strategies.find("https://pawoo.net/web/statuses/1202176") @@ -31,7 +31,7 @@ module Sources end end - context "The source site for a https://pawoo.net/$user/$id url" do + context "The source site for a https://pawoo.net/$user/$id url" do setup do skip "Pawoo keys not set" unless Danbooru.config.pawoo_client_id @site = Sources::Strategies.find("https://pawoo.net/@evazion/19451018") @@ -82,7 +82,7 @@ module Sources end end - context "The source site for a https://img.pawoo.net/ url" do + context "The source site for a https://img.pawoo.net/ url" do setup do skip "Pawoo keys not set" unless Danbooru.config.pawoo_client_id @url = "https://img.pawoo.net/media_attachments/files/001/298/028/original/55a6fd252778454b.mp4" diff --git a/test/unit/sources/pixiv_test.rb b/test/unit/sources/pixiv_test.rb index d8de1fa9b..9b11a2dd9 100644 --- a/test/unit/sources/pixiv_test.rb +++ b/test/unit/sources/pixiv_test.rb @@ -59,9 +59,9 @@ module Sources should "capture the frame data" do assert_equal(2, @site.ugoira_frame_data.size) if @site.ugoira_frame_data[0]["file"] - assert_equal([{"file"=>"000000.jpg", "delay"=>125}, {"file"=>"000001.jpg", "delay"=>125}], @site.ugoira_frame_data) + assert_equal([{"file" => "000000.jpg", "delay" => 125}, {"file" => "000001.jpg", "delay" => 125}], @site.ugoira_frame_data) else - assert_equal([{"delay_msec"=>125}, {"delay_msec"=>125}], @site.ugoira_frame_data) + assert_equal([{"delay_msec" => 125}, {"delay_msec" => 125}], @site.ugoira_frame_data) end end end @@ -171,7 +171,7 @@ module Sources should "get the full size image url" do assert_equal("https://i.pximg.net/img-original/img/2017/08/18/00/09/21/64476642_p0.jpg", @site.image_url) - end + end should "get the full size image url for the canonical url" do assert_equal("https://i.pximg.net/img-original/img/2017/08/18/00/09/21/64476642_p0.jpg", @site.canonical_url) @@ -223,7 +223,7 @@ module Sources "mutsu_(kantai_collection)" => "陸奥", "fate/grand_order" => "Fate/GrandOrder", "fate" => "", - "foo" => "", + "foo" => "" } tags.each do |tag, other_names| diff --git a/test/unit/sources/twitter_test.rb b/test/unit/sources/twitter_test.rb index 3a495a55f..381967fd3 100644 --- a/test/unit/sources/twitter_test.rb +++ b/test/unit/sources/twitter_test.rb @@ -213,7 +213,7 @@ module Sources should "get the tags" do tags = [ %w[foo https://twitter.com/hashtag/foo], - %w[ホワイトデー https://twitter.com/hashtag/ホワイトデー], + %w[ホワイトデー https://twitter.com/hashtag/ホワイトデー] ] assert_equal(tags, @site.tags) diff --git a/test/unit/token_bucket_test.rb b/test/unit/token_bucket_test.rb index 358787329..3c96b371a 100644 --- a/test/unit/token_bucket_test.rb +++ b/test/unit/token_bucket_test.rb @@ -24,7 +24,7 @@ class TokenBucketTest < ActiveSupport::TestCase should "work" do @user.token_bucket.consume! assert_operator(@user.token_bucket.token_count, :<, 1) - @user.reload + @user.reload assert_operator(@user.token_bucket.token_count, :<, 1) end end diff --git a/test/unit/user_feedback_test.rb b/test/unit/user_feedback_test.rb index 280a07084..fe06b0920 100644 --- a/test/unit/user_feedback_test.rb +++ b/test/unit/user_feedback_test.rb @@ -28,7 +28,7 @@ class UserFeedbackTest < ActiveSupport::TestCase assert_equal(dmail, user.dmails.last.body) end end - + should "not validate if the creator is the user" do gold_user = FactoryBot.create(:gold_user) CurrentUser.user = gold_user diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index b6c5f461c..c00804bcb 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -88,7 +88,7 @@ class UserTest < ActiveSupport::TestCase @user.update_column(:created_at, 1.year.ago) assert(@user.can_comment?) assert(!@user.is_comment_limited?) - (Danbooru.config.member_comment_limit).times do + Danbooru.config.member_comment_limit.times do FactoryBot.create(:comment) end assert(@user.is_comment_limited?)