diff --git a/app/controllers/admin/alias_and_implication_imports_controller.rb b/app/controllers/admin/alias_and_implication_imports_controller.rb index 1bf119be1..4f3860bbd 100644 --- a/app/controllers/admin/alias_and_implication_imports_controller.rb +++ b/app/controllers/admin/alias_and_implication_imports_controller.rb @@ -1,10 +1,10 @@ module Admin class AliasAndImplicationImportsController < ApplicationController before_filter :admin_only - + def new end - + def create @importer = AliasAndImplicationImporter.new(params[:batch][:text], params[:batch][:forum_id]) @importer.process! diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index db16c0b9c..0a48f367d 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -1,11 +1,11 @@ module Admin class UsersController < ApplicationController before_filter :moderator_only - + def edit @user = User.find(params[:id]) end - + def update @user = User.find(params[:id]) @user.level = params[:user][:level] diff --git a/app/controllers/advertisement_hits_controller.rb b/app/controllers/advertisement_hits_controller.rb index f250cafc2..926304707 100644 --- a/app/controllers/advertisement_hits_controller.rb +++ b/app/controllers/advertisement_hits_controller.rb @@ -8,5 +8,5 @@ class AdvertisementHitsController < ApplicationController protected def set_title @page_title = Danbooru.config.app_name + "/advertisements" - end + end end diff --git a/app/controllers/advertisements_controller.rb b/app/controllers/advertisements_controller.rb index 922324af7..f808216f1 100644 --- a/app/controllers/advertisements_controller.rb +++ b/app/controllers/advertisements_controller.rb @@ -1,27 +1,27 @@ class AdvertisementsController < ApplicationController before_filter :advertiser_only - + def new @advertisement = Advertisement.new( :ad_type => "vertical", :status => "active" ) end - + def edit @advertisement = Advertisement.find(params[:id]) end - + def index @advertisements = Advertisement.order("id desc").all @start_date = 1.month.ago.to_date @end_date = Date.today end - + def show @advertisement = Advertisement.find(params[:id]) end - + def create @advertisement = Advertisement.new(params[:advertisement]) if @advertisement.save @@ -31,7 +31,7 @@ class AdvertisementsController < ApplicationController render :action => "new" end end - + def update @advertisement = Advertisement.find(params[:id]) if @advertisement.update_attributes(params[:advertisement]) @@ -41,13 +41,13 @@ class AdvertisementsController < ApplicationController render :action => "edit" end end - + def destroy @advertisement = Advertisement.find(params[:id]) @advertisement.destroy redirect_to advertisements_path, :notice => "Advertisement destroyed" end - + private def advertiser_only if !Danbooru.config.is_user_advertiser?(CurrentUser.user) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index c6cce8c31..dd589d8ac 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -6,14 +6,14 @@ class ApplicationController < ActionController::Base before_filter :set_title before_filter :set_started_at_session layout "default" - + rescue_from User::PrivilegeError, :with => :access_denied rescue_from Danbooru::Paginator::PaginationError, :with => :render_pagination_limit protected def rescue_exception(exception) @exception = exception - + if exception.is_a?(::ActiveRecord::StatementInvalid) && exception.to_s =~ /statement timeout/ @exception = nil @error_message = "The database timed out running your query." @@ -26,17 +26,17 @@ protected render :template => "static/error", :status => 500 end end - + def render_pagination_limit @error_message = "You can only view up to #{Danbooru.config.max_numbered_pages} pages. Please narrow your search terms." render :template => "static/error", :status => 410 end - + def access_denied previous_url = params[:url] || request.fullpath respond_to do |fmt| - fmt.html do + fmt.html do if request.get? redirect_to new_session_path(:url => previous_url), :notice => "Access denied" else @@ -56,18 +56,18 @@ protected session_loader = SessionLoader.new(session, cookies, request) session_loader.load end - + def reset_current_user CurrentUser.user = nil CurrentUser.ip_addr = nil end - + def set_started_at_session if session[:started_at].blank? session[:started_at] = Time.now end end - + %w(member banned privileged platinum contributor janitor moderator admin).each do |level| define_method("#{level}_only") do if CurrentUser.user.__send__("is_#{level}?") @@ -78,7 +78,7 @@ protected end end end - + def set_title @page_title = Danbooru.config.app_name + "/#{params[:controller]}" end diff --git a/app/controllers/artists_controller.rb b/app/controllers/artists_controller.rb index b485515d5..7ccb68aad 100644 --- a/app/controllers/artists_controller.rb +++ b/app/controllers/artists_controller.rb @@ -2,28 +2,28 @@ class ArtistsController < ApplicationController respond_to :html, :xml, :json before_filter :member_only, :except => [:index, :show, :banned] before_filter :admin_only, :only => [:ban] - + def new @artist = Artist.new_with_defaults(params) respond_with(@artist) end - + def edit @artist = Artist.find(params[:id]) respond_with(@artist) end - + def banned @artists = Artist.where("is_banned = ?", true).order("name") respond_with(@artists) end - + def ban @artist = Artist.find(params[:id]) @artist.ban! redirect_to(artist_path(@artist), :notice => "Artist was banned") end - + def index @artists = Artist.search(params[:search] || params).order("id desc").paginate(params[:page]) respond_with(@artists) do |format| @@ -35,34 +35,34 @@ class ArtistsController < ApplicationController end end end - + def search end - + def show @artist = Artist.find(params[:id]) @post_set = PostSets::Artist.new(@artist) respond_with(@artist) end - + def create @artist = Artist.create(params[:artist], :as => CurrentUser.role) respond_with(@artist) end - + def update @artist = Artist.find(params[:id]) @artist.update_attributes(params[:artist], :as => CurrentUser.role) respond_with(@artist) end - + def revert @artist = Artist.find(params[:id]) @version = ArtistVersion.find(params[:version_id]) @artist.revert_to!(@version) respond_with(@artist) end - + def show_or_new @artist = Artist.find_by_name(params[:name]) if @artist diff --git a/app/controllers/bans_controller.rb b/app/controllers/bans_controller.rb index 74effffbd..b0dd2b44f 100644 --- a/app/controllers/bans_controller.rb +++ b/app/controllers/bans_controller.rb @@ -1,33 +1,33 @@ class BansController < ApplicationController before_filter :moderator_only, :except => [:show, :index] - + def new @ban = Ban.new end - + def edit @ban = Ban.find(params[:id]) end - + def index @search = Ban.search(params[:search]).order("id desc") @bans = @search.paginate(params[:page]) end - + def show @ban = Ban.find(params[:id]) end - + def create @ban = Ban.create(params[:ban]) - + if @ban.errors.any? render :action => "new" else redirect_to ban_path(@ban), :notice => "Ban created" end end - + def update @ban = Ban.find(params[:id]) if @ban.update_attributes(params[:ban]) @@ -35,8 +35,8 @@ class BansController < ApplicationController else render :action => "edit" end - end - + end + def destroy @ban = Ban.find(params[:id]) @ban.destroy diff --git a/app/controllers/comment_votes_controller.rb b/app/controllers/comment_votes_controller.rb index f1702021e..c0c8c75f7 100644 --- a/app/controllers/comment_votes_controller.rb +++ b/app/controllers/comment_votes_controller.rb @@ -1,7 +1,7 @@ class CommentVotesController < ApplicationController respond_to :js before_filter :member_only - + def create @comment = Comment.find(params[:comment_id]) @comment_vote = @comment.vote!(params[:score]) diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb index 0321a52fa..9ee3c8ea3 100644 --- a/app/controllers/comments_controller.rb +++ b/app/controllers/comments_controller.rb @@ -3,7 +3,7 @@ class CommentsController < ApplicationController before_filter :member_only, :only => [:update, :create, :edit, :destroy] rescue_from User::PrivilegeError, :with => "static/access_denied" rescue_from ActiveRecord::StatementInvalid, :with => :search_error - + def index if params[:group_by] == "comment" index_by_comment @@ -13,21 +13,21 @@ class CommentsController < ApplicationController index_by_post end end - + def search end - + def new redirect_to comments_path end - + def update @comment = Comment.find(params[:id]) check_privilege(@comment) @comment.update_attributes(params[:comment]) respond_with(@comment, :location => post_path(@comment.post_id)) end - + def create @comment = Comment.create(params[:comment]) respond_with(@comment) do |format| @@ -40,20 +40,20 @@ class CommentsController < ApplicationController end end end - + def edit @comment = Comment.find(params[:id]) check_privilege(@comment) respond_with(@comment) end - + def show @comment = Comment.find(params[:id]) respond_with(@comment) do |format| format.json {render :json => @comment.to_json(:methods => [:creator_name])} end end - + def destroy @comment = Comment.find(params[:id]) check_privilege(@comment) @@ -62,7 +62,7 @@ class CommentsController < ApplicationController format.js end end - + private def index_for_post @post = Post.find(params[:post_id]) @@ -78,14 +78,14 @@ private format.html {render :action => "index_by_post"} end end - + def index_by_comment @comments = Comment.search(params[:search]).order("comments.id DESC").paginate(params[:page], :search_count => params[:search]) respond_with(@comments) do |format| format.html {render :action => "index_by_comment"} end end - + def check_privilege(comment) if !comment.editable_by?(CurrentUser.user) raise User::PrivilegeError @@ -93,7 +93,7 @@ private end protected - + def search_error(e) if e.message =~ /syntax error in tsquery/ @error_message = "Meta-tags are not supported in comment searches by tag" diff --git a/app/controllers/dmails_controller.rb b/app/controllers/dmails_controller.rb index a164631ab..c9812d990 100644 --- a/app/controllers/dmails_controller.rb +++ b/app/controllers/dmails_controller.rb @@ -9,19 +9,19 @@ class DmailsController < ApplicationController else @dmail = Dmail.new(params[:dmail]) end - + respond_with(@dmail) end - + def index @search = Dmail.visible.search(params[:search]) @dmails = @search.order("dmails.created_at desc").paginate(params[:page]) respond_with(@dmails) end - + def search end - + def show @dmail = Dmail.find(params[:id]) check_privilege(@dmail) @@ -33,20 +33,20 @@ class DmailsController < ApplicationController @dmail = Dmail.create_split(params[:dmail]) respond_with(@dmail) end - + def destroy @dmail = Dmail.find(params[:id]) check_privilege(@dmail) @dmail.destroy redirect_to dmails_path, :notice => "Message destroyed" end - + def mark_all_as_read Dmail.visible.unread.each do |x| x.update_column(:is_read, true) end end - + private def check_privilege(dmail) if !dmail.visible_to?(CurrentUser.user) diff --git a/app/controllers/explore/posts_controller.rb b/app/controllers/explore/posts_controller.rb index 324e013cd..e19ca0c95 100644 --- a/app/controllers/explore/posts_controller.rb +++ b/app/controllers/explore/posts_controller.rb @@ -1,7 +1,7 @@ module Explore class PostsController < ApplicationController respond_to :html, :xml, :json - + def popular @post_set = PostSets::Popular.new(params[:date], params[:scale]) @posts = @post_set.posts diff --git a/app/controllers/favorites_controller.rb b/app/controllers/favorites_controller.rb index 9148c8aa6..7a0e7bd6d 100644 --- a/app/controllers/favorites_controller.rb +++ b/app/controllers/favorites_controller.rb @@ -1,6 +1,6 @@ class FavoritesController < ApplicationController before_filter :member_only - + def index if params[:tags] redirect_to(posts_path(:tags => params[:tags])) @@ -8,7 +8,7 @@ class FavoritesController < ApplicationController @favorite_set = PostSets::Favorite.new(CurrentUser.user, params[:page]) end end - + def create if CurrentUser.favorite_limit.nil? || CurrentUser.favorite_count < CurrentUser.favorite_limit @post = Post.find(params[:post_id]) @@ -17,7 +17,7 @@ class FavoritesController < ApplicationController @error_msg = "You can only keep up to #{CurrentUser.favorite_limit} favorites. Upgrade your account to save more." end end - + def destroy @post = Post.find(params[:id]) @post.remove_favorite!(CurrentUser.user) diff --git a/app/controllers/forum_posts_controller.rb b/app/controllers/forum_posts_controller.rb index 88a40b51c..3d1ee7956 100644 --- a/app/controllers/forum_posts_controller.rb +++ b/app/controllers/forum_posts_controller.rb @@ -8,19 +8,19 @@ class ForumPostsController < ApplicationController @forum_post = ForumPost.new_reply(params) respond_with(@forum_post) end - + def edit @forum_post = ForumPost.find(params[:id]) check_privilege(@forum_post) respond_with(@forum_post) end - + def index @search = ForumPost.active.search(params[:search]) @forum_posts = @search.order("forum_posts.id DESC").paginate(params[:page], :search_count => params[:search]) respond_with(@forum_posts) end - + def search end @@ -32,33 +32,33 @@ class ForumPostsController < ApplicationController respond_with(@forum_post) end end - + def create @forum_post = ForumPost.create(params[:forum_post]) respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => @forum_post.topic.last_page)) end - + def update @forum_post = ForumPost.find(params[:id]) check_privilege(@forum_post) @forum_post.update_attributes(params[:forum_post]) respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => @forum_post.forum_topic_page)) end - + def destroy @forum_post = ForumPost.find(params[:id]) raise User::PrivilegeError unless @forum_post.editable_by?(CurrentUser.user) @forum_post.update_attribute(:is_deleted, true) respond_with(@forum_post) end - + def undelete @forum_post = ForumPost.find(params[:id]) check_privilege(@forum_post) @forum_post.update_attribute(:is_deleted, false) respond_with(@forum_post) end - + private def check_privilege(forum_post) if !forum_post.editable_by?(CurrentUser.user) diff --git a/app/controllers/forum_topics_controller.rb b/app/controllers/forum_topics_controller.rb index c9cc1827e..a964c83e3 100644 --- a/app/controllers/forum_topics_controller.rb +++ b/app/controllers/forum_topics_controller.rb @@ -10,45 +10,45 @@ class ForumTopicsController < ApplicationController @forum_topic.original_post = ForumPost.new respond_with(@forum_topic) end - + def edit @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) respond_with(@forum_topic) end - + def index @search = ForumTopic.active.search(params[:search]) @forum_topics = @search.order("is_sticky DESC, updated_at DESC").paginate(params[:page], :search_count => params[:search]) respond_with(@forum_topics) end - + def show @forum_topic = ForumTopic.find(params[:id]) @forum_posts = ForumPost.search(:topic_id => @forum_topic.id).order("forum_posts.id").paginate(params[:page]) @forum_posts.all respond_with(@forum_topic) end - + def create @forum_topic = ForumTopic.create(params[:forum_topic], :as => CurrentUser.role) respond_with(@forum_topic) end - + def update @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) @forum_topic.update_attributes(params[:forum_topic], :as => CurrentUser.role) respond_with(@forum_topic) end - + def destroy @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) @forum_topic.update_attribute(:is_deleted, true) respond_with(@forum_topic) end - + def undelete @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) @@ -64,18 +64,18 @@ class ForumTopicsController < ApplicationController private def update_last_forum_read_at return if CurrentUser.is_anonymous? - + if CurrentUser.last_forum_read_at.nil? || CurrentUser.last_forum_read_at < @forum_topic.updated_at CurrentUser.update_column(:last_forum_read_at, @forum_topic.updated_at) end end - + def normalize_search if params[:title_matches] params[:search] ||= {} params[:search][:title_matches] = params.delete(:title_matches) end - + if params[:title] params[:search] ||= {} params[:search][:title] = params.delete(:title) diff --git a/app/controllers/ip_bans_controller.rb b/app/controllers/ip_bans_controller.rb index a278d2a68..9873ee26f 100644 --- a/app/controllers/ip_bans_controller.rb +++ b/app/controllers/ip_bans_controller.rb @@ -14,12 +14,12 @@ class IpBansController < ApplicationController redirect_to ip_bans_path end end - + def index @search = IpBan.search(params[:search]) @ip_bans = @search.order("id desc").paginate(params[:page]) end - + def destroy @ip_ban = IpBan.find(params[:id]) @ip_ban.destroy diff --git a/app/controllers/janitor_trials_controller.rb b/app/controllers/janitor_trials_controller.rb index d96bc7ec2..d2f35e324 100644 --- a/app/controllers/janitor_trials_controller.rb +++ b/app/controllers/janitor_trials_controller.rb @@ -1,28 +1,28 @@ class JanitorTrialsController < ApplicationController respond_to :html, :xml, :json before_filter :moderator_only, :only => [:create, :promote, :demote] - + def new @janitor_trial = JanitorTrial.new respond_with(@janitor_trial) end - + def edit @janitor_trial = JanitorTrial.find(params[:id]) respond_with(@janitor_trial) end - + def index @search = JanitorTrial.search(params[:search]) @janitor_trials = @search.order("id desc").paginate(params[:page]) respond_with(@janitor_trials) end - + def create @janitor_trial = JanitorTrial.create(params[:janitor_trial]) respond_with(@janitor_trial, :location => janitor_trials_path) end - + def promote @janitor_trial = JanitorTrial.find(params[:id]) @janitor_trial.promote! @@ -30,7 +30,7 @@ class JanitorTrialsController < ApplicationController format.js end end - + def demote @janitor_trial = JanitorTrial.find(params[:id]) @janitor_trial.demote! @@ -38,7 +38,7 @@ class JanitorTrialsController < ApplicationController format.js end end - + def test @tester = JanitorTrialTester.new(params[:janitor_trial][:user_name]) end diff --git a/app/controllers/legacy_controller.rb b/app/controllers/legacy_controller.rb index 9cc2dd955..11e01264a 100644 --- a/app/controllers/legacy_controller.rb +++ b/app/controllers/legacy_controller.rb @@ -6,7 +6,7 @@ class LegacyController < ApplicationController @post_set = PostSets::Post.new(tag_query, params[:page], params[:limit]) @posts = @post_set.posts end - + def create_post @upload = Upload.new @upload.server = Socket.gethostname @@ -19,19 +19,19 @@ class LegacyController < ApplicationController @upload.save @upload.process! end - + def users @users = User.limit(100).search(params).paginate(params[:page]) end - + def tags @tags = Tag.limit(100).search(params).paginate(params[:page], :limit => params[:limit]) end - + def artists @artists = Artist.limit(100).search(params[:search]).paginate(params[:page]) end - + def unavailable render :text => "this resource is no longer available", :status => 410 end diff --git a/app/controllers/maintenance/user/login_reminders_controller.rb b/app/controllers/maintenance/user/login_reminders_controller.rb index 15b043798..4f86c2945 100644 --- a/app/controllers/maintenance/user/login_reminders_controller.rb +++ b/app/controllers/maintenance/user/login_reminders_controller.rb @@ -3,7 +3,7 @@ module Maintenance class LoginRemindersController < ApplicationController def new end - + def create @user = ::User.with_email(params[:user][:email]).first if @user @@ -12,7 +12,7 @@ module Maintenance else flash[:notice] = "Email address not found" end - + redirect_to new_maintenance_user_login_reminder_path end end diff --git a/app/controllers/maintenance/user/password_resets_controller.rb b/app/controllers/maintenance/user/password_resets_controller.rb index 22116c39b..d11110714 100644 --- a/app/controllers/maintenance/user/password_resets_controller.rb +++ b/app/controllers/maintenance/user/password_resets_controller.rb @@ -4,7 +4,7 @@ module Maintenance def new @nonce = UserPasswordResetNonce.new end - + def create @nonce = UserPasswordResetNonce.create(params[:nonce]) if @nonce.errors.any? @@ -13,14 +13,14 @@ module Maintenance redirect_to new_maintenance_user_password_reset_path, :notice => "Email request sent" end end - + def edit @nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first end - + def update @nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first - + if @nonce @nonce.reset_user! @nonce.destroy diff --git a/app/controllers/moderator/dashboards_controller.rb b/app/controllers/moderator/dashboards_controller.rb index 37e41a7a8..f309de217 100644 --- a/app/controllers/moderator/dashboards_controller.rb +++ b/app/controllers/moderator/dashboards_controller.rb @@ -2,7 +2,7 @@ module Moderator class DashboardsController < ApplicationController before_filter :janitor_only helper :post_flags, :post_appeals - + def show @dashboard = Moderator::Dashboard::Report.new(params[:min_date] || 2.days.ago.to_date, params[:max_level] || 20) end diff --git a/app/controllers/moderator/invitations_controller.rb b/app/controllers/moderator/invitations_controller.rb index 82a725cfc..2d475756f 100644 --- a/app/controllers/moderator/invitations_controller.rb +++ b/app/controllers/moderator/invitations_controller.rb @@ -1,15 +1,15 @@ module Moderator class InvitationsController < ApplicationController before_filter :moderator_only - + def new end - + def create User.find(params[:invitation][:user_id]).invite!(params[:invitation][:level]) redirect_to moderator_invitations_path end - + def index @users = User.where("inviter_id = ?", CurrentUser.id).paginate(params[:page]) end diff --git a/app/controllers/moderator/ip_addrs_controller.rb b/app/controllers/moderator/ip_addrs_controller.rb index 94c38a9c7..4f923742f 100644 --- a/app/controllers/moderator/ip_addrs_controller.rb +++ b/app/controllers/moderator/ip_addrs_controller.rb @@ -1,11 +1,11 @@ module Moderator class IpAddrsController < ApplicationController before_filter :janitor_only - + def index @search = IpAddrSearch.new(params[:search]) end - + def search end end diff --git a/app/controllers/moderator/post/approvals_controller.rb b/app/controllers/moderator/post/approvals_controller.rb index fbbb4affd..eeaa6c91f 100644 --- a/app/controllers/moderator/post/approvals_controller.rb +++ b/app/controllers/moderator/post/approvals_controller.rb @@ -2,7 +2,7 @@ module Moderator module Post class ApprovalsController < ApplicationController before_filter :janitor_only - + def create @post = ::Post.find(params[:post_id]) if @post.is_deleted? || @post.is_flagged? || @post.is_pending? diff --git a/app/controllers/moderator/post/disapprovals_controller.rb b/app/controllers/moderator/post/disapprovals_controller.rb index 830fd7d09..a7f86582f 100644 --- a/app/controllers/moderator/post/disapprovals_controller.rb +++ b/app/controllers/moderator/post/disapprovals_controller.rb @@ -2,7 +2,7 @@ module Moderator module Post class DisapprovalsController < ApplicationController before_filter :janitor_only - + def create @post = ::Post.find(params[:post_id]) @post_disapproval = PostDisapproval.create(:post => @post, :user => CurrentUser.user) diff --git a/app/controllers/moderator/post/posts_controller.rb b/app/controllers/moderator/post/posts_controller.rb index 80d58212f..0deddf3f8 100644 --- a/app/controllers/moderator/post/posts_controller.rb +++ b/app/controllers/moderator/post/posts_controller.rb @@ -8,7 +8,7 @@ module Moderator def confirm_delete @post = ::Post.find(params[:id]) end - + def delete @post = ::Post.find(params[:id]) if params[:commit] == "Delete" @@ -17,12 +17,12 @@ module Moderator end redirect_to(post_path(@post)) end - + def undelete @post = ::Post.find(params[:id]) @post.undelete! end - + def annihilate @post = ::Post.find(params[:id]) @post.annihilate! diff --git a/app/controllers/moderator/post/queues_controller.rb b/app/controllers/moderator/post/queues_controller.rb index 49be12c7a..d0dfa2fbc 100644 --- a/app/controllers/moderator/post/queues_controller.rb +++ b/app/controllers/moderator/post/queues_controller.rb @@ -3,7 +3,7 @@ module Moderator class QueuesController < ApplicationController respond_to :html, :json before_filter :janitor_only - + def show ::Post.without_timeout do @posts = ::Post.order("posts.id asc").pending_or_flagged.available_for_moderation(params[:hidden]).search(:tag_match => "#{params[:query]} status:any").paginate(params[:page], :limit => 100) diff --git a/app/controllers/moderator/tags_controller.rb b/app/controllers/moderator/tags_controller.rb index 7bc4bc7fd..d44a6285f 100644 --- a/app/controllers/moderator/tags_controller.rb +++ b/app/controllers/moderator/tags_controller.rb @@ -2,15 +2,15 @@ module Moderator class TagsController < ApplicationController before_filter :moderator_only rescue_from TagBatchChange::Error, :with => :error - + def edit end - + def update Delayed::Job.enqueue(TagBatchChange.new(params[:tag][:antecedent], params[:tag][:consequent], CurrentUser.user, CurrentUser.ip_addr)) redirect_to edit_moderator_tag_path, :notice => "Post changes queued" end - + def error redirect_to edit_moderator_tag_path, :notice => "Error" end diff --git a/app/controllers/news_updates_controller.rb b/app/controllers/news_updates_controller.rb index 6e88c509a..784186b02 100644 --- a/app/controllers/news_updates_controller.rb +++ b/app/controllers/news_updates_controller.rb @@ -1,33 +1,33 @@ class NewsUpdatesController < ApplicationController before_filter :admin_only respond_to :html - + def index @news_updates = NewsUpdate.order("id desc").paginate(params[:page]) respond_with(@news_updates) end - + def edit @news_update = NewsUpdate.find(params[:id]) respond_with(@news_update) end - + def update @news_update = NewsUpdate.find(params[:id]) @news_update.update_attributes(params[:news_update]) respond_with(@news_update, :location => news_updates_path) end - + def new @news_update = NewsUpdate.new respond_with(@news_update) end - + def create @news_update = NewsUpdate.create(params[:news_update]) respond_with(@news_update, :location => news_updates_path) end - + def destroy @news_update = NewsUpdate.find(params[:id]) @news_update.destroy diff --git a/app/controllers/note_versions_controller.rb b/app/controllers/note_versions_controller.rb index 9af07a3af..d26d97875 100644 --- a/app/controllers/note_versions_controller.rb +++ b/app/controllers/note_versions_controller.rb @@ -1,7 +1,7 @@ class NoteVersionsController < ApplicationController respond_to :html, :xml, :json before_filter :member_only, :except => [:index, :show] - + def index @search = NoteVersion.search(params[:search]) @note_versions = @search.order("note_versions.id desc").paginate(params[:page]) diff --git a/app/controllers/notes_controller.rb b/app/controllers/notes_controller.rb index 8df8b85f7..78a597e24 100644 --- a/app/controllers/notes_controller.rb +++ b/app/controllers/notes_controller.rb @@ -2,10 +2,10 @@ class NotesController < ApplicationController respond_to :html, :xml, :json, :js before_filter :member_only, :except => [:index, :show] before_filter :pass_html_id, :only => [:create] - + def search end - + def index if params[:group_by] == "note" index_by_note @@ -13,12 +13,12 @@ class NotesController < ApplicationController index_by_post end end - + def show @note = Note.find(params[:id]) respond_with(@note) end - + def create @note = Note.create(params[:note]) respond_with(@note) do |fmt| @@ -27,19 +27,19 @@ class NotesController < ApplicationController end end end - + def update @note = Note.find(params[:id]) @note.update_attributes(params[:note]) respond_with(@note) end - + def destroy @note = Note.find(params[:id]) @note.update_attribute(:is_active, false) respond_with(@note) end - + def revert @note = Note.find(params[:id]) @version = NoteVersion.find(params[:version_id]) diff --git a/app/controllers/pool_elements_controller.rb b/app/controllers/pool_elements_controller.rb index 0e9dd3de9..898b76c98 100644 --- a/app/controllers/pool_elements_controller.rb +++ b/app/controllers/pool_elements_controller.rb @@ -1,30 +1,30 @@ class PoolElementsController < ApplicationController respond_to :html, :xml, :json, :js before_filter :member_only - + def create @pool = Pool.find_by_name(params[:pool_name]) || Pool.find_by_id(params[:pool_id]) - + if @pool.present? @post = Post.find(params[:post_id]) @pool.add!(@post) append_pool_to_session(@pool) end - + respond_with(@pool, :location => post_path(@post)) end - + def destroy @pool = Pool.find(params[:pool_id]) @post = Post.find(params[:post_id]) @pool.remove!(@post) respond_with(@pool, :location => post_path(@post)) end - + def all_select @pools = Pool.active.order("name").select("id, name").all end - + private def append_pool_to_session(pool) recent_pool_ids = session[:recent_pool_ids].to_s.scan(/\d+/) diff --git a/app/controllers/pool_versions_controller.rb b/app/controllers/pool_versions_controller.rb index f11a8de64..ed23ba526 100644 --- a/app/controllers/pool_versions_controller.rb +++ b/app/controllers/pool_versions_controller.rb @@ -3,7 +3,7 @@ class PoolVersionsController < ApplicationController if params[:search] && params[:search][:pool_id] @pool = Pool.find(params[:search][:pool_id]) end - + @pool_versions = PoolVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) end end diff --git a/app/controllers/pools_controller.rb b/app/controllers/pools_controller.rb index 32c5c0f13..9708d13f6 100644 --- a/app/controllers/pools_controller.rb +++ b/app/controllers/pools_controller.rb @@ -8,31 +8,31 @@ class PoolsController < ApplicationController @pool = Pool.new respond_with(@pool) end - + def edit @pool = Pool.find(params[:id]) respond_with(@pool) end - + def index @pools = Pool.active.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) respond_with(@pools) end - + def search end - + def show @pool = Pool.find(params[:id]) @post_set = PostSets::Pool.new(@pool, params[:page]) respond_with(@pool) end - + def create @pool = Pool.create(params[:pool]) respond_with(@pool, :notice => "Pool created") end - + def update # need to do this in order for synchronize! to work correctly @pool = Pool.find(params[:id]) @@ -41,7 +41,7 @@ class PoolsController < ApplicationController @pool.save respond_with(@pool, :notice => "Pool updated") end - + def destroy @pool = Pool.find(params[:id]) if !@pool.deletable_by?(CurrentUser.user) @@ -50,7 +50,7 @@ class PoolsController < ApplicationController @pool.update_attribute(:is_deleted, true) respond_with(@pool, :notice => "Pool deleted") end - + def undelete @pool = Pool.find(params[:id]) if !@pool.deletable_by?(CurrentUser.user) @@ -59,7 +59,7 @@ class PoolsController < ApplicationController @pool.update_attribute(:is_deleted, false) respond_with(@pool, :notice => "Pool undeleted") end - + def revert @pool = Pool.find(params[:id]) @version = PoolVersion.find(params[:version_id]) diff --git a/app/controllers/post_appeals_controller.rb b/app/controllers/post_appeals_controller.rb index 602598209..06508a602 100644 --- a/app/controllers/post_appeals_controller.rb +++ b/app/controllers/post_appeals_controller.rb @@ -7,12 +7,12 @@ class PostAppealsController < ApplicationController @post_appeal = PostAppeal.new respond_with(@post_appeal) end - + def index @search = PostAppeal.order("id desc").search(params[:search]) @post_appeals = @search.paginate(params[:page]) end - + def create @post_appeal = PostAppeal.create(params[:post_appeal]) respond_with(@post_appeal) diff --git a/app/controllers/post_flags_controller.rb b/app/controllers/post_flags_controller.rb index b3028ac17..0c05ec3d8 100644 --- a/app/controllers/post_flags_controller.rb +++ b/app/controllers/post_flags_controller.rb @@ -7,12 +7,12 @@ class PostFlagsController < ApplicationController @post_flag = PostFlag.new respond_with(@post_flag) end - + def index @search = PostFlag.order("id desc").search(params[:search]) @post_flags = @search.paginate(params[:page]) end - + def create @post_flag = PostFlag.create(params[:post_flag].merge(:is_resolved => false)) respond_with(@post_flag) diff --git a/app/controllers/post_versions_controller.rb b/app/controllers/post_versions_controller.rb index e607f40df..7cef5efd1 100644 --- a/app/controllers/post_versions_controller.rb +++ b/app/controllers/post_versions_controller.rb @@ -6,7 +6,7 @@ class PostVersionsController < ApplicationController @post_versions = PostVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) respond_with(@post_versions) end - + def search end end diff --git a/app/controllers/post_votes_controller.rb b/app/controllers/post_votes_controller.rb index ff17d60aa..f5cfe71c9 100644 --- a/app/controllers/post_votes_controller.rb +++ b/app/controllers/post_votes_controller.rb @@ -1,6 +1,6 @@ class PostVotesController < ApplicationController before_filter :privileged_only - + def create @post = Post.find(params[:post_id]) @post.vote!(params[:score]) diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index a72d35132..e7de7239a 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -6,7 +6,7 @@ class PostsController < ApplicationController rescue_from Post::SearchError, :with => :rescue_exception rescue_from ActiveRecord::StatementInvalid, :with => :rescue_exception rescue_from ActiveRecord::RecordNotFound, :with => :rescue_exception - + def index @post_set = PostSets::Post.new(tag_query, params[:page], params[:limit]) @posts = @post_set.posts @@ -14,14 +14,14 @@ class PostsController < ApplicationController format.atom end end - + def show @post = Post.find(params[:id]) @post_flag = PostFlag.new(:post_id => @post.id) @post_appeal = PostAppeal.new(:post_id => @post.id) respond_with(@post) end - + def show_seq context = PostSearchContext.new(params) if context.post_id @@ -30,14 +30,14 @@ class PostsController < ApplicationController redirect_to(post_path(params[:id], :tags => params[:tags])) end end - + def update @post = Post.find(params[:id]) if Danbooru.config.can_user_see_post?(CurrentUser.user, @post) @post.update_attributes(params[:post], :as => CurrentUser.role) end - + respond_with(@post) do |format| format.html do if @post.errors.any? @@ -49,13 +49,13 @@ class PostsController < ApplicationController redirect_to post_path(@post) end end - + format.json do render :json => @post.to_json end end end - + def revert @post = Post.find(params[:id]) @version = PostVersion.find(params[:version_id]) diff --git a/app/controllers/related_tags_controller.rb b/app/controllers/related_tags_controller.rb index a11fecd8e..921ca7d37 100644 --- a/app/controllers/related_tags_controller.rb +++ b/app/controllers/related_tags_controller.rb @@ -1,6 +1,6 @@ class RelatedTagsController < ApplicationController respond_to :json - + def show @query = RelatedTagQuery.new(params[:query].to_s.downcase, params[:category]) respond_with(@query) do |format| diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 9641e3977..53957e2fb 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -2,24 +2,24 @@ class SessionsController < ApplicationController def new @user = User.new end - + def create session_creator = SessionCreator.new(session, cookies, params[:name], params[:password], params[:remember]) - + if session_creator.authenticate redirect_to(params[:url] || session[:previous_uri] || posts_path, :notice => "You are now logged in.") else redirect_to(new_session_path, :notice => "Password was incorrect.") end end - + def destroy session.delete(:user_id) cookies.delete(:cookie_password_hash) cookies.delete(:user_name) redirect_to(posts_path, :notice => "You are now logged out.") end - + def sign_out destroy() end diff --git a/app/controllers/sources_controller.rb b/app/controllers/sources_controller.rb index b19f2d1cf..b098ac5f7 100644 --- a/app/controllers/sources_controller.rb +++ b/app/controllers/sources_controller.rb @@ -1,11 +1,11 @@ class SourcesController < ApplicationController # before_filter :member_only respond_to :json - + def show @source = Sources::Site.new(params[:url]) @source.get - + respond_with(@source) do |format| format.json do render :json => @source.to_json diff --git a/app/controllers/static_controller.rb b/app/controllers/static_controller.rb index ce98dc6cc..1294027cd 100644 --- a/app/controllers/static_controller.rb +++ b/app/controllers/static_controller.rb @@ -2,7 +2,7 @@ class StaticController < ApplicationController def terms_of_service render :layout => "blank" end - + def error end end diff --git a/app/controllers/tag_alias_corrections_controller.rb b/app/controllers/tag_alias_corrections_controller.rb index 2ceb919d2..1320fe993 100644 --- a/app/controllers/tag_alias_corrections_controller.rb +++ b/app/controllers/tag_alias_corrections_controller.rb @@ -1,6 +1,6 @@ class TagAliasCorrectionsController < ApplicationController before_filter :moderator_only - + def create @correction = TagAliasCorrection.new(params[:tag_alias_id]) @@ -8,10 +8,10 @@ class TagAliasCorrectionsController < ApplicationController @correction.fix! flash[:notice] = "The fix has been queued and will be processed" end - + redirect_to tag_alias_correction_path(:tag_alias_id => params[:tag_alias_id]) end - + def show @correction = TagAliasCorrection.new(params[:tag_alias_id]) end diff --git a/app/controllers/tag_alias_requests_controller.rb b/app/controllers/tag_alias_requests_controller.rb index 58737998a..ad256b29f 100644 --- a/app/controllers/tag_alias_requests_controller.rb +++ b/app/controllers/tag_alias_requests_controller.rb @@ -1,10 +1,10 @@ class TagAliasRequestsController < ApplicationController before_filter :member_only rescue_from TagAliasRequest::ValidationError, :with => :rescue_exception - + def new end - + def create @tag_alias_request = TagAliasRequest.new( params[:tag_alias_request][:antecedent_name], diff --git a/app/controllers/tag_aliases_controller.rb b/app/controllers/tag_aliases_controller.rb index 3bde039cd..b634bf5f7 100644 --- a/app/controllers/tag_aliases_controller.rb +++ b/app/controllers/tag_aliases_controller.rb @@ -1,12 +1,12 @@ class TagAliasesController < ApplicationController before_filter :admin_only, :only => [:approve, :destroy, :new, :create] respond_to :html, :xml, :json, :js - + def new @tag_alias = TagAlias.new(params[:tag_alias]) respond_with(@tag_alias) end - + def general_search if params[:commit] == "Search Aliases" redirect_to tag_aliases_path(:search => {:name_matches => params[:query]}) @@ -14,18 +14,18 @@ class TagAliasesController < ApplicationController redirect_to tag_implications_path(:search => {:name_matches => params[:query]}) end end - + def index @search = TagAlias.search(params[:search]) @tag_aliases = @search.order("(case status when 'pending' then 0 when 'queued' then 1 else 2 end), antecedent_name, consequent_name").paginate(params[:page]) respond_with(@tag_aliases) end - + def create @tag_alias = TagAlias.create(params[:tag_alias]) respond_with(@tag_alias, :location => tag_aliases_path(:search => {:id => @tag_alias.id})) end - + def destroy @tag_alias = TagAlias.find(params[:id]) @tag_alias.update_column(:status, "deleted") @@ -33,7 +33,7 @@ class TagAliasesController < ApplicationController @tag_alias.destroy respond_with(@tag_alias, :location => tag_aliases_path) end - + def approve @tag_alias = TagAlias.find(params[:id]) @tag_alias.update_column(:status, "queued") diff --git a/app/controllers/tag_corrections_controller.rb b/app/controllers/tag_corrections_controller.rb index ba44d9976..5a0b95515 100644 --- a/app/controllers/tag_corrections_controller.rb +++ b/app/controllers/tag_corrections_controller.rb @@ -1,16 +1,16 @@ class TagCorrectionsController < ApplicationController before_filter :member_only - + def new @correction = TagCorrection.new(params[:tag_id]) end - + def create if params[:commit] == "Fix" @correction = TagCorrection.new(params[:tag_id]) @correction.fix! end - + redirect_to tags_path(:search => {:name_matches => @correction.tag.name}), :notice => "Tag will be fixed in a few seconds" end end diff --git a/app/controllers/tag_implication_requests_controller.rb b/app/controllers/tag_implication_requests_controller.rb index c212fc3fc..ebb53de36 100644 --- a/app/controllers/tag_implication_requests_controller.rb +++ b/app/controllers/tag_implication_requests_controller.rb @@ -1,10 +1,10 @@ class TagImplicationRequestsController < ApplicationController before_filter :member_only rescue_from TagImplicationRequest::ValidationError, :with => :rescue_exception - + def new end - + def create @tag_implication_request = TagImplicationRequest.new( params[:tag_implication_request][:antecedent_name], diff --git a/app/controllers/tag_implications_controller.rb b/app/controllers/tag_implications_controller.rb index 134970435..e7576725e 100644 --- a/app/controllers/tag_implications_controller.rb +++ b/app/controllers/tag_implications_controller.rb @@ -1,29 +1,29 @@ class TagImplicationsController < ApplicationController before_filter :admin_only, :only => [:new, :create, :approve, :destroy] respond_to :html, :xml, :json, :js - + def new @tag_implication = TagImplication.new respond_with(@tag_implication) end - + def index @search = TagImplication.search(params[:search]) @tag_implications = @search.order("(case status when 'pending' then 0 when 'queued' then 1 else 2 end), antecedent_name, consequent_name").paginate(params[:page]) respond_with(@tag_implications) end - + def create @tag_implication = TagImplication.create(params[:tag_implication]) respond_with(@tag_implication, :location => tag_implications_path(:search => {:id => @tag_implication.id})) end - + def destroy @tag_implication = TagImplication.find(params[:id]) @tag_implication.destroy respond_with(@tag_implication) end - + def approve @tag_implication = TagImplication.find(params[:id]) @tag_implication.update_column(:status, "queued") diff --git a/app/controllers/tag_subscriptions_controller.rb b/app/controllers/tag_subscriptions_controller.rb index 425954b75..b1023451f 100644 --- a/app/controllers/tag_subscriptions_controller.rb +++ b/app/controllers/tag_subscriptions_controller.rb @@ -7,20 +7,20 @@ class TagSubscriptionsController < ApplicationController @tag_subscription = TagSubscription.new respond_with(@tag_subscription) end - + def edit @tag_subscription = TagSubscription.find(params[:id]) check_privilege(@tag_subscription) respond_with(@tag_subscription) end - + def index @user = CurrentUser.user @search = TagSubscription.owned_by(@user).order("name").search(params[:search]) @tag_subscriptions = @search.paginate(params[:page]) respond_with(@tag_subscriptions) end - + def create @tag_subscription = TagSubscription.create(params[:tag_subscription]) respond_with(@tag_subscription) do |format| @@ -33,7 +33,7 @@ class TagSubscriptionsController < ApplicationController end end end - + def update @tag_subscription = TagSubscription.find(params[:id]) check_privilege(@tag_subscription) @@ -48,20 +48,20 @@ class TagSubscriptionsController < ApplicationController end end end - + def destroy @tag_subscription = TagSubscription.find(params[:id]) check_privilege(@tag_subscription) @tag_subscription.destroy respond_with(@tag_subscription) end - + def posts @user = User.find(params[:id]) @post_set = PostSets::Post.new("sub:#{@user.name} #{params[:tags]}", params[:page]) @posts = @post_set.posts end - + private def check_privilege(tag_subscription) raise User::PrivilegeError unless tag_subscription.editable_by?(CurrentUser.user) diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 8d7f1be28..7a25bb83e 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -1,20 +1,20 @@ class TagsController < ApplicationController before_filter :member_only, :only => [:edit, :update] respond_to :html, :xml, :json - + def edit @tag = Tag.find(params[:id]) respond_with(@tag) end - + def index @tags = Tag.search(params[:search]).paginate(params[:page], :search_count => params[:search]) respond_with(@tags) end - + def search end - + def show @tag = Tag.find(params[:id]) respond_with(@tag) @@ -25,5 +25,5 @@ class TagsController < ApplicationController @tag.update_attributes(params[:tag]) @tag.update_category_cache_for_all respond_with(@tag) - end + end end diff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rb index 2f2ecf793..c9cff26fd 100644 --- a/app/controllers/uploads_controller.rb +++ b/app/controllers/uploads_controller.rb @@ -3,7 +3,7 @@ class UploadsController < ApplicationController after_filter :save_recent_tags, :only => [:create] respond_to :html, :xml, :json, :js rescue_from Upload::Error, :with => :rescue_exception - + def new @upload = Upload.new(:rating => "q") if params[:url] @@ -15,13 +15,13 @@ class UploadsController < ApplicationController end respond_with(@upload) end - + def index @search = Upload.search(params[:search]) @uploads = @search.order("id desc").paginate(params[:page]) respond_with(@uploads) end - + def show @upload = Upload.find(params[:id]) respond_with(@upload) do |format| @@ -38,7 +38,7 @@ class UploadsController < ApplicationController @upload.process! if @upload.errors.empty? respond_with(@upload) end - + def update @upload = Upload.find(params[:id]) @upload.process! diff --git a/app/controllers/user_feedbacks_controller.rb b/app/controllers/user_feedbacks_controller.rb index 97b129392..1056f16da 100644 --- a/app/controllers/user_feedbacks_controller.rb +++ b/app/controllers/user_feedbacks_controller.rb @@ -7,29 +7,29 @@ class UserFeedbacksController < ApplicationController @user_feedback = UserFeedback.new(params[:user_feedback]) respond_with(@user_feedback) end - + def edit @user_feedback = UserFeedback.find(params[:id]) check_privilege(@user_feedback) respond_with(@user_feedback) end - + def show @user_feedback = UserFeedback.find(params[:id]) respond_with(@user_feedback) end - + def index @search = UserFeedback.search(params[:search]) @user_feedbacks = @search.paginate(params[:page]).order("created_at desc") respond_with(@user_feedbacks) end - + def create @user_feedback = UserFeedback.create(params[:user_feedback]) respond_with(@user_feedback) end - + def destroy @user_feedback = UserFeedback.find(params[:id]) check_privilege(@user_feedback) diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 2a2eb0574..4a350eb3b 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -7,27 +7,27 @@ class UsersController < ApplicationController @user = User.new respond_with(@user) end - + def edit @user = User.find(params[:id]) check_privilege(@user) respond_with(@user) end - + def index @users = User.search(params[:search]).order("users.id desc").paginate(params[:page], :search_count => params[:search]) respond_with(@users) end - + def search end - + def show @user = User.find(params[:id]) @presenter = UserPresenter.new(@user) respond_with(@user) end - + def create @user = User.create(params[:user], :as => CurrentUser.role) if @user.errors.empty? @@ -36,32 +36,32 @@ class UsersController < ApplicationController set_current_user respond_with(@user) end - + def update @user = User.find(params[:id]) check_privilege(@user) @user.update_attributes(params[:user], :as => CurrentUser.role) respond_with(@user) end - + def upgrade @user = User.find(params[:id]) - + if params[:email] =~ /paypal/ UserMailer.upgrade_fail(params[:email]).deliver else UserMailer.upgrade(@user, params[:email]).deliver end - + redirect_to user_path(@user), :notice => "Email was sent" end - + def cache @user = User.find(params[:id]) @user.update_cache render :nothing => true end - + def restore_uploaded_tags @user = User.find(params[:id]) importer = UploadedTagsImporter.new(@user) diff --git a/app/controllers/wiki_page_versions_controller.rb b/app/controllers/wiki_page_versions_controller.rb index d53767c5c..ccc30524e 100644 --- a/app/controllers/wiki_page_versions_controller.rb +++ b/app/controllers/wiki_page_versions_controller.rb @@ -1,16 +1,16 @@ class WikiPageVersionsController < ApplicationController respond_to :json, :html, :xml - + def index @wiki_page_versions = WikiPageVersion.search(params[:search]).order("id desc").paginate(params[:page], :search_count => params[:search]) respond_with(@wiki_page_versions) end - + def show @wiki_page_version = WikiPageVersion.find(params[:id]) respond_with(@wiki_page_version) end - + def diff @thispage = WikiPageVersion.find(params[:thispage]) @otherpage = WikiPageVersion.find(params[:otherpage]) diff --git a/app/controllers/wiki_pages_controller.rb b/app/controllers/wiki_pages_controller.rb index cf692fdd6..8a2653087 100644 --- a/app/controllers/wiki_pages_controller.rb +++ b/app/controllers/wiki_pages_controller.rb @@ -9,12 +9,12 @@ class WikiPagesController < ApplicationController @wiki_page = WikiPage.new(params[:wiki_page]) respond_with(@wiki_page) end - + def edit @wiki_page = WikiPage.find(params[:id]) respond_with(@wiki_page) end - + def index @wiki_pages = WikiPage.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) respond_with(@wiki_pages) do |format| @@ -25,7 +25,7 @@ class WikiPagesController < ApplicationController end end end - + def show if params[:id] =~ /[a-zA-Z]/ @wiki_page = WikiPage.find_by_title(params[:id]) @@ -34,31 +34,31 @@ class WikiPagesController < ApplicationController end respond_with(@wiki_page) end - + def create @wiki_page = WikiPage.create(params[:wiki_page]) respond_with(@wiki_page) end - + def update @wiki_page = WikiPage.find(params[:id]) @wiki_page.update_attributes(params[:wiki_page]) respond_with(@wiki_page) end - + def destroy @wiki_page = WikiPage.find(params[:id]) @wiki_page.destroy respond_with(@wiki_page) end - + def revert @wiki_page = WikiPage.find(params[:id]) @version = WikiPageVersion.find(params[:version_id]) @wiki_page.revert_to!(@version) respond_with(@wiki_page) end - + def show_or_new @wiki_page = WikiPage.find_by_title(params[:title]) if @wiki_page diff --git a/app/helpers/advertisements_helper.rb b/app/helpers/advertisements_helper.rb index 8047fd686..1904c8214 100644 --- a/app/helpers/advertisements_helper.rb +++ b/app/helpers/advertisements_helper.rb @@ -4,14 +4,14 @@ module AdvertisementsHelper @advertisement = Advertisement.find(:first, :conditions => ["ad_type = ? AND status = 'active'", ad_type], :order => "random()") if @advertisement content_tag( - "div", + "div", link_to( image_tag( - @advertisement.image_url, - :alt => "Advertisement", - :width => @advertisement.width, + @advertisement.image_url, + :alt => "Advertisement", + :width => @advertisement.width, :height => @advertisement.height - ), + ), advertisement_hits_path(:advertisement_id => @advertisement.id), :method => :post ), @@ -22,7 +22,7 @@ module AdvertisementsHelper "" end end - + def render_rss_advertisement(short_or_long, safe) if Danbooru.config.can_see_ads?(CurrentUser.user) if safe diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 7aa494cf3..6a0330f64 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -8,27 +8,27 @@ module ApplicationHelper content_tag("li", link_to(text, url, options), :class => klass) end - + def fast_link_to(text, link_params, options = {}) if options - attributes = options.map do |k, v| + attributes = options.map do |k, v| %{#{k}="#{h(v)}"} end.join(" ") else attributes = "" end - + if link_params.is_a?(Hash) action = link_params.delete(:action) controller = link_params.delete(:controller) || controller_name id = link_params.delete(:id) - + link_params = link_params.map {|k, v| "#{k}=#{u(v)}"}.join("&") - + if link_params.present? link_params = "?#{link_params}" end - + if id url = "/#{controller}/#{action}/#{id}#{link_params}" else @@ -37,43 +37,43 @@ module ApplicationHelper else url = link_params end - + raw %{#{text}} end - + def format_text(text, options = {}) DText.parse(text) end def error_messages_for(instance_name) instance = instance_variable_get("@#{instance_name}") - + if instance && instance.errors.any? %{
}.html_safe else "" end end - + def time_tag(content, time) zone = time.strftime("%z") datetime = time.strftime("%Y-%m-%dT%H:%M" + zone[0, 3] + ":" + zone[3, 2]) - + content_tag(:time, content || datetime, :datetime => datetime, :title => time.to_formatted_s) end - + def time_ago_in_words_tagged(time) raw time_tag(time_ago_in_words(time) + " ago", time) end - + def compact_time(time) time_tag(time.strftime("%Y-%m-%d %H:%M"), time) end - + def mod_link_to_user(user, positive_or_negative) html = "" html << link_to(user.name, user_path(user)) - + if positive_or_negative == :positive html << " [" + link_to("+", new_user_feedback_path(:user_feedback => {:category => "positive", :user_id => user.id})) + "]" @@ -83,26 +83,26 @@ module ApplicationHelper else html << " [" + link_to("–".html_safe, new_user_feedback_path(:user_feedback => {:category => "negative", :user_id => user.id})) + "]" end - + html.html_safe end - + def dtext_field(object, name, options = {}) options[:name] ||= "Body" options[:input_id] ||= "#{object}_#{name}" options[:input_name] ||= "#{object}[#{name}]" options[:value] ||= instance_variable_get("@#{object}").try(name) options[:preview_id] ||= "dtext-preview" - + render "dtext/form", options end - + def dtext_preview_button(object, name, options = {}) options[:input_id] ||= "#{object}_#{name}" options[:preview_id] ||= "dtext-preview" submit_tag("Preview", "data-input-id" => options[:input_id], "data-preview-id" => options[:preview_id]) end - + def search_field(method, options = {}) name = options[:label] || method.titleize string = '" end - + when "[/quote]" if options[:inline] "" @@ -166,7 +166,7 @@ class DText when /\[spoilers?\](?!\])/ stack << "div" '' - + when /\[\/spoilers?\]/ if stack.last == "div" stack.pop @@ -177,7 +177,7 @@ class DText '' + parse_inline(block) + "
" end end - + stack.reverse.each do |tag| if tag == "blockquote" html << "" @@ -188,10 +188,10 @@ class DText sanitize(html.join("")).html_safe end - + def self.sanitize(text) text.gsub!(/<( |-|\Z)/, "<\\1") - + Sanitize.clean( text, :elements => %w(code center tn h1 h2 h3 h4 h5 h6 a span div blockquote br p ul li ol em strong small big b i font u s), diff --git a/app/logical/downloads/file.rb b/app/logical/downloads/file.rb index 85bdd529b..6498ba650 100644 --- a/app/logical/downloads/file.rb +++ b/app/logical/downloads/file.rb @@ -1,14 +1,14 @@ module Downloads class File class Error < Exception ; end - + attr_accessor :source, :content_type, :file_path - + def initialize(source, file_path) @source = source @file_path = file_path end - + def download! http_get_streaming do |response| self.content_type = response["Content-Type"] @@ -18,23 +18,23 @@ module Downloads end after_download end - + def before_download(url, headers) Strategies::Base.strategies.each do |strategy| url, headers = strategy.new.rewrite(url, headers) end - + return [url, headers] end - + def after_download fix_image_board_sources end - + def url URI.parse(source) end - + def http_get_streaming(options = {}) max_size = options[:max_size] || Danbooru.config.max_file_size max_size = nil if max_size == 0 # unlimited @@ -49,7 +49,7 @@ module Downloads "User-Agent" => "#{Danbooru.config.safe_app_name}/#{Danbooru.config.version}" } @source, headers = before_download(source, headers) - + Net::HTTP.start(url.host, url.port, :use_ssl => url.is_a?(URI::HTTPS)) do |http| http.read_timeout = 10 http.request_get(url.request_uri, headers) do |res| @@ -76,7 +76,7 @@ module Downloads end # http.start end # while end # def - + def fix_image_board_sources if source =~ /\/src\/\d{12,}|urnc\.yi\.org|yui\.cynthia\.bne\.jp/ @source = "Image board" diff --git a/app/logical/downloads/strategies/base.rb b/app/logical/downloads/strategies/base.rb index 177ccaf95..cddee48ee 100644 --- a/app/logical/downloads/strategies/base.rb +++ b/app/logical/downloads/strategies/base.rb @@ -4,7 +4,7 @@ module Downloads def self.strategies [Pixiv] end - + def rewrite(url, headers) return [url, headers] end diff --git a/app/logical/downloads/strategies/pixiv.rb b/app/logical/downloads/strategies/pixiv.rb index dfce088fa..2cf37dec9 100644 --- a/app/logical/downloads/strategies/pixiv.rb +++ b/app/logical/downloads/strategies/pixiv.rb @@ -8,16 +8,16 @@ module Downloads url, headers = rewrite_small_images(url, headers) url, headers = rewrite_small_manga_pages(url, headers) end - + return [url, headers] end - + protected def rewrite_headers(url, headers) headers["Referer"] = "http://www.pixiv.net" return [url, headers] end - + def rewrite_html_pages(url, headers) # example: http://www.pixiv.net/member_illust.php?mode=big&illust_id=23828655 @@ -29,16 +29,16 @@ module Downloads return [url, headers] end end - + def rewrite_small_images(url, headers) if url =~ %r!(/img/.+?/.+?)_m.+$! match = $1 url.sub!(match + "_m", match) end - + return [url, headers] end - + def rewrite_small_manga_pages(url, headers) if url =~ %r!(\d+_p\d+)\.! match = $1 @@ -48,7 +48,7 @@ module Downloads url = big_url end end - + return [url, headers] end diff --git a/app/logical/janitor_trial_tester.rb b/app/logical/janitor_trial_tester.rb index f2254a5be..37b402790 100644 --- a/app/logical/janitor_trial_tester.rb +++ b/app/logical/janitor_trial_tester.rb @@ -1,10 +1,10 @@ class JanitorTrialTester attr_reader :user - + def initialize(user_name) @user = User.find_by_name(user_name) end - + def test if user.nil? "User not found" diff --git a/app/logical/moderator/dashboard/queries/artist.rb b/app/logical/moderator/dashboard/queries/artist.rb index 48968e793..842f00716 100644 --- a/app/logical/moderator/dashboard/queries/artist.rb +++ b/app/logical/moderator/dashboard/queries/artist.rb @@ -7,16 +7,16 @@ module Moderator def self.all(min_date, max_level) sql = <<-EOS SELECT artist_versions.updater_id AS updater_id, count(*) - FROM artist_versions - JOIN users ON users.id = artist_versions.updater_id - WHERE - artist_versions.created_at > ? - AND users.level <= ? - GROUP BY artist_versions.updater_id - ORDER BY count(*) DESC + FROM artist_versions + JOIN users ON users.id = artist_versions.updater_id + WHERE + artist_versions.created_at > ? + AND users.level <= ? + GROUP BY artist_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end diff --git a/app/logical/moderator/dashboard/queries/comment.rb b/app/logical/moderator/dashboard/queries/comment.rb index 3e09075ba..b86d189f0 100644 --- a/app/logical/moderator/dashboard/queries/comment.rb +++ b/app/logical/moderator/dashboard/queries/comment.rb @@ -6,20 +6,20 @@ module Moderator def self.all(min_date, max_level) sql = <<-EOS - SELECT comment_votes.comment_id, count(*) - FROM comment_votes - JOIN comments ON comments.id = comment_id - JOIN users ON users.id = comments.creator_id - WHERE - comment_votes.created_at > ? - AND comments.score < 0 - AND users.level <= ? - GROUP BY comment_votes.comment_id + SELECT comment_votes.comment_id, count(*) + FROM comment_votes + JOIN comments ON comments.id = comment_id + JOIN users ON users.id = comments.creator_id + WHERE + comment_votes.created_at > ? + AND comments.score < 0 + AND users.level <= ? + GROUP BY comment_votes.comment_id HAVING count(*) >= 3 - ORDER BY count(*) DESC + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end diff --git a/app/logical/moderator/dashboard/queries/note.rb b/app/logical/moderator/dashboard/queries/note.rb index 59b1825e8..3e58257f1 100644 --- a/app/logical/moderator/dashboard/queries/note.rb +++ b/app/logical/moderator/dashboard/queries/note.rb @@ -3,23 +3,23 @@ module Moderator module Queries class Note attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - SELECT note_versions.updater_id, count(*) - FROM note_versions - JOIN users ON users.id = note_versions.updater_id - WHERE - note_versions.created_at > ? - AND users.level <= ? - GROUP BY note_versions.updater_id - ORDER BY count(*) DESC + SELECT note_versions.updater_id, count(*) + FROM note_versions + JOIN users ON users.id = note_versions.updater_id + WHERE + note_versions.created_at > ? + AND users.level <= ? + GROUP BY note_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end - + def initialize(hash) @user = ::User.find(hash["updater_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/post_appeal.rb b/app/logical/moderator/dashboard/queries/post_appeal.rb index 0a0b9ca9a..c84ed0d9c 100644 --- a/app/logical/moderator/dashboard/queries/post_appeal.rb +++ b/app/logical/moderator/dashboard/queries/post_appeal.rb @@ -10,14 +10,14 @@ module Moderator FROM post_appeals JOIN posts ON posts.id = post_appeals.post_id WHERE - post_appeals.created_at > ? + post_appeals.created_at > ? and posts.is_deleted = true and posts.is_pending = false GROUP BY post_appeals.post_id ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date).map {|x| new(x)} end diff --git a/app/logical/moderator/dashboard/queries/post_flag.rb b/app/logical/moderator/dashboard/queries/post_flag.rb index 3334f4989..9bc1152e0 100644 --- a/app/logical/moderator/dashboard/queries/post_flag.rb +++ b/app/logical/moderator/dashboard/queries/post_flag.rb @@ -6,22 +6,22 @@ module Moderator def self.all(min_date) sql = <<-EOS - SELECT post_flags.post_id, count(*) - FROM post_flags - JOIN posts ON posts.id = post_flags.post_id - WHERE - post_flags.created_at > ? - AND post_flags.reason <> ? + SELECT post_flags.post_id, count(*) + FROM post_flags + JOIN posts ON posts.id = post_flags.post_id + WHERE + post_flags.created_at > ? + AND post_flags.reason <> ? AND posts.is_deleted = false and posts.is_pending = false - GROUP BY post_flags.post_id - ORDER BY count(*) DESC + GROUP BY post_flags.post_id + ORDER BY count(*) DESC LIMIT 10 EOS ActiveRecord::Base.select_all_sql(sql, min_date, "Unapproved in three days").map {|x| new(x)} end - + def initialize(hash) @post = Post.find(hash["post_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/tag.rb b/app/logical/moderator/dashboard/queries/tag.rb index de056c7a9..a3411bbdb 100644 --- a/app/logical/moderator/dashboard/queries/tag.rb +++ b/app/logical/moderator/dashboard/queries/tag.rb @@ -3,25 +3,25 @@ module Moderator module Queries class Tag attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - SELECT post_versions.updater_id, count(*) - FROM post_versions - JOIN users ON users.id = post_versions.updater_id - WHERE - post_versions.updated_at > ? - AND users.level <= ? - GROUP BY post_versions.updater_id - ORDER BY count(*) DESC + SELECT post_versions.updater_id, count(*) + FROM post_versions + JOIN users ON users.id = post_versions.updater_id + WHERE + post_versions.updated_at > ? + AND users.level <= ? + GROUP BY post_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.without_timeout do ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end end - + def initialize(hash) @user = ::User.find(hash["updater_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/upload.rb b/app/logical/moderator/dashboard/queries/upload.rb index b6a3206ce..588ff4169 100644 --- a/app/logical/moderator/dashboard/queries/upload.rb +++ b/app/logical/moderator/dashboard/queries/upload.rb @@ -3,23 +3,23 @@ module Moderator module Queries class Upload attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - select uploader_id, count(*) - from posts - join users on uploader_id = users.id - where - posts.created_at > ? - and level <= ? - group by posts.uploader_id - order by count(*) desc + select uploader_id, count(*) + from posts + join users on uploader_id = users.id + where + posts.created_at > ? + and level <= ? + group by posts.uploader_id + order by count(*) desc limit 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end - + def initialize(hash) @user = ::User.find(hash["uploader_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/wiki_page.rb b/app/logical/moderator/dashboard/queries/wiki_page.rb index 016e566f6..9b4c15f36 100644 --- a/app/logical/moderator/dashboard/queries/wiki_page.rb +++ b/app/logical/moderator/dashboard/queries/wiki_page.rb @@ -3,23 +3,23 @@ module Moderator module Queries class WikiPage attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - SELECT wiki_page_versions.updater_id, count(*) - FROM wiki_page_versions - JOIN users ON users.id = wiki_page_versions.updater_id - WHERE - wiki_page_versions.created_at > ? - AND users.level <= ? - GROUP BY wiki_page_versions.updater_id - ORDER BY count(*) DESC + SELECT wiki_page_versions.updater_id, count(*) + FROM wiki_page_versions + JOIN users ON users.id = wiki_page_versions.updater_id + WHERE + wiki_page_versions.created_at > ? + AND users.level <= ? + GROUP BY wiki_page_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end - + def initialize(hash) @user = ::User.find(hash["updater_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/report.rb b/app/logical/moderator/dashboard/report.rb index a24ca5000..3694988f9 100644 --- a/app/logical/moderator/dashboard/report.rb +++ b/app/logical/moderator/dashboard/report.rb @@ -2,18 +2,18 @@ module Moderator module Dashboard class Report attr_reader :min_date, :max_level - + def initialize(min_date, max_level) @min_date = min_date.present? ? min_date.to_date : 1.week.ago @max_level = max_level.present? ? User::Levels::MEMBER : max_level.to_i end - + def artists ActiveRecord::Base.without_timeout do Queries::Artist.all(min_date, max_level) end end - + def comments ActiveRecord::Base.without_timeout do Queries::Comment.all(min_date, max_level) @@ -55,7 +55,7 @@ module Moderator Queries::Upload.all(min_date, max_level) end end - + def user_feedbacks ActiveRecord::Base.without_timeout do Queries::UserFeedback.all diff --git a/app/logical/moderator/ip_addr_search.rb b/app/logical/moderator/ip_addr_search.rb index b5b10dcca..95c7a9bbd 100644 --- a/app/logical/moderator/ip_addr_search.rb +++ b/app/logical/moderator/ip_addr_search.rb @@ -1,12 +1,12 @@ module Moderator class IpAddrSearch attr_reader :params, :errors - + def initialize(params) @params = params @errors = [] end - + def execute if params[:user_id].present? search_by_user_id(params[:user_id].split(/,/)) @@ -18,41 +18,41 @@ module Moderator [] end end - + private def select_all_sql(sql, *params) ActiveRecord::Base.select_all_sql(sql, *params) end - + def search_by_ip_addr(ip_addrs) sums = Hash.new {|h, k| h[k] = 0} - + add_row(sums, "select creator_id as k, count(*) from comments where ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from post_versions where updater_ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from note_versions where updater_ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from pool_versions where updater_ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from wiki_page_versions where updater_ip_addr in (?) group by k", ip_addrs) - + sums end - + def search_by_user_name(user_names) users = User.where("name in (?)", user_names) search_by_user_id(users.map(&:id)) end - + def search_by_user_id(user_ids) sums = Hash.new {|h, k| h[k] = 0} - + add_row(sums, "select ip_addr as k, count(*) from comments where creator_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from post_versions where updater_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from note_versions where updater_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from pool_versions where updater_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from wiki_page_versions where updater_id in (?) group by k", user_ids) - + sums end - + def add_row(sums, sql, ip_addrs) select_all_sql(sql, ip_addrs).each do |row| sums[row["k"]] += row["count"].to_i diff --git a/app/logical/moderator/tag_batch_change.rb b/app/logical/moderator/tag_batch_change.rb index 08453060e..1b1ab2bdb 100644 --- a/app/logical/moderator/tag_batch_change.rb +++ b/app/logical/moderator/tag_batch_change.rb @@ -1,15 +1,15 @@ module Moderator class TagBatchChange < Struct.new(:antecedent, :consequent, :updater_id, :updater_ip_addr) class Error < Exception ; end - + def perform raise Error.new("antecedent is missing") if antecedent.blank? - + normalized_antecedent = TagAlias.to_aliased(::Tag.scan_tags(antecedent)) normalized_consequent = TagAlias.to_aliased(::Tag.scan_tags(consequent)) - + updater = User.find(updater_id) - + CurrentUser.scoped(updater, updater_ip_addr) do ::Post.tag_match(antecedent).each do |post| tags = (post.tag_array - normalized_antecedent + normalized_consequent).join(" ") diff --git a/app/logical/post_pruner.rb b/app/logical/post_pruner.rb index 3932da151..652da1b7c 100644 --- a/app/logical/post_pruner.rb +++ b/app/logical/post_pruner.rb @@ -1,16 +1,16 @@ class PostPruner attr_reader :admin - + def initialize @admin = User.where(:level => User::Levels::ADMIN).first end - + def prune! prune_pending! prune_flagged! prune_mod_actions! end - + protected def prune_pending! @@ -25,7 +25,7 @@ protected end end end - + def prune_flagged! CurrentUser.scoped(admin, "127.0.0.1") do Post.where("is_deleted = ? and is_flagged = ?", false, true).each do |post| @@ -40,7 +40,7 @@ protected end end end - + def prune_mod_actions! ModAction.destroy_all(["creator_id = ? and description like ?", admin.id, "deleted post %"]) end diff --git a/app/logical/post_query_builder.rb b/app/logical/post_query_builder.rb index 5d9055f52..1fee842e0 100644 --- a/app/logical/post_query_builder.rb +++ b/app/logical/post_query_builder.rb @@ -1,24 +1,24 @@ class PostQueryBuilder attr_accessor :query_string, :has_constraints - + def initialize(query_string) @query_string = query_string @has_constraint = false end - + def has_constraints? @has_constraints end - + def has_constraints! @has_constraints = true end - + def add_range_relation(arr, field, relation) return relation if arr.nil? - + has_constraints! - + case arr[0] when :eq if arr[1].is_a?(Time) @@ -38,7 +38,7 @@ class PostQueryBuilder when :lte relation.where(["#{field} <= ?", arr[1]]) - + when :in relation.where(["#{field} in (?)", arr[1]]) @@ -76,10 +76,10 @@ class PostQueryBuilder if tag_query_sql.any? relation = relation.where("posts.tag_index @@ to_tsquery('danbooru', E?)", tag_query_sql.join(" & ")) end - + relation end - + def add_tag_subscription_relation(subscriptions, relation) subscriptions.each do |subscription| if subscription =~ /^(.+?):(.+)$/ @@ -93,25 +93,25 @@ class PostQueryBuilder return relation if user.nil? post_ids = TagSubscription.find_post_ids(user.id) end - + post_ids = [0] if post_ids.empty? relation = relation.where(["posts.id IN (?)", post_ids]) end - + relation end - + def build unless query_string.is_a?(Hash) q = Tag.parse_query(query_string) end - + relation = Post.scoped - + if q[:tag_count].to_i > Danbooru.config.tag_query_limit raise ::Post::SearchError.new("You cannot search for more than #{Danbooru.config.tag_query_limit} tags at a time") end - + relation = add_range_relation(q[:post_id], "posts.id", relation) relation = add_range_relation(q[:mpixels], "posts.image_width * posts.image_height / 1000000.0", relation) relation = add_range_relation(q[:width], "posts.image_width", relation) @@ -125,12 +125,12 @@ class PostQueryBuilder relation = add_range_relation(q[:character_tag_count], "posts.tag_count_character", relation) relation = add_range_relation(q[:post_tag_count], "posts.tag_count", relation) relation = add_range_relation(q[:pixiv], "substring(posts.source, 'pixiv.net/img.*/([0-9]+)[^/]*$')::integer", relation) - + if q[:md5] relation = relation.where(["posts.md5 IN (?)", q[:md5]]) has_constraints! end - + if q[:status] == "pending" relation = relation.where("posts.is_pending = TRUE") elsif q[:status] == "flagged" @@ -167,26 +167,26 @@ class PostQueryBuilder if q[:uploader_id_neg] relation = relation.where("posts.uploader_id not in (?)", q[:uploader_id_neg]) end - + if q[:uploader_id] relation = relation.where("posts.uploader_id = ?", q[:uploader_id]) has_constraints! end - + if q[:approver_id_neg] relation = relation.where("posts.approver_id not in (?)", q[:approver_id_neg]) end - + if q[:approver_id] relation = relation.where("posts.approver_id = ?", q[:approver_id]) has_constraints! end - + if q[:parent_id] relation = relation.where("(posts.id = ? or posts.parent_id = ?)", q[:parent_id], q[:parent_id]) has_constraints! end - + if q[:rating] =~ /^q/ relation = relation.where("posts.rating = 'q'") elsif q[:rating] =~ /^s/ @@ -202,13 +202,13 @@ class PostQueryBuilder elsif q[:rating_negated] =~ /^e/ relation = relation.where("posts.rating <> 'e'") end - + relation = add_tag_string_search_relation(q[:tags], relation) - + if q[:order] == "rank" relation = relation.where("posts.score > 0 and posts.created_at >= ?", 2.days.ago) end - + case q[:order] when "id", "id_asc" relation = relation.order("posts.id ASC") @@ -221,10 +221,10 @@ class PostQueryBuilder when "score_asc" relation = relation.order("posts.score ASC, posts.id DESC") - + when "favcount" relation = relation.order("posts.fav_count DESC, posts.id DESC") - + when "favcount_asc" relation = relation.order("posts.fav_count ASC, posts.id DESC") diff --git a/app/logical/post_search_context.rb b/app/logical/post_search_context.rb index db3b5b38a..67ddde396 100644 --- a/app/logical/post_search_context.rb +++ b/app/logical/post_search_context.rb @@ -1,14 +1,14 @@ class PostSearchContext attr_reader :params, :post_id - + def initialize(params) @params = params raise unless params[:seq].present? raise unless params[:id].present? - + @post_id = find_post_id end - + def find_post_id if params[:seq] == "prev" post = Post.tag_match(params[:tags]).where("posts.id > ?", params[:id].to_i).reorder("posts.id asc").first diff --git a/app/logical/post_sets/artist.rb b/app/logical/post_sets/artist.rb index b04809268..1fb619498 100644 --- a/app/logical/post_sets/artist.rb +++ b/app/logical/post_sets/artist.rb @@ -1,12 +1,12 @@ module PostSets class Artist < PostSets::Post attr_reader :artist - + def initialize(artist) super(artist.name) @artist = artist end - + def posts ::Post.tag_match(@artist.name).limit(10) rescue ::Post::SearchError diff --git a/app/logical/post_sets/base.rb b/app/logical/post_sets/base.rb index dcd62826e..6dd73cbcb 100644 --- a/app/logical/post_sets/base.rb +++ b/app/logical/post_sets/base.rb @@ -3,38 +3,38 @@ module PostSets def has_wiki? false end - + def wiki_page nil end - + def has_artist? false end - + def artist nil end - + def is_single_tag? false end - + def presenter raise NotImplementedError end - + def arbitrary_sql_order_clause(ids, table_name) if ids.empty? return "#{table_name}.id desc" end - + conditions = [] - + ids.each_with_index do |x, n| conditions << "when #{x} then #{n}" end - + "case #{table_name}.id " + conditions.join(" ") + " end" end end diff --git a/app/logical/post_sets/favorite.rb b/app/logical/post_sets/favorite.rb index 73efc90bb..f932a4977 100644 --- a/app/logical/post_sets/favorite.rb +++ b/app/logical/post_sets/favorite.rb @@ -1,28 +1,28 @@ module PostSets class Favorite < Base attr_reader :user, :page, :favorites - + def initialize(user_id, page = 1) @user = ::User.find(user_id) @favorites = ::Favorite.for_user(user.id).paginate(page).order("favorites.id desc") end - + def tag_array @tag_array ||= ["fav:#{user.name}"] end - + def tag_string tag_array.uniq.join(" ") end - + def humanized_tag_string "fav:#{user.pretty_name}" end - + def posts favorites.includes(:post).map(&:post) end - + def presenter @presenter ||= ::PostSetPresenters::Favorite.new(self) end diff --git a/app/logical/post_sets/pool.rb b/app/logical/post_sets/pool.rb index b34ae1ade..e80670fa5 100644 --- a/app/logical/post_sets/pool.rb +++ b/app/logical/post_sets/pool.rb @@ -3,26 +3,26 @@ module PostSets module ActiveRecordExtension attr_accessor :total_pages, :current_page end - + attr_reader :pool, :page - + def initialize(pool, page = 1) @pool = pool @page = page end - + def offset (current_page - 1) * limit end - + def limit Danbooru.config.posts_per_page end - + def tag_array ["pool:#{pool.id}"] end - + def posts @posts ||= begin x = pool.posts(:offset => offset, :limit => limit) @@ -32,27 +32,27 @@ module PostSets x end end - + def tag_string tag_array.join("") end - + def humanized_tag_string "pool:#{pool.pretty_name}" end - + def presenter @presenter ||= PostSetPresenters::Pool.new(self) end - + def total_pages (pool.post_count.to_f / limit).ceil end - + def size posts.size end - + def current_page [page.to_i, 1].max end diff --git a/app/logical/post_sets/popular.rb b/app/logical/post_sets/popular.rb index 99e4dd956..0950abf6b 100644 --- a/app/logical/post_sets/popular.rb +++ b/app/logical/post_sets/popular.rb @@ -1,41 +1,41 @@ module PostSets class Popular < Base attr_reader :date, :scale - + def initialize(date, scale) @date = date.blank? ? Time.zone.now : Time.zone.parse(date) @scale = scale end - + def posts ::Post.where("created_at between ? and ?", min_date.beginning_of_day, max_date.end_of_day).order("score desc").limit(limit) end - + def limit 25 end - + def min_date case scale when "week" date.beginning_of_week - + when "month" date.beginning_of_month - + else date end end - + def max_date case scale when "week" date.end_of_week - + when "month" date.end_of_month - + else date end diff --git a/app/logical/post_sets/post.rb b/app/logical/post_sets/post.rb index ef97af9ed..c535f2871 100644 --- a/app/logical/post_sets/post.rb +++ b/app/logical/post_sets/post.rb @@ -1,22 +1,22 @@ module PostSets class Post < Base attr_reader :tag_array, :page, :per_page - + def initialize(tags, page = 1, per_page = nil) @tag_array = Tag.scan_query(tags) @page = page @per_page = (per_page || Danbooru.config.posts_per_page).to_i @per_page = 200 if @per_page > 200 end - + def tag_string @tag_string ||= tag_array.uniq.join(" ") end - + def humanized_tag_string tag_array.slice(0, 25).join(" ").tr("_", " ") end - + def has_wiki? tag_array.size == 1 && ::WikiPage.titled(tag_string).exists? end @@ -28,15 +28,15 @@ module PostSets nil end end - + def has_deleted? CurrentUser.is_privileged? && tag_string !~ /status/ && ::Post.tag_match("#{tag_string} status:deleted").exists? end - + def has_explicit? posts.any? {|x| x.rating == "e"} end - + def posts if tag_array.size > 2 && !CurrentUser.is_privileged? raise SearchError.new("Upgrade your account to search more than two tags at once") @@ -45,50 +45,50 @@ module PostSets if tag_array.any? {|x| x =~ /^source:.*\*.*pixiv/} && !CurrentUser.user.is_builder? raise SearchError.new("Your search took too long to execute and was canceled") end - + @posts ||= begin temp = ::Post.tag_match(tag_string).paginate(page, :count => ::Post.fast_count(tag_string), :limit => per_page) temp.all temp end end - + def has_artist? tag_array.any? && ::Artist.name_equals(tag_string).exists? end - + def artist ::Artist.name_matches(tag_string).first end - + def is_single_tag? tag_array.size == 1 end - + def is_empty_tag? tag_array.size == 0 end - + def is_pattern_search? tag_string =~ /\*/ end - + def current_page [page.to_i, 1].max end - + def is_tag_subscription? tag_subscription.present? end - + def tag_subscription @tag_subscription ||= tag_array.select {|x| x =~ /^sub:/}.map {|x| x.sub(/^sub:/, "")}.first end - + def tag_subscription_tags @tag_subscription_tags ||= TagSubscription.find_tags(tag_subscription) end - + def presenter @presenter ||= ::PostSetPresenters::Post.new(self) end diff --git a/app/logical/post_sets/wiki_page.rb b/app/logical/post_sets/wiki_page.rb index 81ac2bd81..2c83d5c2c 100644 --- a/app/logical/post_sets/wiki_page.rb +++ b/app/logical/post_sets/wiki_page.rb @@ -1,7 +1,7 @@ module PostSets class SearchError < Exception end - + class WikiPage < Post def presenter @presenter ||= ::PostSetPresenters::WikiPage.new(self) diff --git a/app/logical/related_tag_calculator.rb b/app/logical/related_tag_calculator.rb index 4e1543b94..a780aeb71 100644 --- a/app/logical/related_tag_calculator.rb +++ b/app/logical/related_tag_calculator.rb @@ -2,25 +2,25 @@ class RelatedTagCalculator def self.find_tags(tag, limit) Post.tag_match(tag).limit(limit).select("posts.tag_string").reorder("posts.md5").map(&:tag_string) end - + def self.calculate_from_sample_to_array(tags, category_constraint = nil) convert_hash_to_array(calculate_from_sample(tags, Danbooru.config.post_sample_size, category_constraint)) end - + def self.calculate_from_sample(tags, limit, category_constraint = nil) counts = Hash.new {|h, k| h[k] = 0} - + case category_constraint when Tag.categories.artist limit *= 4 - + when Tag.categories.copyright limit *= 3 - + when Tag.categories.character limit *= 2 end - + find_tags(tags, limit).each do |tags| tag_array = Tag.scan_tags(tags) if category_constraint @@ -36,14 +36,14 @@ class RelatedTagCalculator end end end - + counts end - + def self.convert_hash_to_array(hash) hash.to_a.sort_by {|x| -x[1]}.slice(0, 25) end - + def self.convert_hash_to_string(hash) convert_hash_to_array(hash).flatten.join(" ") end diff --git a/app/logical/related_tag_query.rb b/app/logical/related_tag_query.rb index dab1c273f..e2eb55007 100644 --- a/app/logical/related_tag_query.rb +++ b/app/logical/related_tag_query.rb @@ -1,6 +1,6 @@ class RelatedTagQuery attr_reader :query, :category - + def initialize(query, category) @query = query.strip @category = category @@ -17,7 +17,7 @@ class RelatedTagQuery [] end end - + def wiki_page_tags results = wiki_page.try(:tags) || [] results.reject! do |name| @@ -25,31 +25,31 @@ class RelatedTagQuery end results end - + def to_json {:query => query, :category => category, :tags => map_with_category_data(tags), :wiki_page_tags => map_with_category_data(wiki_page_tags)}.to_json end - + protected - + def map_with_category_data(list_of_tag_names) Tag.categories_for(list_of_tag_names).to_a end - + def pattern_matching_tags Tag.name_matches(query).where("post_count > 0").order("post_count desc").limit(50).sort_by {|x| x.name}.map(&:name) end - + def related_tags tag = Tag.named(query.strip).first - + if tag tag.related_tag_array.map(&:first) else [] end end - + def related_tags_by_category RelatedTagCalculator.calculate_from_sample_to_array(query, Tag.categories.value_for(category)).map(&:first) end diff --git a/app/logical/remote_file_manager.rb b/app/logical/remote_file_manager.rb index beb2c7af5..e80e0ce68 100644 --- a/app/logical/remote_file_manager.rb +++ b/app/logical/remote_file_manager.rb @@ -1,10 +1,10 @@ class RemoteFileManager attr_reader :path - + def initialize(path) @path = path end - + def distribute Danbooru.config.other_server_hosts.each do |hostname| Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp| @@ -12,7 +12,7 @@ class RemoteFileManager end end end - + def delete Danbooru.config.other_server_hosts.each do |hostname| Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp| diff --git a/app/logical/session_creator.rb b/app/logical/session_creator.rb index d346ad31f..4230a6037 100644 --- a/app/logical/session_creator.rb +++ b/app/logical/session_creator.rb @@ -1,6 +1,6 @@ class SessionCreator attr_reader :session, :cookies, :name, :password, :remember - + def initialize(session, cookies, name, password, remember) @session = session @cookies = cookies @@ -8,17 +8,17 @@ class SessionCreator @password = password @remember = remember end - + def authenticate if User.authenticate(name, password) user = User.find_by_name(name) user.update_column(:last_logged_in_at, Time.now) - + if remember.present? cookies.permanent.signed[:user_name] = user.name cookies.permanent[:password_hash] = user.bcrypt_cookie_password_hash end - + session[:user_id] = user.id return true else diff --git a/app/logical/session_loader.rb b/app/logical/session_loader.rb index 1924e7dc8..e7c2ffa8c 100644 --- a/app/logical/session_loader.rb +++ b/app/logical/session_loader.rb @@ -1,55 +1,55 @@ class SessionLoader attr_reader :session, :cookies, :request - + def initialize(session, cookies, request) @session = session @cookies = cookies @request = request end - + def load if session[:user_id] load_session_user elsif cookie_password_hash_valid? load_cookie_user end - + if CurrentUser.user CurrentUser.user.unban! if ban_expired? else CurrentUser.user = AnonymousUser.new end - + update_last_logged_in_at set_time_zone end private - + def load_session_user CurrentUser.user = User.find_by_id(session[:user_id]) CurrentUser.ip_addr = request.remote_ip end - + def load_cookie_user CurrentUser.user = User.find_by_name(cookies.signed[:user_name]) CurrentUser.ip_addr = request.remote_ip end - + def ban_expired? CurrentUser.user.is_banned? && CurrentUser.user.ban && CurrentUser.user.ban.expired? end - + def cookie_password_hash_valid? cookies[:password_hash] && cookies.signed[:user_name] && User.authenticate_cookie_hash(cookies.signed[:user_name], cookies[:password_hash]) end - + def update_last_logged_in_at return if CurrentUser.is_anonymous? return if CurrentUser.last_logged_in_at && CurrentUser.last_logged_in_at > 1.week.ago CurrentUser.user.update_attribute(:last_logged_in_at, Time.now) end - + def set_time_zone Time.zone = CurrentUser.user.time_zone end diff --git a/app/logical/sources/site.rb b/app/logical/sources/site.rb index 4f8ff0776..4c14285d0 100644 --- a/app/logical/sources/site.rb +++ b/app/logical/sources/site.rb @@ -2,14 +2,14 @@ module Sources class Site attr_reader :url, :strategy delegate :get, :referer_url, :site_name, :artist_name, :profile_url, :image_url, :tags, :artist_record, :unique_id, :to => :strategy - + def self.strategies [Strategies::NicoSeiga, Strategies::Pixiv] end - + def initialize(url) @url = url - + Site.strategies.each do |strategy| if strategy.url_match?(url) @strategy = strategy.new(url) @@ -18,7 +18,7 @@ module Sources end end end - + def to_json return { :artist_name => artist_name, @@ -30,7 +30,7 @@ module Sources :unique_id => unique_id }.to_json end - + def available? strategy.present? end diff --git a/app/logical/sources/strategies/base.rb b/app/logical/sources/strategies/base.rb index cd73898ca..1df257e71 100644 --- a/app/logical/sources/strategies/base.rb +++ b/app/logical/sources/strategies/base.rb @@ -3,28 +3,28 @@ module Sources class Base attr_reader :url attr_reader :artist_name, :profile_url, :image_url, :tags - + def self.url_match?(url) false end - + def initialize(url) @url = url end - + # No remote calls are made until this method is called. def get raise NotImplementedError end - + def site_name raise NotImplementedError end - + def unique_id artist_name end - + def artist_record if artist_name.present? Artist.other_names_match(artist_name) @@ -32,11 +32,11 @@ module Sources nil end end - + def referer_url(template) template.params[:ref] || template.params[:url] end - + protected def agent raise NotImplementedError diff --git a/app/logical/sources/strategies/nico_seiga.rb b/app/logical/sources/strategies/nico_seiga.rb index e74c8e2a5..35f483559 100644 --- a/app/logical/sources/strategies/nico_seiga.rb +++ b/app/logical/sources/strategies/nico_seiga.rb @@ -8,7 +8,7 @@ module Sources def site_name "Nico Seiga" end - + def unique_id profile_url =~ /\/illust\/(\d+)/ "nicoseiga" + $1 @@ -21,9 +21,9 @@ module Sources @tags = get_tags_from_page(page) end end - + protected - + def get_profile_from_page(page) links = page.search("div.illust_user_name a") @@ -34,10 +34,10 @@ module Sources profile_url = nil artist_name = nil end - + return [artist_name, profile_url].compact end - + def get_image_url_from_page(page) links = page.search("a#illust_link") @@ -47,7 +47,7 @@ module Sources nil end end - + def get_tags_from_page(page) links = page.search("div#tag_block nobr a.tag") @@ -55,7 +55,7 @@ module Sources [node.text, "http://seiga.nicovideo.jp" + node.attr("href")] end end - + def agent @agent ||= begin mech = Mechanize.new diff --git a/app/logical/sources/strategies/pixiv.rb b/app/logical/sources/strategies/pixiv.rb index a7be61358..016e48ad6 100644 --- a/app/logical/sources/strategies/pixiv.rb +++ b/app/logical/sources/strategies/pixiv.rb @@ -4,7 +4,7 @@ module Sources def self.url_match?(url) url =~ /^https?:\/\/(?:\w+\.)?pixiv\.net/ end - + def referer_url(template) if template.params[:ref] =~ /pixiv\.net\/member_illust/ && template.params[:ref] !~ /mode=manga/ template.params[:ref] @@ -12,16 +12,16 @@ module Sources template.params[:url] end end - + def site_name "Pixiv" end - + def unique_id image_url =~ /\/img\/([^\/]+)/ $1 end - + def get agent.get(URI.parse(normalized_url).request_uri) do |page| @artist_name, @profile_url = get_profile_from_page(page) @@ -31,13 +31,13 @@ module Sources end protected - + def get_profile_from_page(page) profile_url = page.search("a.user-link").first if profile_url profile_url = "http://www.pixiv.net" + profile_url["href"] end - + artist_name = page.search("h1.user").first if artist_name artist_name = artist_name.inner_text @@ -45,7 +45,7 @@ module Sources return [artist_name, profile_url] end - + def get_image_url_from_page(page) element = page.search("div.works_display a img").first if element @@ -54,10 +54,10 @@ module Sources nil end end - + def get_tags_from_page(page) # puts page.root.to_xhtml - + links = page.search("ul.tags a.text").find_all do |node| node["href"] =~ /search\.php/ end @@ -70,7 +70,7 @@ module Sources [] end end - + def normalized_url @normalized_url ||= begin if url =~ /\/(\d+)(?:_big)?(?:_m|_p\d+)?\.(?:jpg|jpeg|png|gif)/i @@ -84,7 +84,7 @@ module Sources end end end - + def agent @agent ||= begin mech = Mechanize.new diff --git a/app/logical/tag_alias_correction.rb b/app/logical/tag_alias_correction.rb index f33b6b403..4afd1e39b 100644 --- a/app/logical/tag_alias_correction.rb +++ b/app/logical/tag_alias_correction.rb @@ -1,17 +1,17 @@ class TagAliasCorrection attr_reader :tag_alias_id, :tag_alias, :hostname delegate :antecedent_name, :consequent_name, :to => :tag_alias - + def initialize(tag_alias_id, hostname = Socket.gethostname) @tag_alias_id = tag_alias_id @tag_alias = TagAlias.find(tag_alias_id) @hostname = hostname end - + def to_json(options = {}) statistics_hash.to_json end - + def statistics_hash @statistics_hash ||= { "antecedent_cache" => Cache.get("ta:" + Cache.sanitize(tag_alias.antecedent_name)), @@ -20,7 +20,7 @@ class TagAliasCorrection "consequent_count" => Tag.find_by_name(tag_alias.consequent_name).try(:post_count) } end - + def fill_hash! Net::HTTP.start(hostname, 80) do |http| http.request_get("/tag_aliases/#{tag_alias_id}/correction.json") do |res| @@ -32,23 +32,23 @@ class TagAliasCorrection end end end - + def each_server Danbooru.config.all_server_hosts.each do |host| other = TagAliasCorrection.new(tag_alias_id, host) - + if host != Socket.gethostname other.fill_hash! end - + yield other end end - + def clear_cache tag_alias.clear_all_cache end - + def fix! clear_cache tag_alias.delay(:queue => "default").update_posts diff --git a/app/logical/tag_alias_request.rb b/app/logical/tag_alias_request.rb index 407901b82..b71a72efd 100644 --- a/app/logical/tag_alias_request.rb +++ b/app/logical/tag_alias_request.rb @@ -1,28 +1,28 @@ class TagAliasRequest class ValidationError < Exception ; end - + attr_reader :antecedent_name, :consequent_name, :reason, :tag_alias, :forum_topic - + def initialize(antecedent_name, consequent_name, reason) @antecedent_name = antecedent_name.tr(" ", "_") @consequent_name = consequent_name.tr(" ", "_") @reason = reason end - + def create TagAlias.transaction do create_alias create_forum_topic end end - + def create_alias @tag_alias = TagAlias.create(:antecedent_name => antecedent_name, :consequent_name => consequent_name, :status => "pending") if @tag_alias.errors.any? raise ValidationError.new(@tag_alias.errors.full_messages.join("; ")) end end - + def create_forum_topic @forum_topic = ForumTopic.create( :title => "Tag alias: #{antecedent_name} -> #{consequent_name}", @@ -33,7 +33,7 @@ class TagAliasRequest if @forum_topic.errors.any? raise ValidationError.new(@forum_topic.errors.full_messages.join("; ")) end - + tag_alias.update_attribute(:forum_topic_id, @forum_topic.id) end end diff --git a/app/logical/tag_correction.rb b/app/logical/tag_correction.rb index 834f625d6..8bd56fd09 100644 --- a/app/logical/tag_correction.rb +++ b/app/logical/tag_correction.rb @@ -1,23 +1,23 @@ class TagCorrection attr_reader :tag_id, :tag, :hostname - + def initialize(tag_id, hostname = Socket.gethostname) @tag_id = tag_id @tag = Tag.find(tag_id) @hostname = hostname end - + def to_json(options = {}) statistics_hash.to_json end - + def statistics_hash @statistics_hash ||= { "category_cache" => Cache.get("tc:" + Cache.sanitize(tag.name)), "post_fast_count_cache" => Cache.get("pfc:" + Cache.sanitize(tag.name)) } end - + def fill_hash! Net::HTTP.start(hostname, 80) do |http| http.request_get("/tags/#{tag_id}/correction.json") do |res| @@ -29,19 +29,19 @@ class TagCorrection end end end - + def each_server Danbooru.config.all_server_hosts.each do |host| other = TagCorrection.new(tag_id, host) - + if host != Socket.gethostname other.fill_hash! end - + yield other end end - + def fix! tag.delay(:queue => "default").fix_post_count Post.expire_cache_for_all([tag.name]) diff --git a/app/logical/tag_implication_request.rb b/app/logical/tag_implication_request.rb index 80754658f..f4a831746 100644 --- a/app/logical/tag_implication_request.rb +++ b/app/logical/tag_implication_request.rb @@ -1,28 +1,28 @@ class TagImplicationRequest class ValidationError < Exception ; end - + attr_reader :antecedent_name, :consequent_name, :reason, :tag_implication, :forum_topic - + def initialize(antecedent_name, consequent_name, reason) @antecedent_name = antecedent_name.tr(" ", "_") @consequent_name = consequent_name.tr(" ", "_") @reason = reason end - + def create TagImplication.transaction do create_implication create_forum_topic end end - + def create_implication @tag_implication = TagImplication.create(:antecedent_name => antecedent_name, :consequent_name => consequent_name, :status => "pending") if @tag_implication.errors.any? raise ValidationError.new(@tag_implication.errors.full_messages.join("; ")) end end - + def create_forum_topic @forum_topic = ForumTopic.create( :title => "Tag implication: #{antecedent_name} -> #{consequent_name}", @@ -33,7 +33,7 @@ class TagImplicationRequest if @forum_topic.errors.any? raise ValidationError.new(@forum_topic.errors.full_messages.join("; ")) end - + tag_implication.update_attribute(:forum_topic_id, @forum_topic.id) end end diff --git a/app/logical/uploaded_tags_importer.rb b/app/logical/uploaded_tags_importer.rb index 349d72db9..c9b99e9bb 100644 --- a/app/logical/uploaded_tags_importer.rb +++ b/app/logical/uploaded_tags_importer.rb @@ -1,10 +1,10 @@ class UploadedTagsImporter attr_reader :user - + def initialize(user) @user = user end - + def import! row = connection.exec("SELECT uploaded_tags FROM users WHERE id = #{user.id}").first if row @@ -13,7 +13,7 @@ class UploadedTagsImporter connection.close rescue Exception end - + def connection @connection ||= PGconn.connect(:dbname => "danbooru", :host => "dbserver", :user => "albert") end diff --git a/app/mailers/maintenance/user/password_reset_mailer.rb b/app/mailers/maintenance/user/password_reset_mailer.rb index 8ad1f6d0a..7910bacbd 100644 --- a/app/mailers/maintenance/user/password_reset_mailer.rb +++ b/app/mailers/maintenance/user/password_reset_mailer.rb @@ -6,7 +6,7 @@ module Maintenance @nonce = nonce mail(:to => @user.email, :subject => "#{Danbooru.config.app_name} password reset request", :from => Danbooru.config.contact_email) end - + def confirmation(user, new_password) @user = user @new_password = new_password diff --git a/app/mailers/user_mailer.rb b/app/mailers/user_mailer.rb index 69d15921a..7a9689b70 100644 --- a/app/mailers/user_mailer.rb +++ b/app/mailers/user_mailer.rb @@ -3,13 +3,13 @@ class UserMailer < ActionMailer::Base def dmail_notice(dmail) @dmail = dmail - mail(:to => "#{dmail.to.name} <#{dmail.to.email}>", :subject => "#{Danbooru.config.app_name} - Message received from #{dmail.from.name}") + mail(:to => "#{dmail.to.name} <#{dmail.to.email}>", :subject => "#{Danbooru.config.app_name} - Message received from #{dmail.from.name}") end - + def upgrade(user, email) mail(:to => "#{user.name} <#{email}>", :subject => "#{Danbooru.config.app_name} account upgrade") end - + def upgrade_fail(email) mail(:to => "#{user.name} <#{email}>", :subject => "#{Danbooru.config.app_name} account upgrade") end diff --git a/app/models/advertisement.rb b/app/models/advertisement.rb index 26a2bb095..598baf62c 100644 --- a/app/models/advertisement.rb +++ b/app/models/advertisement.rb @@ -7,7 +7,7 @@ class Advertisement < ActiveRecord::Base def copy_to_servers RemoteFileManager.new(image_path).distribute end - + def delete_from_servers RemoteFileManager.new(image_path).delete end @@ -19,15 +19,15 @@ class Advertisement < ActiveRecord::Base def hit_sum(start_date, end_date) hits.where(["created_at BETWEEN ? AND ?", start_date, end_date]).count end - + def unique_identifier @unique_identifier ||= ("%.0f" % (Time.now.to_f * 1_000)) end - + def image_url "/images/advertisements/ads-#{date_prefix}/#{file_name}" end - + def date_prefix created_at.try(:strftime, "%Y%m%d") end @@ -35,11 +35,11 @@ class Advertisement < ActiveRecord::Base def image_path "#{Danbooru.config.advertisement_path}/ads-#{date_prefix}/#{file_name}" end - + def file nil end - + def file=(f) if f.size > 0 self.file_name = unique_identifier + File.extname(f.original_filename) @@ -55,7 +55,7 @@ class Advertisement < ActiveRecord::Base image_size = ImageSize.new(File.open(image_path, "rb")) self.width = image_size.get_width self.height = image_size.get_height - + if width > height self.ad_type = "horizontal" else @@ -63,7 +63,7 @@ class Advertisement < ActiveRecord::Base end end end - + def preview_width if width > 100 || height > 100 if width < height @@ -72,9 +72,9 @@ class Advertisement < ActiveRecord::Base else return 100 end - end + end end - + def preview_height if width > 100 || height > 100 if height < width @@ -83,6 +83,6 @@ class Advertisement < ActiveRecord::Base else return 100 end - end + end end end diff --git a/app/models/advertisement_hit.rb b/app/models/advertisement_hit.rb index b20905e59..4d2c40c20 100644 --- a/app/models/advertisement_hit.rb +++ b/app/models/advertisement_hit.rb @@ -1,5 +1,5 @@ class AdvertisementHit < ActiveRecord::Base belongs_to :advertisement - + scope :between, lambda {|start_date, end_date| where("created_at BETWEEN ? AND ?", start_date, end_date)} end diff --git a/app/models/amazon_backup.rb b/app/models/amazon_backup.rb index 2c33383e4..bdcbf17d2 100644 --- a/app/models/amazon_backup.rb +++ b/app/models/amazon_backup.rb @@ -5,17 +5,17 @@ class AmazonBackup < ActiveRecord::Base def self.last_id first.last_id end - + def self.update_id(new_id) first.update_column(:last_id, new_id) end - + def self.execute last_id = AmazonBackup.last_id - + Post.where("id > ?", last_id).limit(200).order("id").each do |post| AWS::S3::Base.establish_connection!( - :access_key_id => Danbooru.config.amazon_s3_access_key_id, + :access_key_id => Danbooru.config.amazon_s3_access_key_id, :secret_access_key => Danbooru.config.amazon_s3_secret_access_key ) @@ -31,7 +31,7 @@ class AmazonBackup < ActiveRecord::Base if File.exists?(post.large_file_path) AWS::S3::S3Object.store("large/#{post.md5}.jpg", open(post.large_file_path, "rb"), Danbooru.config.amazon_s3_bucket_name) end - + AmazonBackup.update_id(last_id) end rescue Exception => x diff --git a/app/models/artist.rb b/app/models/artist.rb index 285e5baa5..145d02acc 100644 --- a/app/models/artist.rb +++ b/app/models/artist.rb @@ -13,10 +13,10 @@ class Artist < ActiveRecord::Base accepts_nested_attributes_for :wiki_page attr_accessible :body, :name, :url_string, :other_names, :other_names_comma, :group_name, :wiki_page_attributes, :notes, :is_active, :as => [:member, :privileged, :builder, :platinum, :contributor, :janitor, :moderator, :default, :admin] attr_accessible :is_banned, :as => :admin - + module UrlMethods extend ActiveSupport::Concern - + module ClassMethods def find_all_by_url(url) url = ArtistUrl.normalize(url) @@ -43,11 +43,11 @@ class Artist < ActiveRecord::Base end end end - + def url_string=(string) @url_string = string end - + def url_string @url_string || urls.map {|x| x.url}.join("\n") end @@ -55,7 +55,7 @@ class Artist < ActiveRecord::Base module NameMethods extend ActiveSupport::Concern - + module ClassMethods def normalize_name(name) name.to_s.downcase.strip.gsub(/ /, '_') @@ -65,26 +65,26 @@ class Artist < ActiveRecord::Base def normalize_name self.name = Artist.normalize_name(name) end - + def other_names_array other_names.try(:split, / /) end - + def other_names_comma other_names_array.try(:join, ", ") end - + def other_names_comma=(string) self.other_names = string.split(/,/).map {|x| Artist.normalize_name(x)}.join(" ") end end - + module GroupMethods def member_names members.map(&:name).join(", ") end end - + module VersionMethods def create_version ArtistVersion.create( @@ -98,14 +98,14 @@ class Artist < ActiveRecord::Base :group_name => group_name ) end - + def revert_to!(version) self.name = version.name self.url_string = version.url_string self.is_active = version.is_active self.other_names = version.other_names self.group_name = version.group_name - save + save end end @@ -119,11 +119,11 @@ class Artist < ActiveRecord::Base artist.url_string = post.source end end - + if params[:other_names] artist.other_names = params[:other_names] end - + if params[:urls] artist.url_string = params[:urls] end @@ -139,7 +139,7 @@ class Artist < ActiveRecord::Base nil end end - + def notes=(msg) if wiki_page wiki_page.title = name @@ -152,7 +152,7 @@ class Artist < ActiveRecord::Base end end end - + module TagMethods def has_tag_alias? TagAlias.exists?(["antecedent_name = ?", name]) @@ -162,7 +162,7 @@ class Artist < ActiveRecord::Base TagAlias.find_by_antecedent_name(name).consequent_name end end - + module BanMethods def ban! Post.transaction do @@ -178,24 +178,24 @@ class Artist < ActiveRecord::Base rescue Post::SearchError # swallow end - + # potential race condition but unlikely unless TagImplication.where(:antecedent_name => name, :consequent_name => "banned_artist").exists? tag_implication = TagImplication.create(:antecedent_name => name, :consequent_name => "banned_artist") tag_implication.delay(:queue => "default").process! end - + update_column(:is_active, false) update_column(:is_banned, true) end end end - + module SearchMethods def active where("is_active = true") end - + def banned where("is_banned = true") end @@ -209,27 +209,27 @@ class Artist < ActiveRecord::Base where("false") end end - + def other_names_match(string) where("other_names_index @@ to_tsquery('danbooru', E?)", Artist.normalize_name(string).to_escaped_for_tsquery) end - + def group_name_matches(name) stripped_name = normalize_name(name).to_escaped_for_sql_like where("group_name LIKE ? ESCAPE E'\\\\'", stripped_name) end - + def name_matches(name) stripped_name = normalize_name(name).to_escaped_for_sql_like where("name LIKE ? ESCAPE E'\\\\'", stripped_name) end - + def any_name_matches(name) stripped_name = normalize_name(name).to_escaped_for_sql_like name_for_tsquery = normalize_name(name).to_escaped_for_tsquery where("(name LIKE ? ESCAPE E'\\\\' OR other_names_index @@ to_tsquery('danbooru', E?))", stripped_name, name_for_tsquery) end - + def search(params) q = active params = {} if params.blank? @@ -240,7 +240,7 @@ class Artist < ActiveRecord::Base when /name:(.+)/ q = q.name_matches($1) - + when /other:(.+)/ q = q.other_names_match($1) @@ -253,7 +253,7 @@ class Artist < ActiveRecord::Base when /./ q = q.any_name_matches(params[:name]) end - + if params[:sort] == "Name" q = q.reorder("name") else @@ -263,11 +263,11 @@ class Artist < ActiveRecord::Base if params[:id].present? q = q.where("id = ?", params[:id]) end - + q end end - + include UrlMethods include NameMethods include GroupMethods @@ -277,7 +277,7 @@ class Artist < ActiveRecord::Base include TagMethods include BanMethods extend SearchMethods - + def status if is_banned? "Banned" @@ -287,11 +287,11 @@ class Artist < ActiveRecord::Base "Deleted" end end - + def legacy_api_hash return { - :id => id, - :name => name, + :id => id, + :name => name, :other_names => other_names, :group_name => group_name, :urls => artist_urls.map {|x| x.url}, @@ -299,7 +299,7 @@ class Artist < ActiveRecord::Base :updater_id => 0 } end - + def initialize_creator self.creator_id = CurrentUser.user.id end diff --git a/app/models/artist_url.rb b/app/models/artist_url.rb index 3c05a5d04..834b0921b 100644 --- a/app/models/artist_url.rb +++ b/app/models/artist_url.rb @@ -2,7 +2,7 @@ class ArtistUrl < ActiveRecord::Base before_save :normalize validates_presence_of :url belongs_to :artist - + def self.normalize(url) if url.nil? nil @@ -17,24 +17,24 @@ class ArtistUrl < ActiveRecord::Base url + "/" end end - + def self.normalize_for_search(url) if url =~ /\.\w+\Z/ && url =~ /\w\/\w/ url = File.dirname(url) end - + url = url.gsub(/^https:\/\//, "http://") url = url.gsub(/^http:\/\/blog\d+\.fc2/, "http://blog*.fc2") url = url.gsub(/^http:\/\/blog-imgs-\d+\.fc2/, "http://blog*.fc2") url = url.gsub(/^http:\/\/blog-imgs-\d+-\w+\.fc2/, "http://blog*.fc2") - url = url.gsub(/^http:\/\/img\d+\.pixiv\.net/, "http://img*.pixiv.net") + url = url.gsub(/^http:\/\/img\d+\.pixiv\.net/, "http://img*.pixiv.net") url = url.gsub(/^http:\/\/i\d+\.pixiv\.net\/img\d+/, "http://*.pixiv.net/img*") end def normalize self.normalized_url = self.class.normalize(url) end - + def to_s url end diff --git a/app/models/artist_version.rb b/app/models/artist_version.rb index c2b1feb0a..1e5b15a3c 100644 --- a/app/models/artist_version.rb +++ b/app/models/artist_version.rb @@ -1,32 +1,32 @@ class ArtistVersion < ActiveRecord::Base belongs_to :updater belongs_to :artist - + def self.search(params) q = scoped return q if params.blank? - + if params[:name] q = q.where("name like ? escape E'\\\\'", params[:name].to_escaped_for_sql_like) end - + if params[:artist_id] q = q.where("artist_id = ?", params[:artist_id].to_i) end - + if params[:sort] == "Name" q = q.reorder("name") else q = q.reorder("id desc") end - + q end - + def url_array url_string.scan(/\S+/) end - + def updater_name User.id_to_name(updater_id).tr("_", " ") end diff --git a/app/models/ban.rb b/app/models/ban.rb index 94edc8216..98d5a5231 100644 --- a/app/models/ban.rb +++ b/app/models/ban.rb @@ -6,42 +6,42 @@ class Ban < ActiveRecord::Base validate :user_is_inferior validates_presence_of :user_id, :reason, :duration before_validation :initialize_banner_id, :on => :create - + def self.is_banned?(user) exists?(["user_id = ? AND expires_at > ?", user.id, Time.now]) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:banner_name] q = q.where("banner_id = (select _.id from users _ where lower(_.name) = ?)", params[:banner_name].downcase) end - + if params[:banner_id] q = q.where("banner_id = ?", params[:banner_id].to_i) end - + if params[:user_name] q = q.where("user_id = (select _.id from users _ where lower(_.name) = ?)", params[:user_name].downcase) end - + if params[:user_id] q = q.where("user_id = ?", params[:user_id].to_i) end - + q end - + def initialize_banner_id self.banner_id = CurrentUser.id end - + def user_is_inferior if user if user.is_admin? - errors[:base] << "You can never ban an admin." + errors[:base] << "You can never ban an admin." false elsif user.is_moderator? && banner.is_admin? true @@ -56,7 +56,7 @@ class Ban < ActiveRecord::Base end end end - + def update_feedback if user feedback = user.feedback.build @@ -66,24 +66,24 @@ class Ban < ActiveRecord::Base feedback.save end end - + def user_name user ? user.name : nil end - + def user_name=(username) self.user_id = User.name_to_id(username) end - + def duration=(dur) self.expires_at = dur.to_i.days.from_now @duration = dur end - + def duration @duration end - + def expired? expires_at < Time.now end diff --git a/app/models/comment.rb b/app/models/comment.rb index 485a0a56e..eb10fab60 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -10,62 +10,62 @@ class Comment < ActiveRecord::Base after_destroy :update_last_commented_at attr_accessible :body, :post_id, :do_not_bump_post attr_accessor :do_not_bump_post - + module SearchMethods def recent reorder("comments.id desc").limit(6) end - + def body_matches(query) where("body_index @@ plainto_tsquery(?)", query.to_escaped_for_tsquery_split).order("comments.id DESC") end - + def hidden(user) where("score < ?", user.comment_threshold) end - + def visible(user) where("score >= ?", user.comment_threshold) end - + def post_tags_match(query) joins(:post).where("posts.tag_index @@ to_tsquery('danbooru', ?)", query.to_escaped_for_tsquery_split) end - + def for_creator(user_id) where("creator_id = ?", user_id) end - + def for_creator_name(user_name) where("creator_id = (select _.id from users _ where lower(_.name) = lower(?))", user_name.downcase) end - + def search(params) q = scoped return q if params.blank? - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end - + if params[:post_tags_match].present? q = q.post_tags_match(params[:post_tags_match]) end - + if params[:creator_name].present? q = q.for_creator_name(params[:creator_name]) end - + if params[:creator_id].present? q = q.for_creator(params[:creator_id].to_i) end - + q end end - + extend SearchMethods - + def initialize_creator self.creator_id = CurrentUser.user.id self.ip_addr = CurrentUser.ip_addr @@ -79,7 +79,7 @@ class Comment < ActiveRecord::Base def creator_name User.id_to_name(creator_id) end - + def updater_name User.id_to_name(updater_id) end @@ -100,15 +100,15 @@ class Comment < ActiveRecord::Base Post.update_all(["last_commented_at = ?", created_at], ["id = ?", post_id]) end end - + def do_not_bump_post? do_not_bump_post == "1" end - + def vote!(val) numerical_score = val == "up" ? 1 : -1 vote = votes.create(:score => numerical_score) - + if vote.errors.empty? if vote.is_positive? update_column(:score, score + 1) @@ -119,7 +119,7 @@ class Comment < ActiveRecord::Base return vote end - + def editable_by?(user) creator_id == user.id || user.is_janitor? end diff --git a/app/models/comment_vote.rb b/app/models/comment_vote.rb index a4c3831c2..728da2b0a 100644 --- a/app/models/comment_vote.rb +++ b/app/models/comment_vote.rb @@ -9,22 +9,22 @@ class CommentVote < ActiveRecord::Base validate :validate_user_can_vote validate :validate_comment_can_be_down_voted validates_inclusion_of :score, :in => [-1, 1], :message => "must be 1 or -1" - + def self.prune! destroy_all("created_at < ?", 14.days.ago) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:comment_id] q = q.where("comment_id = ?", params[:comment_id].to_i) end - + q end - + def validate_user_can_vote if !user.can_comment_vote? errors.add :base, "You cannot vote on comments" @@ -33,24 +33,24 @@ class CommentVote < ActiveRecord::Base true end end - + def validate_comment_can_be_down_voted - if is_negative? && comment.creator.is_janitor? + if is_negative? && comment.creator.is_janitor? errors.add :base, "You cannot downvote a janitor comment" false else true end end - + def is_positive? score == 1 end - + def is_negative? score == -1 end - + def initialize_user self.user_id = CurrentUser.user.id end diff --git a/app/models/dmail.rb b/app/models/dmail.rb index 0f4c4a995..2889a45d8 100644 --- a/app/models/dmail.rb +++ b/app/models/dmail.rb @@ -11,7 +11,7 @@ class Dmail < ActiveRecord::Base after_create :update_recipient after_create :send_dmail attr_accessible :title, :body, :is_deleted, :to_id, :to, :to_name - + module AddressMethods def to_name User.id_to_pretty_name(to_id) @@ -26,19 +26,19 @@ class Dmail < ActiveRecord::Base return if user.nil? self.to_id = user.id end - + def initialize_from_id self.from_id = CurrentUser.id end end - + module FactoryMethods extend ActiveSupport::Concern - + module ClassMethods def create_split(params) copy = nil - + Dmail.transaction do copy = Dmail.new(params) copy.owner_id = copy.to_id @@ -51,17 +51,17 @@ class Dmail < ActiveRecord::Base copy.is_read = true copy.save end - + copy end - + def new_blank Dmail.new do |dmail| dmail.from_id = CurrentUser.id end end end - + def build_response(options = {}) Dmail.new do |dmail| if title =~ /Re:/ @@ -76,84 +76,84 @@ class Dmail < ActiveRecord::Base end end end - + module SearchMethods def for(user) where("owner_id = ?", user) end - + def inbox where("to_id = owner_id") end - + def sent where("from_id = owner_id") end - + def active where("is_deleted = ?", false) end - + def deleted where("is_deleted = ?", true) end - + def search_message(query) where("message_index @@ plainto_tsquery(?)", query.to_escaped_for_tsquery_split) end - + def unread where("is_read = false and is_deleted = false") end - + def visible where("owner_id = ?", CurrentUser.id) end - + def to_name_matches(name) where("to_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def from_name_matches(name) where("from_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def search(params) q = scoped return q if params.blank? - + if params[:message_matches].present? q = q.search_message(params[:message_matches]) end - + if params[:owner_id].present? q = q.for(params[:owner_id].to_i) end - + if params[:to_name].present? q = q.to_name_matches(params[:to_name]) end - + if params[:to_id].present? q = q.where("to_id = ?", params[:to_id].to_i) end - + if params[:from_name].present? q = q.from_name_matches(params[:from_name]) end - + if params[:from_id].present? q = q.where("from_id = ?", params[:from_id].to_i) end - + q end end - + include AddressMethods include FactoryMethods extend SearchMethods - + def validate_sender_is_not_banned if from.is_banned? errors[:base] = "Sender is banned and cannot send messages" @@ -162,29 +162,29 @@ class Dmail < ActiveRecord::Base return true end end - + def quoted_body "[quote]#{body}[/quote]" end - + def send_dmail if to.receive_email_notifications? && to.email.include?("@") && owner_id == CurrentUser.id UserMailer.dmail_notice(self).deliver - end + end end - + def mark_as_read! update_column(:is_read, true) - + unless Dmail.exists?(["to_id = ? AND is_read = false", to_id]) to.update_column(:has_mail, false) end end - + def update_recipient to.update_column(:has_mail, true) end - + def visible_to?(user) user.is_moderator? || owner_id == user.id end diff --git a/app/models/favorite.rb b/app/models/favorite.rb index 24a2ba940..9f81edba5 100644 --- a/app/models/favorite.rb +++ b/app/models/favorite.rb @@ -1,7 +1,7 @@ class Favorite < ActiveRecord::Base belongs_to :post scope :for_user, lambda {|user_id| where("user_id % 100 = #{user_id.to_i % 100} and user_id = #{user_id.to_i}")} - + # this is necessary because there's no trigger for deleting favorites def self.destroy_all(hash) connection.execute("delete from favorites_#{hash[:user_id] % 100} where user_id = #{hash[:user_id]} and post_id = #{hash[:post_id]}") diff --git a/app/models/forum_post.rb b/app/models/forum_post.rb index 4ce71fb67..c0fec63b1 100644 --- a/app/models/forum_post.rb +++ b/app/models/forum_post.rb @@ -11,54 +11,54 @@ class ForumPost < ActiveRecord::Base validate :validate_topic_is_unlocked before_destroy :validate_topic_is_unlocked after_save :delete_topic_if_original_post - + module SearchMethods def body_matches(body) where("forum_posts.text_index @@ plainto_tsquery(E?)", body.to_escaped_for_tsquery) end - + def for_user(user_id) where("forum_posts.creator_id = ?", user_id) end - + def creator_name(name) where("forum_posts.creator_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def active where("forum_posts.is_deleted = false") end - + def search(params) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:topic_id].present? q = q.where("topic_id = ?", params[:topic_id].to_i) end - + if params[:topic_title_matches].present? q = q.joins(:topic).where("forum_topics.text_index @@ plainto_tsquery(E?)", params[:topic_title_matches].to_escaped_for_tsquery_split) end - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end - + if params[:creator_name].present? q = q.creator_name(params[:creator_name]) end - + q end end - + extend SearchMethods - + def self.new_reply(params) if params[:topic_id] new(:topic_id => params[:topic_id]) @@ -69,13 +69,13 @@ class ForumPost < ActiveRecord::Base new end end - + def validate_topic_is_unlocked return if CurrentUser.is_moderator? return if topic.nil? - + if topic.is_locked? - errors.add(:topic, "is locked") + errors.add(:topic, "is locked") return false else return true @@ -85,7 +85,7 @@ class ForumPost < ActiveRecord::Base def editable_by?(user) creator_id == user.id || user.is_janitor? end - + def update_topic_updated_at if topic topic.updater_id = CurrentUser.id @@ -93,19 +93,19 @@ class ForumPost < ActiveRecord::Base topic.save end end - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id end - + def initialize_is_deleted self.is_deleted = false if is_deleted.nil? end - + def creator_name User.id_to_name(creator_id) end @@ -113,28 +113,28 @@ class ForumPost < ActiveRecord::Base def updater_name User.id_to_name(updater_id) end - + def quoted_response stripped_body = body.gsub(/\[quote\](?:.|\n|\r)+?\[\/quote\][\n\r]*/m, "") "[quote]\n#{creator_name} said:\n\n#{stripped_body}\n[/quote]\n\n" 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 end - + def is_original_post? ForumPost.exists?(["id = ? and id = (select _.id from forum_posts _ where _.topic_id = ? order by _.id asc limit 1)", id, topic_id]) end - + def delete_topic_if_original_post if is_deleted? && is_original_post? topic.update_attribute(:is_deleted, true) end - + true end - + def build_response dup.tap do |x| x.body = x.quoted_response diff --git a/app/models/forum_topic.rb b/app/models/forum_topic.rb index 975e81054..c78e0b4e8 100644 --- a/app/models/forum_topic.rb +++ b/app/models/forum_topic.rb @@ -11,34 +11,34 @@ class ForumTopic < ActiveRecord::Base validates_presence_of :title, :creator_id validates_associated :original_post accepts_nested_attributes_for :original_post - + module SearchMethods def title_matches(title) where("text_index @@ plainto_tsquery(E?)", title.to_escaped_for_tsquery_split) end - + def active where("is_deleted = false") end - + def search(params) q = scoped return q if params.blank? - + if params[:title_matches].present? q = q.title_matches(params[:title_matches]) end - + if params[:title].present? q = q.where("title = ?", params[:title]) end - + q end end - + extend SearchMethods - + def editable_by?(user) creator_id == user.id || user.is_janitor? end @@ -50,15 +50,15 @@ class ForumTopic < ActiveRecord::Base def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id end - + def last_page (posts.count / Danbooru.config.posts_per_page.to_f).ceil end - + def presenter(forum_posts) @presenter ||= ForumTopicPresenter.new(self, forum_posts) end diff --git a/app/models/ip_ban.rb b/app/models/ip_ban.rb index a6921c5e6..e5e6e089c 100644 --- a/app/models/ip_ban.rb +++ b/app/models/ip_ban.rb @@ -5,19 +5,19 @@ class IpBan < ActiveRecord::Base validates_presence_of :reason, :creator, :ip_addr validates_format_of :ip_addr, :with => IP_ADDR_REGEX validates_uniqueness_of :ip_addr, :if => lambda {|rec| rec.ip_addr =~ IP_ADDR_REGEX} - + def self.is_banned?(ip_addr) exists?(["ip_addr = ?", ip_addr]) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:ip_addr].present? q = q.where("ip_addr = ?", params[:ip_addr]) end - + q end @@ -26,7 +26,7 @@ class IpBan < ActiveRecord::Base notes = count_by_ip_addr("note_versions", user_ids, "updater_id", "updater_ip_addr") pools = count_by_ip_addr("pool_versions", user_ids, "updater_id", "updater_ip_addr") wiki_pages = count_by_ip_addr("wiki_page_versions", user_ids, "updater_id", "updater_ip_addr") - + return { "comments" => comments, "notes" => notes, @@ -34,11 +34,11 @@ class IpBan < ActiveRecord::Base "wiki_pages" => wiki_pages } end - + def self.count_by_ip_addr(table, user_ids, user_id_field = "user_id", ip_addr_field = "ip_addr") select_all_sql("SELECT #{ip_addr_field}, count(*) FROM #{table} WHERE #{user_id_field} IN (?) GROUP BY #{ip_addr_field} ORDER BY count(*) DESC", user_ids) end - + def initialize_creator self.creator_id = CurrentUser.id end diff --git a/app/models/janitor_trial.rb b/app/models/janitor_trial.rb index 4039094a7..cd16c8a31 100644 --- a/app/models/janitor_trial.rb +++ b/app/models/janitor_trial.rb @@ -6,59 +6,59 @@ class JanitorTrial < ActiveRecord::Base after_destroy :create_feedback validates_presence_of :user before_validation :initialize_creator - + def self.search(params) q = scoped return q if params.blank? - + if params[:user_name] q = q.where("user_id = (select _.id from users _ where lower(_.name) = ?)", params[:user_name].downcase) end - + if params[:user_id] q = q.where("user_id = ?", params[:user_id].to_i) end - + q end - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_original_level self.original_level = user.level end - + def user_name user.try(:name) end - + def user_name=(name) self.user_id = User.name_to_id(name) end - + def send_dmail body = "You have been selected as a test janitor. You can now approve pending posts and have access to the moderation interface.\n\nOver the next several weeks your approvals will be monitored. If the majority of them are quality uploads, then you will be promoted to full janitor status which grants you the ability to delete and undelete posts, ban users, and revert tag changes from vandals. If you fail the trial period, you will be demoted back to your original level and you'll receive a negative user record indicating you previously attempted and failed a test janitor trial.\n\nThere is a minimum quota of 5 approvals a week to indicate that you are being active. Remember, the goal isn't to approve as much as possible. It's to filter out borderline-quality art.\n\nIf you have any questions please respond to this message." - + Dmail.create_split(:title => "Test Janitor Trial Period", :body => body, :to_id => user_id) end - + def promote_user user.update_column(:level, User::Levels::JANITOR) end - + def create_feedback user.feedback.create( :category => "negative", :body => "Demoted from janitor trial" ) end - + def promote! destroy end - + def demote! user.update_column(:level, original_level) destroy diff --git a/app/models/mod_action.rb b/app/models/mod_action.rb index 97013ef2f..d8459096a 100644 --- a/app/models/mod_action.rb +++ b/app/models/mod_action.rb @@ -1,18 +1,18 @@ class ModAction < ActiveRecord::Base belongs_to :creator, :class_name => "User" before_validation :initialize_creator, :on => :create - + def self.search(params = {}) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + q end - + def initialize_creator self.creator_id = CurrentUser.id end diff --git a/app/models/news_update.rb b/app/models/news_update.rb index 9b844767d..5fa37bbc0 100644 --- a/app/models/news_update.rb +++ b/app/models/news_update.rb @@ -4,11 +4,11 @@ class NewsUpdate < ActiveRecord::Base scope :recent, order("created_at desc").limit(5) before_validation :initialize_creator, :on => :create before_validation :initialize_updater - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id end diff --git a/app/models/note.rb b/app/models/note.rb index d61865e9a..ec36dde35 100644 --- a/app/models/note.rb +++ b/app/models/note.rb @@ -12,28 +12,28 @@ class Note < ActiveRecord::Base after_save :create_version validate :post_must_not_be_note_locked attr_accessible :x, :y, :width, :height, :body, :updater_id, :updater_ip_addr, :is_active, :post_id, :html_id - + module SearchMethods def active where("is_active = TRUE") end - + def body_matches(query) where("body_index @@ plainto_tsquery(E?)", query.to_escaped_for_tsquery_split) end - + def post_tags_match(query) joins(:post).where("posts.tag_index @@ to_tsquery('danbooru', E?)", query.to_escaped_for_tsquery_split) end - + def creator_name(name) where("creator_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def search(params) q = scoped return q if params.blank? - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end @@ -41,23 +41,23 @@ class Note < ActiveRecord::Base if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + if params[:post_tags_match].present? q = q.post_tags_match(params[:post_tags_match]) end - + if params[:creator_name].present? q = q.creator_name(params[:creator_name]) end - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + q end end - + module ApiMethods def serializable_hash(options = {}) options ||= {} @@ -70,7 +70,7 @@ class Note < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -78,34 +78,34 @@ class Note < ActiveRecord::Base super(options, &block) end end - + extend SearchMethods include ApiMethods - + def presenter @presenter ||= NotePresenter.new(self) end - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def post_must_not_be_note_locked if is_locked? errors.add :post, "is note locked" return false end end - + def is_locked? Post.exists?(["id = ? AND is_note_locked = ?", post_id, true]) end - + def blank_body self.body = "(empty)" if body.blank? end @@ -121,10 +121,10 @@ class Note < ActiveRecord::Base execute_sql("UPDATE posts SET last_noted_at = NULL WHERE id = ?", post_id) end end - + def create_version CurrentUser.increment!(:note_update_count) - + versions.create( :updater_id => updater_id, :updater_ip_addr => updater_ip_addr, @@ -137,7 +137,7 @@ class Note < ActiveRecord::Base :body => body ) end - + def revert_to(version) self.x = version.x self.y = version.y @@ -149,7 +149,7 @@ class Note < ActiveRecord::Base self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def revert_to!(version) revert_to(version) save! diff --git a/app/models/note_version.rb b/app/models/note_version.rb index 012bfa731..f88b20324 100644 --- a/app/models/note_version.rb +++ b/app/models/note_version.rb @@ -6,22 +6,22 @@ class NoteVersion < ActiveRecord::Base def self.search(params) q = scoped params = {} if params.blank? - + if params[:updater_id] q = q.where("updater_id = ?", params[:updater_id].to_i) end - + if params[:post_id] q = q.where("post_id = ?", params[:post_id].to_i) end - + if params[:note_id] q = q.where("note_id = ?", params[:note_id].to_i) end - + q end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr diff --git a/app/models/pool.rb b/app/models/pool.rb index dbcce217b..0770332c6 100644 --- a/app/models/pool.rb +++ b/app/models/pool.rb @@ -19,41 +19,41 @@ class Pool < ActiveRecord::Base def active where("is_deleted = false") end - + def search(params) q = scoped params = {} if params.blank? - + if params[:name_matches].present? params[:name_matches] = params[:name_matches].tr(" ", "_") params[:name_matches] = "*#{params[:name_matches]}*" unless params[:name_matches] =~ /\*/ q = q.where("name ilike ? escape E'\\\\'", params[:name_matches].to_escaped_for_sql_like) end - + if params[:description_matches].present? q = q.where("description like ? escape E'\\\\'", "%" + params[:description_matches].to_escaped_for_sql_like + "%") end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:sort] == "name" q = q.order("name") else q = q.order("updated_at desc") end - + q end end - + extend SearchMethods - + def self.name_to_id(name) if name =~ /^\d+$/ name.to_i @@ -61,15 +61,15 @@ class Pool < ActiveRecord::Base select_value_sql("SELECT id FROM pools WHERE lower(name) = ?", name.downcase.tr(" ", "_")).to_i end end - + def self.id_to_name(id) select_value_sql("SELECT name FROM pools WHERE id = ?", id) end - + def self.options select_all_sql("SELECT id, name FROM pools WHERE is_active = true AND is_deleted = false ORDER BY name LIMIT 100").map {|x| [x["name"].tr("_", " "), x["id"]]} end - + def self.create_anonymous Pool.new do |pool| pool.name = "TEMP:#{Time.now.to_f}.#{rand(1_000_000)}" @@ -78,15 +78,15 @@ class Pool < ActiveRecord::Base pool.save end end - + def self.normalize_name(name) name.gsub(/\s+/, "_") end - + def self.normalize_post_ids(post_ids) post_ids.scan(/\d+/).join(" ") end - + def self.find_by_name(name) if name =~ /^\d+$/ where("id = ?", name.to_i).first @@ -96,32 +96,32 @@ class Pool < ActiveRecord::Base nil end end - + def initialize_is_active self.is_deleted = false if is_deleted.nil? self.is_active = true if is_active.nil? end - + def initialize_creator self.creator_id = CurrentUser.id end - + def normalize_name self.name = Pool.normalize_name(name) end - + def pretty_name name.tr("_", " ") end - + def creator_name User.id_to_name(creator_id) end - + def normalize_post_ids self.post_ids = self.class.normalize_post_ids(post_ids) end - + def revert_to!(version) self.post_ids = version.post_ids synchronize! @@ -130,39 +130,39 @@ class Pool < ActiveRecord::Base def contains?(post_id) post_ids =~ /(?:\A| )#{post_id}(?:\Z| )/ end - + def deletable_by?(user) user.is_janitor? end - + def create_mod_action_for_destroy ModAction.create(:description => "deleted pool ##{id} name=#{name} post_ids=#{post_ids}") end - + def add!(post) return if contains?(post.id) - + update_attributes(:post_ids => add_number_to_string(post.id, post_ids), :post_count => post_count + 1) post.add_pool!(self) clear_post_id_array end - + def remove!(post) return unless contains?(post.id) - + update_attributes(:post_ids => remove_number_from_string(post.id, post_ids), :post_count => post_count - 1) post.remove_pool!(self) clear_post_id_array end - + def add_number_to_string(number, string) "#{string} #{number}" end - + def remove_number_from_string(number, string) string.gsub(/(?:\A| )#{number}(?:\Z| )/, " ") end - + def posts(options = {}) offset = options[:offset] || 0 limit = options[:limit] || Danbooru.config.posts_per_page @@ -173,47 +173,47 @@ class Pool < ActiveRecord::Base Post.where("false") end end - + def synchronize! added = post_id_array - post_id_array_was removed = post_id_array_was - post_id_array - + added.each do |post_id| post = Post.find(post_id) post.add_pool!(self) end - + removed.each do |post_id| post = Post.find(post_id) post.remove_pool!(self) end - + self.post_count = post_id_array.size save end - + def post_id_array @post_id_array ||= post_ids.scan(/\d+/).map(&:to_i) end - + def post_id_array=(array) self.post_ids = array.join(" ") clear_post_id_array end - + def post_id_array_was @post_id_array_was ||= post_ids_was.scan(/\d+/).map(&:to_i) end - + def clear_post_id_array @post_id_array = nil @post_id_array_was = nil end - + def neighbors(post) @neighbor_posts ||= begin post_ids =~ /\A#{post.id} (\d+)|(\d+) #{post.id} (\d+)|(\d+) #{post.id}\Z/ - + if $2 && $3 OpenStruct.new(:previous => $2.to_i, :next => $3.to_i) elsif $1 @@ -225,7 +225,7 @@ class Pool < ActiveRecord::Base end end end - + def create_version last_version = versions.last @@ -235,20 +235,20 @@ class Pool < ActiveRecord::Base versions.create(:post_ids => post_ids) end end - + def reload(options = {}) super @neighbor_posts = nil clear_post_id_array end - + def to_xml(options = {}, &block) # to_xml ignores the serializable_hash method options ||= {} options[:methods] = [:creator_name] super(options, &block) end - + def serializable_hash(options = {}) return { "created_at" => created_at, diff --git a/app/models/pool_version.rb b/app/models/pool_version.rb index 5534803e8..04a419fa7 100644 --- a/app/models/pool_version.rb +++ b/app/models/pool_version.rb @@ -1,6 +1,6 @@ class PoolVersion < ActiveRecord::Base class Error < Exception ; end - + validates_presence_of :updater_id, :updater_ip_addr belongs_to :pool belongs_to :updater, :class_name => "User" @@ -10,38 +10,38 @@ class PoolVersion < ActiveRecord::Base def for_user(user_id) where("updater_id = ?", user_id) end - + def search(params) q = scoped return q if params.blank? - + if params[:updater_id].present? q = q.for_user(params[:updater_id].to_i) end - + if params[:updater_name].present? q = q.where("updater_id = (select _.id from users _ where lower(_.name) = ?)", params[:updater_name].downcase) end - + if params[:pool_id].present? q = q.where("pool_id = ?", params[:pool_id].to_i) end - + q end end - + extend SearchMethods - + def updater_name User.id_to_name(updater_id) end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def post_id_array @post_id_array ||= post_ids.scan(/\d+/).map(&:to_i) end diff --git a/app/models/post.rb b/app/models/post.rb index bff6fec83..d7f209976 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -2,7 +2,7 @@ class Post < ActiveRecord::Base class ApprovalError < Exception ; end class DisapprovalError < Exception ; end class SearchError < Exception ; end - + attr_accessor :old_tag_string, :old_parent_id, :has_constraints after_destroy :delete_files after_destroy :delete_remote_files @@ -34,7 +34,7 @@ class Post < ActiveRecord::Base attr_accessible :source, :rating, :tag_string, :old_tag_string, :last_noted_at, :parent_id, :as => [:member, :builder, :privileged, :platinum, :contributor, :janitor, :moderator, :admin, :default] attr_accessible :is_rating_locked, :is_note_locked, :as => [:builder, :contributor, :janitor, :moderator, :admin] attr_accessible :is_status_locked, :as => [:admin] - + module FileMethods def distribute_files RemoteFileManager.new(file_path).distribute @@ -42,14 +42,14 @@ class Post < ActiveRecord::Base RemoteFileManager.new(ssd_preview_file_path).distribute if Danbooru.config.ssd_path RemoteFileManager.new(large_file_path).distribute if has_large? end - + def delete_remote_files RemoteFileManager.new(file_path).delete RemoteFileManager.new(real_preview_file_path).delete RemoteFileManager.new(ssd_preview_file_path).delete if Danbooru.config.ssd_path RemoteFileManager.new(large_file_path).delete if has_large? end - + def delete_files FileUtils.rm_f(file_path) FileUtils.rm_f(large_file_path) @@ -60,11 +60,11 @@ class Post < ActiveRecord::Base def file_path_prefix Rails.env == "test" ? "test." : "" end - + def file_path "#{Rails.root}/public/data/#{file_path_prefix}#{md5}.#{file_ext}" end - + def large_file_path if has_large? "#{Rails.root}/public/data/sample/#{file_path_prefix}#{Danbooru.config.large_image_prefix}#{md5}.jpg" @@ -72,11 +72,11 @@ class Post < ActiveRecord::Base file_path end end - + def real_preview_file_path "#{Rails.root}/public/data/preview/#{file_path_prefix}#{md5}.jpg" end - + def ssd_preview_file_path "#{Danbooru.config.ssd_path}/public/data/preview/#{file_path_prefix}#{md5}.jpg" end @@ -92,7 +92,7 @@ class Post < ActiveRecord::Base def file_url "/data/#{file_path_prefix}#{md5}.#{file_ext}" end - + def large_file_url if has_large? "/data/sample/#{file_path_prefix}#{Danbooru.config.large_image_prefix}#{md5}.jpg" @@ -105,14 +105,14 @@ class Post < ActiveRecord::Base if !is_image? return "/images/download-preview.png" end - + if Danbooru.config.ssd_path "/ssd/data/preview/#{file_path_prefix}#{md5}.jpg" else "/data/preview/#{file_path_prefix}#{md5}.jpg" end end - + def file_url_for(user) case user.default_image_size when "large" @@ -121,12 +121,12 @@ class Post < ActiveRecord::Base else file_url end - + else file_url end end - + def file_path_for(user) case user.default_image_size when "large" @@ -135,34 +135,34 @@ class Post < ActiveRecord::Base else file_path end - + else file_path end end - + def is_image? file_ext =~ /jpg|jpeg|gif|png/ end - + def is_flash? file_ext =~ /swf/ end end - + module ImageMethods def has_large? image_width.present? && image_width > Danbooru.config.large_image_width end - + def has_large has_large? end - + def large_image_width [Danbooru.config.large_image_width, image_width].min end - + def large_image_height ratio = Danbooru.config.large_image_width.to_f / image_width.to_f if ratio < 1 @@ -171,58 +171,58 @@ class Post < ActiveRecord::Base image_height end end - + def image_width_for(user) case user.default_image_size when "large" large_image_width - + else image_width end end - + def image_height_for(user) case user.default_image_size when "large" large_image_height - + else image_height end end - + def resize_percentage 100 * large_image_width.to_f / image_width.to_f end end - + module ApprovalMethods def is_approvable? !is_status_locked? && (is_pending? || is_flagged? || is_deleted?) && approver_id != CurrentUser.id end - + def flag!(reason) if is_status_locked? raise PostFlag::Error.new("Post is locked and cannot be flagged") end - + flag = flags.create(:reason => reason, :is_resolved => false) - + if flag.errors.any? raise PostFlag::Error.new(flag.errors.full_messages.join("; ")) end update_column(:is_flagged, true) unless is_flagged? end - + def appeal!(reason) if is_status_locked? raise PostAppeal::Error.new("Post is locked and cannot be appealed") end - + appeal = appeals.create(:reason => reason) - + if appeal.errors.any? raise PostAppeal::Error.new(appeal.errors.full_messages.join("; ")) end @@ -233,17 +233,17 @@ class Post < ActiveRecord::Base errors.add(:is_status_locked, "; post cannot be approved") raise ApprovalError.new("Post is locked and cannot be approved") end - + if uploader_id == CurrentUser.id errors.add(:base, "You cannot approve a post you uploaded") raise ApprovalError.new("You cannot approve a post you uploaded") end - + if approver_id == CurrentUser.id errors.add(:approver, "have already approved this post") - raise ApprovalError.new("You have previously approved this post and cannot approve it again") + raise ApprovalError.new("You have previously approved this post and cannot approve it again") end - + flags.each {|x| x.resolve!} self.is_flagged = false self.is_pending = false @@ -252,12 +252,12 @@ class Post < ActiveRecord::Base save! # ModAction.create(:description => "approved post ##{id}") end - + def disapproved_by?(user) PostDisapproval.where(:user_id => user.id, :post_id => id).exists? end end - + module PresenterMethods def presenter @presenter ||= PostPresenter.new(self) @@ -267,15 +267,15 @@ class Post < ActiveRecord::Base case rating when "q" "Questionable" - + when "e" "Explicit" - + when "s" "Safe" end end - + def normalized_source if source =~ /pixiv\.net\/img/ img_id = source[/(\d+)(_s|_m|(_big)?_p\d+)?\.[\w\?]+\s*$/, 1] @@ -290,28 +290,28 @@ class Post < ActiveRecord::Base end end end - + module TagMethods def tag_array @tag_array ||= Tag.scan_tags(tag_string) end - + def tag_array_was @tag_array_was ||= Tag.scan_tags(tag_string_was) end - + def create_tags set_tag_string(tag_array.map {|x| Tag.find_or_create_by_name(x).name}.uniq.sort.join(" ")) end - + def increment_tag_post_counts execute_sql("UPDATE tags SET post_count = post_count + 1 WHERE name IN (?)", tag_array) if tag_array.any? end - + def decrement_tag_post_counts execute_sql("UPDATE tags SET post_count = post_count - 1 WHERE name IN (?)", tag_array) if tag_array.any? end - + def update_tag_post_counts decrement_tags = tag_array_was - tag_array increment_tags = tag_array - tag_array_was @@ -321,55 +321,55 @@ class Post < ActiveRecord::Base Post.expire_cache_for_all(increment_tags) Post.expire_cache_for_all([""]) if new_record? || id <= 100_000 end - + def set_tag_counts self.tag_count = 0 self.tag_count_general = 0 self.tag_count_artist = 0 self.tag_count_copyright = 0 self.tag_count_character = 0 - + categories = Tag.categories_for(tag_array) categories.each_value do |category| self.tag_count += 1 - + case category when Tag.categories.general self.tag_count_general += 1 - + when Tag.categories.artist self.tag_count_artist += 1 - + when Tag.categories.copyright self.tag_count_copyright += 1 - + when Tag.categories.character self.tag_count_character += 1 end end end - + def merge_old_tags 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() - old_tags = Tag.scan_tags(old_tag_string) + old_tags = Tag.scan_tags(old_tag_string) set_tag_string(((current_tags + new_tags) - old_tags + (current_tags & new_tags)).uniq.sort.join(" ")) end end - + def reset_tag_array_cache @tag_array = nil @tag_array_was = nil end - + def set_tag_string(string) self.tag_string = string reset_tag_array_cache end - + def normalize_tags normalized_tags = Tag.scan_tags(tag_string) normalized_tags = TagAlias.to_aliased(normalized_tags) @@ -379,52 +379,52 @@ class Post < ActiveRecord::Base normalized_tags.sort! set_tag_string(normalized_tags.uniq.sort.join(" ")) end - + def filter_metatags(tags) @pre_metatags, tags = tags.partition {|x| x =~ /\A(?:rating|parent):/} @post_metatags, tags = tags.partition {|x| x =~ /\A(?:-pool|pool|fav):/} apply_pre_metatags return tags end - + def apply_post_metatags return unless @post_metatags - + @post_metatags.each do |tag| case tag when /^-pool:(\d+)$/ pool = Pool.find_by_id($1.to_i) remove_pool!(pool) if pool - + when /^-pool:(.+)$/ pool = Pool.find_by_name($1) remove_pool!(pool) if pool - + when /^pool:(\d+)$/ pool = Pool.find_by_id($1.to_i) add_pool!(pool) if pool - + when /^pool:(.+)$/ pool = Pool.find_by_name($1) if pool.nil? pool = Pool.create(:name => $1, :description => "This pool was automatically generated") end add_pool!(pool) if pool - + when /^fav:(.+)$/ add_favorite!(CurrentUser.user) end end end - + def apply_pre_metatags return unless @pre_metatags - + @pre_metatags.each do |tag| case tag when /^parent:none$/, /^parent:0$/ self.parent_id = nil - + when /^parent:(\d+)$/ self.parent_id = $1.to_i @@ -433,31 +433,31 @@ class Post < ActiveRecord::Base end end end - + def has_tag?(tag) tag_string =~ /(?:^| )#{tag}(?:$| )/ end - + def has_dup_tag? has_tag?("duplicate") ? true : false end - + def tag_categories @tag_categories ||= Tag.categories_for(tag_array) end - + def copyright_tags typed_tags("copyright") end - + def character_tags typed_tags("character") end - + def artist_tags typed_tags("artist") end - + def typed_tags(name) @typed_tags ||= {} @typed_tags[name] ||= begin @@ -466,7 +466,7 @@ class Post < ActiveRecord::Base end end end - + def essential_tag_string tag_array.each do |tag| if tag_categories[tag] == Danbooru.config.tag_category_mapping["copyright"] @@ -489,16 +489,16 @@ class Post < ActiveRecord::Base return tag_array.first end end - + module FavoriteMethods def favorited_by?(user_id) fav_string =~ /(?:\A| )fav:#{user_id}(?:\Z| )/ end - + def append_user_to_fav_string(user_id) update_column(:fav_string, (fav_string + " fav:#{user_id}").strip) end - + def add_favorite!(user) return if favorited_by?(user.id) append_user_to_fav_string(user.id) @@ -506,11 +506,11 @@ class Post < ActiveRecord::Base increment!(:score) if CurrentUser.is_privileged? user.add_favorite!(self) end - + def delete_user_from_fav_string(user_id) update_column(:fav_string, fav_string.gsub(/(?:\A| )fav:#{user_id}(?:\Z| )/, " ").strip) end - + def remove_favorite!(user) return unless favorited_by?(user.id) decrement!(:fav_count) @@ -518,12 +518,12 @@ class Post < ActiveRecord::Base delete_user_from_fav_string(user.id) user.remove_favorite!(self) end - + def favorited_user_ids fav_string.scan(/\d+/) end end - + module UploaderMethods def initialize_uploader if uploader_id.blank? @@ -531,12 +531,12 @@ class Post < ActiveRecord::Base self.uploader_ip_addr = CurrentUser.ip_addr end end - + def uploader_name User.id_to_name(uploader_id).tr("_", " ") end end - + module PoolMethods def pools @pools ||= begin @@ -544,18 +544,18 @@ class Post < ActiveRecord::Base Pool.where(["is_deleted = false and id in (?)", pool_ids]) end end - + def belongs_to_pool?(pool) pool_string =~ /(?:\A| )pool:#{pool.id}(?:\Z| )/ end - + def add_pool!(pool) return if belongs_to_pool?(pool) self.pool_string = "#{pool_string} pool:#{pool.id}".strip update_column(:pool_string, pool_string) unless new_record? pool.add!(self) end - + def remove_pool!(pool) return unless belongs_to_pool?(pool) self.pool_string = pool_string.gsub(/(?:\A| )pool:#{pool.id}(?:\Z| )/, " ").strip @@ -563,7 +563,7 @@ class Post < ActiveRecord::Base pool.remove!(self) end end - + module VoteMethods def can_be_voted_by?(user) !votes.exists?(["user_id = ?", user.id]) @@ -585,7 +585,7 @@ class Post < ActiveRecord::Base end end end - + module CountMethods def fix_post_counts post.set_tag_counts @@ -595,17 +595,17 @@ class Post < ActiveRecord::Base post.update_column(:tag_count_copyright, post.tag_count_copyright) post.update_column(:tag_count_character, post.tag_count_character) end - + def get_count_from_cache(tags) count = Cache.get(count_cache_key(tags)) - + if count.nil? count = select_value_sql("SELECT post_count FROM tags WHERE name = ?", tags.to_s) end - + count end - + def set_count_in_cache(tags, count, expiry = nil) if expiry.nil? if count < 100 @@ -614,14 +614,14 @@ class Post < ActiveRecord::Base expiry = (count * 4).minutes end end - + Cache.put(count_cache_key(tags), count, expiry) end - + def count_cache_key(tags) "pfc:#{Cache.sanitize(tags)}" end - + def fast_count(tags = "") tags = tags.to_s.strip @@ -633,7 +633,7 @@ class Post < ActiveRecord::Base count = fast_count_search(tags) else count = get_count_from_cache(tags) - + if count.to_i == 0 count = fast_count_search(tags) end @@ -643,7 +643,7 @@ class Post < ActiveRecord::Base rescue SearchError 0 end - + def fast_count_search(tags) count = Post.with_timeout(500, Danbooru.config.blank_tag_search_fast_count || 1_000_000) do Post.tag_match(tags).count @@ -654,19 +654,19 @@ class Post < ActiveRecord::Base count end end - + module CacheMethods def expire_cache_for_all(tag_names) Danbooru.config.all_server_hosts.each do |host| delay(:queue => host).expire_cache(tag_names) end end - + def expire_cache(tag_names) tag_names.each do |tag_name| Cache.delete(Post.count_cache_key(tag_name)) end - + if Post.fast_count("").to_i < 1000 Cache.delete(Post.count_cache_key("")) end @@ -674,7 +674,7 @@ class Post < ActiveRecord::Base end module ParentMethods - # A parent has many children. A child belongs to a parent. + # A parent has many children. A child belongs to a parent. # A parent cannot have a parent. # # After deleting a child: @@ -686,14 +686,14 @@ class Post < ActiveRecord::Base # After deleting a parent: # - Move favorites to the first child. # - Reparent all active children to the first active child. - + module ClassMethods def update_has_children_flag_for(post_id) return if post_id.nil? has_children = Post.exists?(["is_deleted = ? AND parent_id = ?", false, post_id]) execute_sql("UPDATE posts SET has_children = ? WHERE id = ?", has_children, post_id) end - + def recalculate_has_children_for_all_posts transaction do execute_sql("UPDATE posts SET has_children = false WHERE has_children = true") @@ -701,7 +701,7 @@ class Post < ActiveRecord::Base end end end - + def self.included(m) m.extend(ClassMethods) end @@ -712,13 +712,13 @@ class Post < ActiveRecord::Base errors.add(:parent, "can not have a parent") end end - + def update_parent_on_destroy Post.update_has_children_flag_for(id) Post.update_has_children_flag_for(parent_id) if parent_id Post.update_has_children_flag_for(parent_id_was) if parent_id_was && parent_id != parent_id_was end - + def update_children_on_destroy if children.size == 0 # do nothing @@ -741,7 +741,7 @@ class Post < ActiveRecord::Base Post.update_has_children_flag_for(parent_id) end end - + def give_favorites_to_parent return if parent.nil? @@ -753,26 +753,26 @@ class Post < ActiveRecord::Base update_column(:score, 0) end end - + module DeletionMethods def annihilate! if is_status_locked? self.errors.add(:is_status_locked, "; cannot delete post") return false end - + ModAction.create(:description => "permanently deleted post ##{id}") decrement_tag_post_counts delete!(:without_mod_action => true) destroy end - + def delete!(options = {}) if is_status_locked? self.errors.add(:is_status_locked, "; cannot delete post") return false end - + Post.transaction do update_column(:is_deleted, true) update_column(:is_pending, false) @@ -782,19 +782,19 @@ class Post < ActiveRecord::Base update_parent_on_destroy # decrement_tag_post_counts update_column(:parent_id, nil) - + unless options[:without_mod_action] ModAction.create(:description => "deleted post ##{id}") end end end - + def undelete! if is_status_locked? self.errors.add(:is_status_locked, "; cannot undelete post") return false end - + self.is_deleted = false self.approver_id = CurrentUser.id save @@ -803,7 +803,7 @@ class Post < ActiveRecord::Base ModAction.create(:description => "undeleted post ##{id}") end end - + module VersionMethods def create_version if created_at == updated_at @@ -824,31 +824,31 @@ class Post < ActiveRecord::Base ) end end - + def revert_to(target) self.tag_string = target.tags self.rating = target.rating self.source = target.source self.parent_id = target.parent_id end - + def revert_to!(target) revert_to(target) save! end end - + module NoteMethods def last_noted_at_as_integer last_noted_at.to_i end end - + module ApiMethods def hidden_attributes super + [:tag_index] end - + def serializable_hash(options = {}) options ||= {} options[:except] ||= [] @@ -860,7 +860,7 @@ class Post < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -868,7 +868,7 @@ class Post < ActiveRecord::Base options[:procs] << lambda {|options, record| options[:builder].tag!("has-large", record.has_large?, :type => "boolean")} super(options, &block) end - + def to_legacy_json return { "has_comments" => last_commented_at.present?, @@ -892,7 +892,7 @@ class Post < ActiveRecord::Base "file_url" => file_url }.to_json end - + def status if is_pending? "pending" @@ -905,44 +905,44 @@ class Post < ActiveRecord::Base end end end - + module SearchMethods def pending where("is_pending = ?", true) end - + def flagged where("is_flagged = ?", true) end - + def pending_or_flagged where("(is_pending = ? or (is_flagged = ? and id in (select _.post_id from post_flags _ where _.created_at >= ?)))", true, true, 1.week.ago) end - + def undeleted where("is_deleted = ?", false) end - + def deleted where("is_deleted = ?", true) end - + def visible(user) Danbooru.config.can_user_see_post_conditions(user) end - + def commented_before(date) where("last_commented_at < ?", date).order("last_commented_at DESC") end - + def has_notes where("last_noted_at is not null") end - + def for_user(user_id) where("uploader_id = ?", user_id) end - + def available_for_moderation(hidden) if hidden.present? where("posts.id IN (SELECT pd.post_id FROM post_disapprovals pd WHERE pd.user_id = ?)", CurrentUser.id) @@ -950,31 +950,31 @@ class Post < ActiveRecord::Base where("posts.id NOT IN (SELECT pd.post_id FROM post_disapprovals pd WHERE pd.user_id = ?)", CurrentUser.id) end end - + def hidden_from_moderation where("id IN (SELECT pd.post_id FROM post_disapprovals pd WHERE pd.user_id = ?)", CurrentUser.id) end - + def raw_tag_match(tag) where("posts.tag_index @@ to_tsquery('danbooru', E?)", tag.to_escaped_for_tsquery) end - + def tag_match(query) PostQueryBuilder.new(query).build end - + def positive where("score > 1") end - + def negative where("score < -1") end - + def updater_name_matches(name) where("updater_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def after_id(num) if num.present? where("id > ?", num.to_i).reorder("id asc") @@ -982,7 +982,7 @@ class Post < ActiveRecord::Base where("true") end end - + def before_id(num) if num.present? where("id < ?", num.to_i).reorder("id desc") @@ -990,27 +990,27 @@ class Post < ActiveRecord::Base where("true") end end - + def search(params) q = scoped return q if params.blank? - + if params[:before_id].present? q = q.before_id(params[:before_id].to_i) end - + if params[:after_id].present? q = q.after_id(params[:after_id].to_i) end - + if params[:tag_match].present? q = q.tag_match(params[:tag_match]) end - + q end end - + include FileMethods include ImageMethods include ApprovalMethods @@ -1028,7 +1028,7 @@ class Post < ActiveRecord::Base include NoteMethods include ApiMethods extend SearchMethods - + def reload(options = nil) super reset_tag_array_cache diff --git a/app/models/post_appeal.rb b/app/models/post_appeal.rb index d4999bab1..ac9986b68 100644 --- a/app/models/post_appeal.rb +++ b/app/models/post_appeal.rb @@ -1,6 +1,6 @@ class PostAppeal < ActiveRecord::Base class Error < Exception ; end - + belongs_to :creator, :class_name => "User" belongs_to :post validates_presence_of :reason, :creator_id, :creator_ip_addr @@ -8,38 +8,38 @@ class PostAppeal < ActiveRecord::Base validate :validate_creator_is_not_limited before_validation :initialize_creator, :on => :create validates_uniqueness_of :creator_id, :scope => :post_id, :message => "have already appealed this post" - + module SearchMethods def for_user(user_id) where("creator_id = ?", user_id) end - + def recent where("created_at >= ?", 1.day.ago) end - + def search(params) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.for_user(params[:creator_id].to_i) end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + q end end - + extend SearchMethods - + def validate_creator_is_not_limited if appeal_count_for_creator >= Danbooru.config.max_appeals_per_day errors[:creator] << "can appeal at most #{Danbooru.config.max_appeals_per_day} post a day" @@ -48,7 +48,7 @@ class PostAppeal < ActiveRecord::Base true end end - + def validate_post_is_inactive if !post.is_deleted? && !post.is_flagged? errors[:post] << "is active" @@ -57,12 +57,12 @@ class PostAppeal < ActiveRecord::Base true end end - + def initialize_creator self.creator_id = CurrentUser.id self.creator_ip_addr = CurrentUser.ip_addr end - + def appeal_count_for_creator PostAppeal.for_user(creator_id).recent.count end diff --git a/app/models/post_flag.rb b/app/models/post_flag.rb index 142718905..5d5aba1c2 100644 --- a/app/models/post_flag.rb +++ b/app/models/post_flag.rb @@ -1,6 +1,6 @@ class PostFlag < ActiveRecord::Base class Error < Exception ; end - + belongs_to :creator, :class_name => "User" belongs_to :post validates_presence_of :reason, :creator_id, :creator_ip_addr @@ -14,45 +14,45 @@ class PostFlag < ActiveRecord::Base def resolved where("is_resolved = ?", true) end - + def unresolved where("is_resolved = ?", false) end - + def recent where("created_at >= ?", 1.day.ago) end - + def old where("created_at <= ?", 3.days.ago) end - + def search(params) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + q end end - + extend SearchMethods - + def update_post post.update_column(:is_flagged, true) unless post.is_flagged? end - + def validate_creator_is_not_limited if CurrentUser.is_janitor? false @@ -63,7 +63,7 @@ class PostFlag < ActiveRecord::Base true end end - + def validate_post_is_active if post.is_deleted? errors[:post] << "is deleted" @@ -72,16 +72,16 @@ class PostFlag < ActiveRecord::Base true end end - + def initialize_creator self.creator_id = CurrentUser.id self.creator_ip_addr = CurrentUser.ip_addr end - + def resolve! update_column(:is_resolved, true) end - + def flag_count_for_creator PostFlag.where(:creator_id => creator_id).recent.count end diff --git a/app/models/post_version.rb b/app/models/post_version.rb index bb218d4d1..73882d9cb 100644 --- a/app/models/post_version.rb +++ b/app/models/post_version.rb @@ -2,38 +2,38 @@ class PostVersion < ActiveRecord::Base belongs_to :post belongs_to :updater, :class_name => "User" before_validation :initialize_updater - + module SearchMethods def for_user(user_id) where("updater_id = ?", user_id) end - + def updater_name(name) where("updater_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def search(params) q = scoped params = {} if params.blank? - + if params[:updater_name].present? q = q.updater_name(params[:updater_name]) end - + if params[:updater_id].present? q = q.where("updater_id = ?", params[:updater_id].to_i) end - + if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + q end end - + extend SearchMethods - + def self.create_from_post(post) if post.created_at == post.updated_at create_from_created_post(post) @@ -41,20 +41,20 @@ class PostVersion < ActiveRecord::Base create_from_updated_post(post) end end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def tag_array @tag_array ||= tags.scan(/\S+/) end - + def presenter PostVersionPresenter.new(self) end - + def reload @tag_array = nil super @@ -70,7 +70,7 @@ class PostVersion < ActiveRecord::Base end return diffs end - + def diff(version) latest_tags = post.tag_array new_tags = tag_array @@ -92,11 +92,11 @@ class PostVersion < ActiveRecord::Base :obsolete_removed_tags => old_tags & latest_tags, } end - + def previous PostVersion.where("post_id = ? and updated_at < ?", post_id, updated_at).order("updated_at desc").first end - + def truncated_source source.gsub(/^http:\/\//, "").sub(/\/.+/, "") end diff --git a/app/models/post_vote.rb b/app/models/post_vote.rb index db51f07ef..e2632e0ac 100644 --- a/app/models/post_vote.rb +++ b/app/models/post_vote.rb @@ -1,6 +1,6 @@ class PostVote < ActiveRecord::Base class Error < Exception ; end - + belongs_to :post before_validation :initialize_user, :on => :create validates_presence_of :post_id, :user_id, :score @@ -13,7 +13,7 @@ class PostVote < ActiveRecord::Base write_attribute(:score, -1) end end - + def initialize_user self.user_id = CurrentUser.user.id end diff --git a/app/models/report_mailer.rb b/app/models/report_mailer.rb index 5f8bad38b..9c2313916 100644 --- a/app/models/report_mailer.rb +++ b/app/models/report_mailer.rb @@ -1,6 +1,6 @@ class ReportMailer < ActionMailer::Base default :host => Danbooru.config.server_host, :from => Danbooru.config.contact_email, :content_type => "text/html" - + def moderator_report(email) mail(:to => email, :subject => "#{Danbooru.config.app_name} - Moderator Report") end diff --git a/app/models/tag.rb b/app/models/tag.rb index ebfb64657..9b9f4568c 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -2,7 +2,7 @@ class Tag < ActiveRecord::Base METATAGS = "-user|user|-approver|approver|-pool|pool|-fav|fav|sub|md5|-rating|rating|width|height|mpixels|score|filesize|source|id|date|order|status|tagcount|gentags|arttags|chartags|copytags|parent|pixiv" attr_accessible :category has_one :wiki_page, :foreign_key => "name", :primary_key => "title" - + module ApiMethods def to_legacy_json return { @@ -15,70 +15,70 @@ class Tag < ActiveRecord::Base }.to_json end end - + class CategoryMapping Danbooru.config.reverse_tag_category_mapping.each do |value, category| define_method(category.downcase) do value end end - + def regexp @regexp ||= Regexp.compile(Danbooru.config.tag_category_mapping.keys.sort_by {|x| -x.size}.join("|")) end - + def value_for(string) Danbooru.config.tag_category_mapping[string.to_s.downcase] || 0 end end - + module CountMethods extend ActiveSupport::Concern - + module ClassMethods def counts_for(tag_names) select_all_sql("SELECT name, post_count FROM tags WHERE name IN (?)", tag_names) end end - + def real_post_count @real_post_count ||= Post.raw_tag_match(name).count end - + def fix_post_count update_column(:post_count, real_post_count) end end - + module ViewCountMethods def increment_view_count(name) Cache.incr("tvc:#{Cache.sanitize(name)}") end end - + module CategoryMethods module ClassMethods def categories @category_mapping ||= CategoryMapping.new end - + def select_category_for(tag_name) select_value_sql("SELECT category FROM tags WHERE name = ?", tag_name).to_i end - + def category_for(tag_name) Cache.get("tc:#{Cache.sanitize(tag_name)}") do select_category_for(tag_name) end end - + def categories_for(tag_names) Cache.get_multi(tag_names, "tc") do |name| select_category_for(name) end end end - + def self.included(m) m.extend(ClassMethods) end @@ -86,16 +86,16 @@ class Tag < ActiveRecord::Base def category_name Danbooru.config.reverse_tag_category_mapping[category] end - + def update_category_cache_for_all update_category_cache Danbooru.config.other_server_hosts.each do |host| delay(:queue => host).update_category_cache end - + delay(:queue => "default").update_category_post_counts end - + def update_category_post_counts Post.raw_tag_match(name).find_each do |post| post.reload @@ -107,18 +107,18 @@ class Tag < ActiveRecord::Base post.update_column(:tag_count_character, post.tag_count_character) end end - + def update_category_cache Cache.put("tc:#{Cache.sanitize(name)}", category, 1.hour) end end - + module StatisticsMethods def trending raise NotImplementedError end end - + module NameMethods def normalize_name(name) name.downcase.tr(" ", "_").gsub(/\A[-~]+/, "").gsub(/\*/, "") @@ -138,7 +138,7 @@ class Tag < ActiveRecord::Base if tag if category category_id = categories.value_for(category) - + if category_id != tag.category tag.update_column(:category, category_id) tag.update_category_cache_for_all @@ -160,7 +160,7 @@ class Tag < ActiveRecord::Base def normalize(query) query.to_s.strip end - + def scan_query(query) normalize(query).scan(/\S+/).uniq end @@ -221,7 +221,7 @@ class Tag < ActiveRecord::Base when /\A>(.+)/ return [:gt, parse_cast($1, type)] - + when /,/ return [:in, range.split(/,/)] @@ -230,19 +230,19 @@ class Tag < ActiveRecord::Base end end - + def parse_tag(tag, output) if tag[0] == "-" && tag.size > 1 output[:exclude] << tag[1..-1].downcase - + elsif tag[0] == "~" && tag.size > 1 output[:include] << tag[1..-1].downcase - + elsif tag =~ /\*/ matches = Tag.name_matches(tag.downcase).all(:select => "name", :limit => Danbooru.config.tag_query_limit, :order => "post_count DESC").map(&:name) matches = ["~no_matches~"] if matches.empty? output[:include] += matches - + else output[:related] << tag.downcase end @@ -250,15 +250,15 @@ class Tag < ActiveRecord::Base def parse_query(query, options = {}) q = {} - + q[:tag_count] = 0 - + q[:tags] = { :related => [], :include => [], :exclude => [] } - + scan_query(query).each do |token| q[:tag_count] += 1 unless token == "status:deleted" @@ -267,25 +267,25 @@ class Tag < ActiveRecord::Base when "-user" q[:uploader_id_neg] ||= [] q[:uploader_id_neg] << User.name_to_id($2) - + when "user" q[:uploader_id] = User.name_to_id($2) q[:uploader_id] = -1 if q[:uploader_id].nil? - + when "-approver" q[:approver_id_neg] ||= [] q[:approver_id_neg] << User.name_to_id($2) - + when "approver" q[:approver_id] = User.name_to_id($2) q[:approver_id] = -1 if q[:approver_id].nil? - + when "-pool" q[:tags][:exclude] << "pool:#{Pool.name_to_id($2)}" - + when "pool" q[:tags][:related] << "pool:#{Pool.name_to_id($2)}" - + when "-fav" q[:tags][:exclude] << "fav:#{User.name_to_id($2)}" @@ -304,16 +304,16 @@ class Tag < ActiveRecord::Base when "rating" q[:rating] = $2 - + when "id" q[:post_id] = parse_helper($2) - + when "width" q[:width] = parse_helper($2) - + when "height" q[:height] = parse_helper($2) - + when "mpixels" q[:mpixels] = parse_helper($2, :float) @@ -325,13 +325,13 @@ class Tag < ActiveRecord::Base when "source" q[:source] = ($2.to_escaped_for_sql_like + "%").gsub(/%+/, '%') - + when "date" q[:date] = parse_helper($2, :date) when "tagcount" q[:post_tag_count] = parse_helper($2) - + when "gentags" q[:general_tag_count] = parse_helper($2) @@ -343,26 +343,26 @@ class Tag < ActiveRecord::Base when "copytags" q[:copyright_tag_count] = parse_helper($2) - + when "parent" q[:parent_id] = $2.to_i - + when "order" q[:order] = $2.downcase when "status" q[:status] = $2.downcase - + when "pixiv" q[:pixiv] = parse_helper($2) end - + else parse_tag(token, q[:tags]) end end - + normalize_tags_in_query(q) return q @@ -374,7 +374,7 @@ class Tag < ActiveRecord::Base query_hash[:tags][:related] = TagAlias.to_aliased(query_hash[:tags][:related]) end end - + module RelationMethods def update_related return unless should_update_related? @@ -384,13 +384,13 @@ class Tag < ActiveRecord::Base self.related_tags_updated_at = Time.now save end - + def update_related_if_outdated if should_update_related? && Delayed::Job.count < 200 - delay(:queue => "default").update_related + delay(:queue => "default").update_related end end - + def related_cache_expiry base = Math.sqrt([post_count, 0].max) if base > 24 * 7 @@ -401,21 +401,21 @@ class Tag < ActiveRecord::Base base end end - + def should_update_related? related_tags.blank? || related_tags_updated_at.blank? || related_tags_updated_at < related_cache_expiry.hours.ago end - + def related_tag_array update_related_if_outdated related_tags.to_s.split(/ /).in_groups_of(2) end end - + module SuggestionMethods def find_suggestions(query) query_tokens = query.split(/_/) - + if query_tokens.size == 2 search_for = query_tokens.reverse.join("_").to_escaped_for_sql_like else @@ -425,42 +425,42 @@ class Tag < ActiveRecord::Base Tag.where(["name LIKE ? ESCAPE E'\\\\' AND post_count > 0 AND name <> ?", search_for, query]).all(:order => "post_count DESC", :limit => 6, :select => "name").map(&:name).sort end end - + module SearchMethods def name_matches(name) where("name LIKE ? ESCAPE E'\\\\'", name.downcase.to_escaped_for_sql_like) end - + def named(name) where("name = ?", TagAlias.to_aliased([name]).join("")) end - + def search(params) q = scoped params = {} if params.blank? - + if params[:name_matches].present? q = q.name_matches(params[:name_matches].strip) end - + if params[:category].present? q = q.where("category = ?", params[:category]) end - + if params[:hide_empty].blank? || params[:hide_empty] != "no" q = q.where("post_count > 0") end - + if params[:limit].present? q = q.limit(params[:limit].to_i) end - + if params[:order] == "name" q = q.reorder("name") - + elsif params[:order] == "date" q = q.reorder("id desc") - + elsif params[:sort] == "date" q = q.reorder("id desc") @@ -470,11 +470,11 @@ class Tag < ActiveRecord::Base else q = q.reorder("post_count desc") end - + q end end - + include ApiMethods include CountMethods extend ViewCountMethods diff --git a/app/models/tag_alias.rb b/app/models/tag_alias.rb index edd99cb42..052468557 100644 --- a/app/models/tag_alias.rb +++ b/app/models/tag_alias.rb @@ -8,20 +8,20 @@ class TagAlias < ActiveRecord::Base validate :absence_of_transitive_relation belongs_to :creator, :class_name => "User" belongs_to :forum_topic - + module SearchMethods def name_matches(name) where("(antecedent_name like ? escape E'\\\\' or consequent_name like ? escape E'\\\\')", name.downcase.to_escaped_for_sql_like, name.downcase.to_escaped_for_sql_like) end - + def search(params) q = scoped return q if params.blank? - + if params[:name_matches].present? q = q.name_matches(params[:name_matches]) end - + if params[:antecedent_name].present? q = q.where("antecedent_name = ?", params[:antecedent_name]) end @@ -29,20 +29,20 @@ class TagAlias < ActiveRecord::Base if params[:id].present? q = q.where("id = ?", params[:id].to_i) end - + q end end - + module CacheMethods extend ActiveSupport::Concern - + module ClassMethods def clear_cache_for(name) Cache.delete("ta:#{Cache.sanitize(name)}") end end - + def clear_all_cache Danbooru.config.all_server_hosts.each do |host| TagAlias.delay(:queue => host).clear_cache_for(antecedent_name) @@ -50,10 +50,10 @@ class TagAlias < ActiveRecord::Base end end end - + extend SearchMethods include CacheMethods - + def self.to_aliased(names) alias_hash = Cache.get_multi(names.flatten, "ta") do |name| ta = TagAlias.find_by_antecedent_name(name) @@ -63,10 +63,10 @@ class TagAlias < ActiveRecord::Base name end end - + alias_hash.values.flatten.uniq end - + def process! update_column(:status, "processing") clear_all_cache @@ -75,28 +75,28 @@ class TagAlias < ActiveRecord::Base rescue Exception => e update_column(:status, "error: #{e}") end - + def is_pending? status == "pending" end - + def is_active? status == "active" end - + def initialize_creator self.creator_id = CurrentUser.user.id self.creator_ip_addr = CurrentUser.ip_addr end - + def antecedent_tag Tag.find_by_name(antecedent_name) end - + def consequent_tag Tag.find_by_name(consequent_name) end - + def absence_of_transitive_relation # We don't want a -> b && b -> c chains if self.class.exists?(["antecedent_name = ?", consequent_name]) || self.class.exists?(["consequent_name = ?", antecedent_name]) @@ -104,15 +104,15 @@ class TagAlias < ActiveRecord::Base false end end - + def ensure_category_consistency if antecedent_tag && consequent_tag && antecedent_tag.category != consequent_tag.category consequent_tag.update_attribute(:category, antecedent_tag.category) end - + true end - + def update_posts Post.raw_tag_match(antecedent_name).find_each do |post| escaped_antecedent_name = Regexp.escape(antecedent_name) diff --git a/app/models/tag_implication.rb b/app/models/tag_implication.rb index f5f692d43..3384386b2 100644 --- a/app/models/tag_implication.rb +++ b/app/models/tag_implication.rb @@ -6,17 +6,17 @@ class TagImplication < ActiveRecord::Base validates_presence_of :creator_id, :antecedent_name, :consequent_name validates_uniqueness_of :antecedent_name, :scope => :consequent_name validate :absence_of_circular_relation - + module DescendantMethods extend ActiveSupport::Concern - + module ClassMethods # assumes names are normalized def with_descendants(names) (names + where("antecedent_name in (?) and status = ?", names, "active").map(&:descendant_names_array)).flatten.uniq end end - + def descendants @descendants ||= begin [].tap do |all| @@ -45,7 +45,7 @@ class TagImplication < ActiveRecord::Base def update_descendant_names_for_parent p = parent - + while p p.update_descendant_names! p = p.parent @@ -56,22 +56,22 @@ class TagImplication < ActiveRecord::Base @descendants = nil end end - + module ParentMethods def parent @parent ||= self.class.where(["consequent_name = ?", antecedent_name]).first end - + def clear_parent_cache @parent = nil end end - + module SearchMethods def name_matches(name) where("(antecedent_name like ? escape E'\\\\' or consequent_name like ? escape E'\\\\')", name.downcase.to_escaped_for_sql_like, name.downcase.to_escaped_for_sql_like) end - + def search(params) q = scoped return q if params.blank? @@ -79,11 +79,11 @@ class TagImplication < ActiveRecord::Base if params[:id].present? q = q.where("id = ?", params[:id].to_i) end - + if params[:name_matches].present? q = q.name_matches(params[:name_matches]) end - + if params[:antecedent_name].present? q = q.where("antecedent_name = ?", params[:antecedent_name]) end @@ -91,16 +91,16 @@ class TagImplication < ActiveRecord::Base q end end - + include DescendantMethods include ParentMethods extend SearchMethods - + def initialize_creator self.creator_id = CurrentUser.user.id self.creator_ip_addr = CurrentUser.ip_addr end - + def process! update_column(:status, "processing") update_descendant_names_for_parent @@ -109,7 +109,7 @@ class TagImplication < ActiveRecord::Base rescue Exception => e update_column(:status, "error: #{e}") end - + def absence_of_circular_relation # We don't want a -> b && b -> a chains if self.class.exists?(["antecedent_name = ? and consequent_name = ?", consequent_name, antecedent_name]) @@ -117,7 +117,7 @@ class TagImplication < ActiveRecord::Base false end end - + def update_posts Post.tag_match("#{antecedent_name} status:any").find_each do |post| escaped_antecedent_name = Regexp.escape(antecedent_name) @@ -129,23 +129,23 @@ class TagImplication < ActiveRecord::Base end end end - + def is_pending? status == "pending" end - + def is_active? status == "active" end - + def antecedent_tag Tag.find_by_name(antecedent_name) end - + def consequent_tag Tag.find_by_name(consequent_name) end - + def reload(options = {}) super clear_parent_cache diff --git a/app/models/tag_subscription.rb b/app/models/tag_subscription.rb index e265d1525..bdf733fce 100644 --- a/app/models/tag_subscription.rb +++ b/app/models/tag_subscription.rb @@ -8,15 +8,15 @@ class TagSubscription < ActiveRecord::Base validates_presence_of :name, :tag_query, :creator_id validates_format_of :tag_query, :with => /^(?:\S+\s*){1,20}$/m, :message => "can have up to 20 tags" validate :creator_can_create_subscriptions, :on => :create - + def normalize_name self.name = name.gsub(/\s+/, "_") end - + def pretty_name name.tr("_", " ") end - + def initialize_creator self.creator_id = CurrentUser.id end @@ -24,7 +24,7 @@ class TagSubscription < ActiveRecord::Base def initialize_post_ids process end - + def creator_can_create_subscriptions if TagSubscription.owned_by(creator).count >= Danbooru.config.max_tag_subscriptions self.errors.add(:creator, "can create up to #{Danbooru.config.max_tag_subscriptions} tag subscriptions") @@ -49,38 +49,38 @@ class TagSubscription < ActiveRecord::Base end self.post_ids = post_ids.sort.reverse.slice(0, Danbooru.config.tag_subscription_post_limit).join(",") end - + def is_active? creator.last_logged_in_at && creator.last_logged_in_at > 1.year.ago end - + def editable_by?(user) user.is_moderator? || creator_id == user.id end - + def post_id_array post_ids.split(/,/) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:creator_id] q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:creator_name] q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + q end - + def self.visible_to(user) where("(is_public = TRUE OR creator_id = ? OR ?)", user.id, user.is_moderator?) end - + def self.owned_by(user) where("creator_id = ?", user.id) end @@ -95,10 +95,10 @@ class TagSubscription < ActiveRecord::Base end user = User.find_by_name(user_name) - + if user relation = where(["creator_id = ?", user.id]) - + if sub_group relation = relation.where(["name ILIKE ? ESCAPE E'\\\\'", sub_group.to_escaped_for_sql_like]) end @@ -106,16 +106,16 @@ class TagSubscription < ActiveRecord::Base relation.map {|x| x.tag_query.split(/ /)}.flatten else [] - end + end end def self.find_post_ids(user_id, name = nil, limit = Danbooru.config.tag_subscription_post_limit) relation = where("creator_id = ?", user_id) - + if name relation = relation.where("lower(name) LIKE ? ESCAPE E'\\\\'", name.downcase.to_escaped_for_sql_like) end - + relation.each do |tag_sub| tag_sub.update_column(:last_accessed_at, Time.now) end diff --git a/app/models/upload.rb b/app/models/upload.rb index 9fe0c2e55..d162de1a0 100644 --- a/app/models/upload.rb +++ b/app/models/upload.rb @@ -3,7 +3,7 @@ require "tmpdir" class Upload < ActiveRecord::Base class Error < Exception ; end - + attr_accessor :file, :image_width, :image_height, :file_ext, :md5, :file_size belongs_to :uploader, :class_name => "User" belongs_to :post @@ -13,7 +13,7 @@ class Upload < ActiveRecord::Base after_destroy :delete_temp_file validate :uploader_is_not_limited validate :file_or_source_is_present, :on => :create - + module ValidationMethods def uploader_is_not_limited if !uploader.can_upload? @@ -37,34 +37,34 @@ class Upload < ActiveRecord::Base def validate_md5_uniqueness md5_post = Post.find_by_md5(md5) if md5_post - merge_tags(md5_post) + merge_tags(md5_post) raise "duplicate: #{md5_post.id}" end end - + def validate_file_exists unless file_path && File.exists?(file_path) raise "file does not exist" end end - + def validate_file_content_type unless is_valid_content_type? raise "invalid content type (#{file_ext} not allowed)" end end - + def validate_md5_confirmation if !md5_confirmation.blank? && md5_confirmation != md5 raise "md5 mismatch" end end end - + module ConversionMethods def process! force=false return if !force && status =~ /processing|completed|error/ - + CurrentUser.scoped(uploader, uploader_ip_addr) do update_attribute(:status, "processing") if is_downloadable? @@ -79,7 +79,7 @@ class Upload < ActiveRecord::Base calculate_file_size(file_path) add_file_size_tags!(file_path) if has_dimensions? - calculate_dimensions(file_path) + calculate_dimensions(file_path) add_dimension_tags! end generate_resizes(file_path) @@ -118,18 +118,18 @@ class Upload < ActiveRecord::Base end end end - + def merge_tags(post) post.tag_string += " #{tag_string}" post.save end end - + module FileMethods def delete_temp_file FileUtils.rm_f(temp_file_path) end - + def move_file FileUtils.mv(file_path, md5_file_path) end @@ -142,7 +142,7 @@ class Upload < ActiveRecord::Base def calculate_hash(source_path) self.md5 = Digest::MD5.file(source_path).hexdigest end - + def is_image? ["jpg", "gif", "png"].include?(file_ext) end @@ -176,10 +176,10 @@ class Upload < ActiveRecord::Base self.image_width = image_size.get_width self.image_height = image_size.get_height end - + def add_dimension_tags! return if !Danbooru.config.enable_dimension_autotagging - + if image_width >= 10_000 || image_height >= 10_000 self.tag_string = "#{tag_string} incredibly_absurdres".strip elsif image_width >= 3200 || image_height >= 2400 @@ -190,37 +190,37 @@ class Upload < ActiveRecord::Base self.tag_string = "#{tag_string} lowres".strip end end - + # Does this file have image dimensions? def has_dimensions? %w(jpg gif png swf).include?(file_ext) end end - + module ContentTypeMethods def is_valid_content_type? file_ext =~ /jpg|gif|png|swf/ end - + def content_type_to_file_ext(content_type) case content_type when "image/jpeg" "jpg" - + when "image/gif" "gif" - + when "image/png" "png" - + when "application/x-shockwave-flash" "swf" - + else "bin" end end - + # Converts a content type string to a file extension def file_ext_to_content_type(file_ext) case file_ext @@ -247,12 +247,12 @@ class Upload < ActiveRecord::Base prefix = Rails.env == "test" ? "test." : "" "#{Rails.root}/public/data/#{prefix}#{md5}.#{file_ext}" end - + def ssd_file_path prefix = Rails.env == "test" ? "test." : "" "#{Danbooru.config.ssd_path}/public/data/preview/#{prefix}#{md5}.jpg" end - + def resized_file_path_for(width) prefix = Rails.env == "test" ? "test." : "" @@ -264,12 +264,12 @@ class Upload < ActiveRecord::Base "#{Rails.root}/public/data/sample/#{Danbooru.config.large_image_prefix}#{prefix}#{md5}.jpg" end end - + def temp_file_path @temp_file_path ||= File.join(Rails.root, "tmp", "upload_#{Time.now.to_f}.#{Process.pid}") end end - + module DownloaderMethods # Determines whether the source is downloadable def is_downloadable? @@ -296,7 +296,7 @@ class Upload < ActiveRecord::Base if file.respond_to?(:tempfile) && file.tempfile FileUtils.cp(file.tempfile.path, file_path) else - File.open(file_path, 'wb') do |out| + File.open(file_path, 'wb') do |out| out.write(file.read) end end @@ -305,69 +305,69 @@ class Upload < ActiveRecord::Base self.file_ext = content_type_to_file_ext(content_type) end end - + module StatusMethods def initialize_status self.status = "pending" end - + def is_pending? status == "pending" end - + def is_processing? status == "processing" end - + def is_completed? status == "completed" end - + def is_duplicate? status =~ /duplicate/ end - + def duplicate_post_id @duplicate_post_id ||= status[/duplicate: (\d+)/, 1] end end - + module UploaderMethods def initialize_uploader self.uploader_id = CurrentUser.user.id self.uploader_ip_addr = CurrentUser.ip_addr end end - + module SearchMethods def uploaded_by(user_id) where("uploader_id = ?", user_id) end - + def pending where(:status => "pending") end - + def search(params) q = scoped return q if params.blank? - + if params[:uploader_id].present? q = q.uploaded_by(params[:uploader_id].to_i) end - + if params[:uploader_name].present? q = q.where("uploader_id = (select _.id from users _ where lower(_.name) = ?)", params[:uploader_name].downcase) end - + if params[:source].present? q = q.where("source = ?", params[:source]) end - + q end end - + module ApiMethods def serializable_hash(options = {}) options ||= {} @@ -380,7 +380,7 @@ class Upload < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -388,7 +388,7 @@ class Upload < ActiveRecord::Base super(options, &block) end end - + include ConversionMethods include ValidationMethods include FileMethods @@ -402,17 +402,17 @@ class Upload < ActiveRecord::Base include UploaderMethods extend SearchMethods include ApiMethods - + def add_file_size_tags!(file_path) if file_size >= 10.megabytes self.tag_string = "#{tag_string} huge_filesize".strip end end - + def uploader_name User.id_to_name(uploader_id) end - + def presenter @presenter ||= UploadPresenter.new(self) end diff --git a/app/models/user.rb b/app/models/user.rb index 5195d5617..7b30bc4d4 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -3,7 +3,7 @@ require 'digest/sha1' class User < ActiveRecord::Base class Error < Exception ; end class PrivilegeError < Exception ; end - + module Levels BLOCKED = 10 MEMBER = 20 @@ -15,7 +15,7 @@ class User < ActiveRecord::Base MODERATOR = 40 ADMIN = 50 end - + attr_accessor :password, :old_password attr_accessible :enable_privacy_mode, :enable_post_navigation, :new_post_navigation_layout, :password, :old_password, :password_confirmation, :password_hash, :email, :last_logged_in_at, :last_forum_read_at, :has_mail, :receive_email_notifications, :comment_threshold, :always_resize_images, :favorite_tags, :blacklisted_tags, :name, :ip_addr, :time_zone, :default_image_size, :enable_sequential_post_navigation, :as => [:moderator, :janitor, :contributor, :privileged, :member, :anonymous, :default, :builder, :admin] attr_accessible :level, :as => :admin @@ -44,7 +44,7 @@ class User < ActiveRecord::Base has_many :dmails, :foreign_key => "owner_id", :order => "dmails.id desc" belongs_to :inviter, :class_name => "User" after_update :create_mod_action - + module BanMethods def validate_ip_addr_is_not_banned if IpBan.is_banned?(CurrentUser.ip_addr) @@ -52,13 +52,13 @@ class User < ActiveRecord::Base return false end end - + def unban! update_column(:is_banned, false) ban.destroy end end - + module InvitationMethods def invite!(level) if level.to_i <= Levels::CONTRIBUTOR @@ -68,40 +68,40 @@ class User < ActiveRecord::Base end end end - + module NameMethods extend ActiveSupport::Concern - + module ClassMethods def name_to_id(name) Cache.get("uni:#{Cache.sanitize(name)}", 4.hours) do select_value_sql("SELECT id FROM users WHERE lower(name) = ?", name.mb_chars.downcase) end end - + def id_to_name(user_id) Cache.get("uin:#{user_id}", 4.hours) do select_value_sql("SELECT name FROM users WHERE id = ?", user_id) || Danbooru.config.default_guest_name end end - + def find_by_name(name) where("lower(name) = ?", name.mb_chars.downcase.tr(" ", "_")).first end - + def id_to_pretty_name(user_id) id_to_name(user_id).tr("_", " ") end end - + def pretty_name name.tr("_", " ") end - + def update_cache Cache.put("uin:#{id}", name) end - + def update_remote_cache if name_changed? Danbooru.config.other_server_hosts.each do |server| @@ -111,7 +111,7 @@ class User < ActiveRecord::Base rescue Exception # swallow, since it'll be expired eventually anyway end - + def validate_feedback_on_name_change if feedback.negative.count > 0 && name_changed? self.errors[:base] << "You can not change your name if you have any negative feedback" @@ -119,12 +119,12 @@ class User < ActiveRecord::Base end end end - + module PasswordMethods def bcrypt_password BCrypt::Password.new(bcrypt_password_hash) end - + def bcrypt_cookie_password_hash bcrypt_password_hash.slice(20, 100) end @@ -133,11 +133,11 @@ class User < ActiveRecord::Base self.password_hash = "" self.bcrypt_password_hash = User.bcrypt(password) end - + def encrypt_password_on_update return if password.blank? return if old_password.blank? - + if bcrypt_password == User.sha1(old_password) self.bcrypt_password_hash = User.bcrypt(password) return true @@ -159,18 +159,18 @@ class User < ActiveRecord::Base pass << rand(100).to_s update_column(:bcrypt_password_hash, User.bcrypt(pass)) - pass + pass end - + def reset_password_and_deliver_notice new_password = reset_password() Maintenance::User::PasswordResetMailer.confirmation(self, new_password).deliver end end - + module AuthenticationMethods extend ActiveSupport::Concern - + module ClassMethods def authenticate(name, pass) authenticate_hash(name, sha1(pass)) @@ -193,7 +193,7 @@ class User < ActiveRecord::Base nil end end - + def bcrypt(pass) BCrypt::Password.create(sha1(pass)) end @@ -203,19 +203,19 @@ class User < ActiveRecord::Base end end end - + module FavoriteMethods def favorites Favorite.where("user_id % 100 = #{id % 100} and user_id = #{id}").order("id desc") end - + def add_favorite!(post) return if Favorite.for_user(id).exists?(:user_id => id, :post_id => post.id) Favorite.create(:user_id => id, :post_id => post.id) increment!(:favorite_count) post.add_favorite!(self) end - + def remove_favorite!(post) return unless Favorite.for_user(id).exists?(:user_id => id, :post_id => post.id) Favorite.destroy_all(:user_id => id, :post_id => post.id) @@ -223,10 +223,10 @@ class User < ActiveRecord::Base post.remove_favorite!(self) end end - + module LevelMethods extend ActiveSupport::Concern - + module ClassMethods def level_hash return { @@ -241,68 +241,68 @@ class User < ActiveRecord::Base } end end - + def promote_to_admin_if_first_user return if Rails.env.test? - + if User.count == 0 self.level = Levels::ADMIN else self.level = Levels::MEMBER end end - + def role case level when Levels::MEMBER :member - + when Levels::PRIVILEGED :privileged - + when Levels::BUILDER :builder - + when Levels::CONTRIBUTOR :contributor - + when Levels::MODERATOR :moderator when Levels::JANITOR :janitor - + when Levels::ADMIN :admin end end - + def level_string(value = nil) case (value || level) when Levels::BLOCKED "Banned" - + when Levels::MEMBER "Member" - + when Levels::BUILDER "Builder" - + when Levels::PRIVILEGED "Gold" - + when Levels::PLATINUM "Platinum" - + when Levels::CONTRIBUTOR "Contributor" - + when Levels::JANITOR "Janitor" - + when Levels::MODERATOR "Moderator" - + when Levels::ADMIN "Admin" end @@ -315,55 +315,55 @@ class User < ActiveRecord::Base def is_member? true end - + def is_builder? level >= Levels::BUILDER end - + def is_privileged? level >= Levels::PRIVILEGED end - + def is_platinum? level >= Levels::PLATINUM end - + def is_contributor? level >= Levels::CONTRIBUTOR end - + def is_janitor? level >= Levels::JANITOR end - + def is_moderator? level >= Levels::MODERATOR end - + def is_mod? level >= Levels::MODERATOR end - + def is_admin? level >= Levels::ADMIN end - + def create_mod_action if level_changed? ModAction.create(:description => "#{name} level changed #{level_string(level_was)} -> #{level_string} by #{CurrentUser.name}") end end end - + module EmailMethods def is_verified? email_verification_key.blank? end - + def generate_email_verification_key self.email_verification_key = Digest::SHA1.hexdigest("#{Time.now.to_f}--#{name}--#{rand(1_000_000)}--") end - + def verify!(key) if email_verification_key == key self.update_column(:email_verification_key, nil) @@ -372,17 +372,17 @@ class User < ActiveRecord::Base end end end - + module BlacklistMethods def blacklisted_tag_array Tag.scan_query(blacklisted_tags) end - + def normalize_blacklisted_tags self.blacklisted_tags = blacklisted_tags.downcase if blacklisted_tags.present? end end - + module ForumMethods def has_forum_been_updated? return false unless is_privileged? @@ -392,7 +392,7 @@ class User < ActiveRecord::Base return newest_topic.updated_at > last_forum_read_at end end - + module LimitMethods def can_upload? if is_contributor? @@ -403,7 +403,7 @@ class User < ActiveRecord::Base upload_limit > 0 end end - + def upload_limited_reason if created_at > 1.week.ago "You cannot upload during your first week of registration" @@ -413,7 +413,7 @@ class User < ActiveRecord::Base nil end end - + def can_comment? if is_privileged? true @@ -423,33 +423,33 @@ class User < ActiveRecord::Base Comment.where("creator_id = ? and created_at > ?", id, 1.hour.ago).count < Danbooru.config.member_comment_limit end end - + def can_comment_vote? CommentVote.where("user_id = ? and created_at > ?", id, 1.hour.ago).count < 10 end - + def can_remove_from_pools? created_at <= 1.week.ago end - + def upload_limit deleted_count = Post.for_user(id).deleted.count pending_count = Post.for_user(id).pending.count approved_count = Post.where("is_flagged = false and is_pending = false and is_deleted = false and uploader_id = ?", id).count - + if base_upload_limit limit = base_upload_limit - pending_count else limit = 10 + (approved_count / 10) - (deleted_count / 4) - pending_count end - + if limit < 0 limit = 0 end - + limit end - + def tag_query_limit if is_platinum? Danbooru.config.base_tag_query_limit * 2 @@ -459,7 +459,7 @@ class User < ActiveRecord::Base 2 end end - + def favorite_limit if is_platinum? nil @@ -470,19 +470,19 @@ class User < ActiveRecord::Base end end end - + module ApiMethods def hidden_attributes super + [:password_hash, :bcrypt_password_hash, :email, :email_verification_key, :time_zone, :created_at, :updated_at, :receive_email_notifications, :last_logged_in_at, :last_forum_read_at, :has_mail, :default_image_size, :comment_threshold, :always_resize_images, :favorite_tags, :blacklisted_tags, :base_upload_limit, :recent_tags, :enable_privacy_mode, :enable_post_navigation, :new_post_navigation_layout] end - + def serializable_hash(options = {}) options ||= {} options[:except] ||= [] options[:except] += hidden_attributes super(options) end - + def to_xml(options = {}, &block) # to_xml ignores the serializable_hash method options ||= {} @@ -500,48 +500,48 @@ class User < ActiveRecord::Base }.to_json end end - + module SearchMethods def named(name) where("lower(name) = ?", name) end - + def name_matches(name) where("lower(name) like ? escape E'\\\\'", name.to_escaped_for_sql_like) end - + def admins where("is_admin = TRUE") end - + def with_email(email) - if email.blank? + if email.blank? where("FALSE") - else + else where("email = ?", email) end end - + def find_for_password_reset(name, email) - if email.blank? + if email.blank? where("FALSE") else where(["name = ? AND email = ?", name, email]) end end - + def search(params) q = scoped return q if params.blank? - + if params[:name].present? q = q.name_matches(params[:name].mb_chars.downcase) end - + if params[:name_matches].present? q = q.name_matches(params[:name_matches].mb_chars.downcase) end - + if params[:min_level].present? q = q.where("level >= ?", params[:min_level].to_i) end @@ -549,32 +549,32 @@ class User < ActiveRecord::Base if params[:level].present? q = q.where("level = ?", params[:level].to_i) end - + if params[:id].present? q = q.where("id = ?", params[:id].to_i) end - + case params[:order] when "name" q = q.order("name") - + when "post_upload_count" q = q.order("post_upload_count desc") - + when "note_count" q = q.order("note_update_count desc") - - when "post_update_count" + + when "post_update_count" q = q.order("post_update_count desc") - + else q = q.order("created_at desc") end - + q end end - + include BanMethods include NameMethods include PasswordMethods @@ -588,7 +588,7 @@ class User < ActiveRecord::Base include InvitationMethods include ApiMethods extend SearchMethods - + def initialize_default_image_size self.default_image_size = "large" end @@ -596,7 +596,7 @@ class User < ActiveRecord::Base def can_update?(object, foreign_key = :user_id) is_moderator? || is_admin? || object.__send__(foreign_key) == id end - + def dmail_count if has_mail? "(#{dmails.unread.count})" diff --git a/app/models/user_feedback.rb b/app/models/user_feedback.rb index cc3eb45cf..f758948e8 100644 --- a/app/models/user_feedback.rb +++ b/app/models/user_feedback.rb @@ -12,31 +12,31 @@ class UserFeedback < ActiveRecord::Base def positive where("category = ?", "positive") end - + def neutral where("category = ?", "neutral") end - + def negative where("category = ?", "negative") end - + def for_user(user_id) where("user_id = ?", user_id) end - + def search(params) q = scoped return q if params.blank? - + if params[:user_id].present? q = q.for_user(params[:user_id].to_i) end - + if params[:user_name].present? q = q.where("user_id = (select _.id from users _ where lower(_.name) = ?)", params[:user_name].downcase) end - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end @@ -44,34 +44,34 @@ class UserFeedback < ActiveRecord::Base if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + q end end - + extend SearchMethods - + def initialize_creator self.creator_id = CurrentUser.id end - + def user_name User.id_to_name(user_id) end - + def creator_name User.id_to_name(creator_id) end - + def user_name=(name) self.user_id = User.name_to_id(name) end - + def create_dmail body = %{#{creator_name} created a "#{category} record":/user_feedbacks?search[user_id]=#{user_id} for your account. #{body}} Dmail.create_split(:to_id => user_id, :title => "Your user record has been updated", :body => body) end - + def creator_is_privileged if !creator.is_privileged? errors[:creator] << "must be privileged" diff --git a/app/models/user_password_reset_nonce.rb b/app/models/user_password_reset_nonce.rb index d54b9c52e..74dba55c4 100644 --- a/app/models/user_password_reset_nonce.rb +++ b/app/models/user_password_reset_nonce.rb @@ -15,18 +15,18 @@ class UserPasswordResetNonce < ActiveRecord::Base def initialize_key self.key = SecureRandom.hex(16) end - + def validate_existence_of_email if !User.with_email(email).exists? errors[:email] << "is invalid" return false end end - + def reset_user! user.reset_password_and_deliver_notice end - + def user @user ||= User.with_email(email).first end diff --git a/app/models/wiki_page.rb b/app/models/wiki_page.rb index d20760dcd..40a6b2fc5 100644 --- a/app/models/wiki_page.rb +++ b/app/models/wiki_page.rb @@ -10,16 +10,16 @@ class WikiPage < ActiveRecord::Base has_one :tag, :foreign_key => "name", :primary_key => "title" has_one :artist, :foreign_key => "name", :primary_key => "title" has_many :versions, :class_name => "WikiPageVersion", :dependent => :destroy, :order => "wiki_page_versions.id ASC" - + module SearchMethods def titled(title) where("title = ?", title.downcase.tr(" ", "_")) end - + def recent order("updated_at DESC").limit(25) end - + def body_matches(query) where("body_index @@ plainto_tsquery(?)", query.to_escaped_for_tsquery_split) end @@ -35,15 +35,15 @@ class WikiPage < ActiveRecord::Base if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id]) end - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:sort] == "time" || params[:sort] == "Date" q = q.order("updated_at desc") end @@ -51,7 +51,7 @@ class WikiPage < ActiveRecord::Base q end end - + module ApiMethods def serializable_hash(options = {}) options ||= {} @@ -64,7 +64,7 @@ class WikiPage < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -72,27 +72,27 @@ class WikiPage < ActiveRecord::Base super(options, &block) end end - + extend SearchMethods include ApiMethods - + def self.find_title_and_id(title) titled(title).select("title, id").first end - + def validate_locker_is_janitor if is_locked_changed? && !CurrentUser.is_janitor? errors.add(:is_locked, "can be modified by janitors only") return false end end - + def revert_to(version) self.title = version.title self.body = version.body self.is_locked = version.is_locked end - + def revert_to!(version) revert_to(version) save! @@ -105,7 +105,7 @@ class WikiPage < ActiveRecord::Base def creator_name User.id_to_name(creator_id).tr("_", " ") end - + def category_name Tag.category_for(title) end @@ -113,7 +113,7 @@ class WikiPage < ActiveRecord::Base def pretty_title title.tr("_", " ") end - + def create_version if title_changed? || body_changed? || is_locked_changed? versions.create( @@ -125,19 +125,19 @@ class WikiPage < ActiveRecord::Base ) end end - + def initialize_creator self.creator_id = CurrentUser.user.id end - + def post_set @post_set ||= PostSets::WikiPage.new(title, 1, 4) end - + def presenter @presenter ||= WikiPagePresenter.new(self) end - + def tags body.scan(/\[\[(.+?)\]\]/).flatten.map do |match| if match =~ /^(.+?)\|(.+)/ diff --git a/app/models/wiki_page_version.rb b/app/models/wiki_page_version.rb index 003e61439..c39f1c258 100644 --- a/app/models/wiki_page_version.rb +++ b/app/models/wiki_page_version.rb @@ -6,25 +6,25 @@ class WikiPageVersion < ActiveRecord::Base def for_user(user_id) where("updater_id = ?", user_id) end - + def search(params) q = scoped return q if params.blank? - + if params[:updater_id].present? q = q.for_user(params[:updater_id].to_i) end - + if params[:wiki_page_id].present? q = q.where("wiki_page_id = ?", params[:wiki_page_id].to_i) end - + q end end - + extend SearchMethods - + def updater_name User.id_to_name(updater_id) end diff --git a/app/presenters/forum_topic_presenter.rb b/app/presenters/forum_topic_presenter.rb index a10593cbc..fd38877d5 100644 --- a/app/presenters/forum_topic_presenter.rb +++ b/app/presenters/forum_topic_presenter.rb @@ -1,6 +1,6 @@ class ForumTopicPresenter < Presenter attr_reader :forum_topic, :forum_posts - + def initialize(forum_topic, forum_posts) @forum_posts = forum_posts @forum_topic = forum_topic diff --git a/app/presenters/note_presenter.rb b/app/presenters/note_presenter.rb index 010c2524c..f30297982 100644 --- a/app/presenters/note_presenter.rb +++ b/app/presenters/note_presenter.rb @@ -2,8 +2,8 @@ class NotePresenter def initialize(note) @note = note end - + def formatted_body - note.body.gsub(/(.+?)<\/tn>/m, ' \1
').gsub(/\n/, '
') + note.body.gsub(/(.+?)<\/tn>/m, ' \1
').gsub(/\n/, '
') end end diff --git a/app/presenters/post_presenter.rb b/app/presenters/post_presenter.rb index dc51bc6b4..0a37a5c86 100644 --- a/app/presenters/post_presenter.rb +++ b/app/presenters/post_presenter.rb @@ -3,18 +3,18 @@ class PostPresenter < Presenter if post.is_deleted? && !CurrentUser.is_privileged? return "" end - + unless Danbooru.config.can_user_see_post?(CurrentUser.user, post) return "" end - + flags = [] flags << "pending" if post.is_pending? flags << "flagged" if post.is_flagged? flags << "deleted" if post.is_deleted? - + path = options[:path_prefix] || "/posts" - + html = %{} if options[:tags].present? tag_param = "?tags=#{CGI::escape(options[:tags])}" @@ -29,43 +29,43 @@ class PostPresenter < Presenter html << %{ } html.html_safe end - + def initialize(post) @post = post end - + def preview_html PostPresenter.preview(@post) end - + def humanized_tag_string @post.tag_string.split(/ /).slice(0, 25).join(", ").tr("_", " ") end - + def humanized_essential_tag_string string = [] - + if @post.character_tags.any? string << @post.character_tags.slice(0, 5).to_sentence end - + if @post.copyright_tags.any? string << "from" string << @post.copyright_tags.slice(0, 5).to_sentence end - + if @post.artist_tags.any? string << "drawn by" string << @post.artist_tags.to_sentence end - + string.join(" ").tr("_", " ") end - + def image_html(template) return template.content_tag("p", "This image was deleted.") if @post.is_deleted? && !CurrentUser.user.is_privileged? return template.content_tag("p", "You need a privileged account to see this image.") if !Danbooru.config.can_user_see_post?(CurrentUser.user, @post) - + if @post.is_flash? template.render("posts/partials/show/flash", :post => @post) elsif !@post.is_image? @@ -74,21 +74,21 @@ class PostPresenter < Presenter template.render("posts/partials/show/image", :post => @post) end end - + def tag_list_html(template, options = {}) @tag_set_presenter ||= TagSetPresenter.new(@post.tag_array) @tag_set_presenter.tag_list_html(template, options.merge(:show_extra_links => CurrentUser.user.is_privileged?)) end - + def split_tag_list_html(template, options = {}) @tag_set_presenter ||= TagSetPresenter.new(@post.tag_array) @tag_set_presenter.split_tag_list_html(template, options.merge(:show_extra_links => CurrentUser.user.is_privileged?)) end - + def has_nav_links?(template) (CurrentUser.user.enable_sequential_post_navigation && template.params[:tags].present? && template.params[:tags] !~ /order:/) || @post.pools.active.any? end - + def post_footer_for_pool_html(template) if template.params[:pool_id] pool = Pool.where(:id => template.params[:pool_id]).first @@ -99,15 +99,15 @@ class PostPresenter < Presenter nil end end - + def pool_html(template) html = [""] - + if template.params[:pool_id].present? pool = Pool.where(:id => template.params[:pool_id]).first return if pool.nil? html += pool_link_html(template, pool, :include_rel => true) - + @post.pools.active.where("id <> ?", template.params[:pool_id]).each do |other_pool| html += pool_link_html(template, other_pool) end @@ -122,15 +122,15 @@ class PostPresenter < Presenter end end end - + html << "
" html.join("\n").html_safe end - + def pool_link_html(template, pool, options = {}) pool_html = [""] match_found = false - + if options[:include_rel] prev_rel = "prev" next_rel = "next" @@ -140,14 +140,14 @@ class PostPresenter < Presenter next_rel = nil klass = "" end - + if pool.neighbors(@post).previous pool_html << template.link_to("«prev".html_safe, template.post_path(pool.neighbors(@post).previous, :pool_id => pool.id), :rel => prev_rel, :class => "#{klass} prev") match_found = true else pool_html << '«prev' end - + pool_html << ' ' pool_html << template.link_to("Pool: #{pool.pretty_name}", template.pool_path(pool)) pool_html << ' ' @@ -158,7 +158,7 @@ class PostPresenter < Presenter else pool_html << 'next»' end - + pool_html << " " pool_html end diff --git a/app/presenters/post_set_presenters/base.rb b/app/presenters/post_set_presenters/base.rb index 6c117d28a..7a726bb2f 100644 --- a/app/presenters/post_set_presenters/base.rb +++ b/app/presenters/post_set_presenters/base.rb @@ -3,7 +3,7 @@ module PostSetPresenters def posts raise NotImplementedError end - + def post_previews_html(template) html = "" diff --git a/app/presenters/post_set_presenters/favorite.rb b/app/presenters/post_set_presenters/favorite.rb index 312414057..f719a80b9 100644 --- a/app/presenters/post_set_presenters/favorite.rb +++ b/app/presenters/post_set_presenters/favorite.rb @@ -11,11 +11,11 @@ module PostSetPresenters ).map {|x| x[0]} ) end - + def tag_list_html(template) tag_set_presenter.tag_list_html(template) end - + def posts @posts ||= favorite_set.posts end diff --git a/app/presenters/post_set_presenters/pool.rb b/app/presenters/post_set_presenters/pool.rb index 9157bb15d..4bba321ed 100644 --- a/app/presenters/post_set_presenters/pool.rb +++ b/app/presenters/post_set_presenters/pool.rb @@ -11,11 +11,11 @@ module PostSetPresenters ).map {|x| x[0]} ) end - + def tag_list_html(template) tag_set_presenter.tag_list_html(template) end - + def post_previews_html(template) html = "" diff --git a/app/presenters/post_set_presenters/popular.rb b/app/presenters/post_set_presenters/popular.rb index b474349e9..db95f8c7a 100644 --- a/app/presenters/post_set_presenters/popular.rb +++ b/app/presenters/post_set_presenters/popular.rb @@ -2,7 +2,7 @@ module PostSetPresenters class Popular < Base attr_accessor :post_set, :tag_set_presenter delegate :posts, :date, :min_date, :max_date, :to => :post_set - + def initialize(post_set) @post_set = post_set end @@ -10,42 +10,42 @@ module PostSetPresenters def prev_day date - 1.day end - + def next_day date + 1.day end - + def prev_week date - 7.days end - + def next_week date + 7.days end - + def prev_month 1.month.ago(date) end - + def next_month 1.month.since(date) end - + def link_rel_for_scale?(template, scale) (template.params[:scale].blank? && scale == "day") || template.params[:scale].to_s.include?(scale) end - + def next_date_for_scale(scale) case scale when "Day" next_day - + when "Week" next_week - + when "Month" next_month - + else nil end @@ -55,41 +55,41 @@ module PostSetPresenters case scale when "Day" prev_day - + when "Week" prev_week - + when "Month" prev_month - + else nil end end - + def nav_links_for_scale(template, scale) html = [] html << '' html << template.link_to( - "«prev".html_safe, + "«prev".html_safe, template.popular_explore_posts_path( - :date => prev_date_for_scale(scale), + :date => prev_date_for_scale(scale), :scale => scale.downcase ), :rel => (link_rel_for_scale?(template, scale.downcase) ? "prev" : nil) ) html << template.link_to( - scale, + scale, template.popular_explore_posts_path( - :date => date, + :date => date, :scale => scale.downcase - ), + ), :class => "desc" ) html << template.link_to( - "next»".html_safe, + "next»".html_safe, template.popular_explore_posts_path( - :date => next_date_for_scale(scale), + :date => next_date_for_scale(scale), :scale => scale.downcase ), :rel => (link_rel_for_scale?(template, scale.downcase) ? "next" : nil) @@ -97,7 +97,7 @@ module PostSetPresenters html << '' html.join("\n").html_safe end - + def nav_links(template) html = [] html << '' html.join("\n").html_safe end - + def range_text if min_date == max_date date.strftime("%B %d, %Y") diff --git a/app/presenters/post_set_presenters/post.rb b/app/presenters/post_set_presenters/post.rb index 4b64a70e4..54a516917 100644 --- a/app/presenters/post_set_presenters/post.rb +++ b/app/presenters/post_set_presenters/post.rb @@ -7,7 +7,7 @@ module PostSetPresenters @post_set = post_set @tag_set_presenter = TagSetPresenter.new(related_tags) end - + def related_tags if post_set.is_pattern_search? pattern_tags @@ -21,28 +21,28 @@ module PostSetPresenters related_tags_for_group end end - + def popular_tags n = 1 results = [] - + while results.empty? && n < 256 query = n.days.ago.strftime("date:>%Y-%m-%d") results = RelatedTagCalculator.calculate_from_sample_to_array(query).map(&:first) n *= 2 end - + results end - + def pattern_tags Tag.name_matches(post_set.tag_string).all(:select => "name", :limit => Danbooru.config.tag_query_limit, :order => "post_count DESC").map(&:name) end - + def related_tags_for_group RelatedTagCalculator.calculate_from_sample_to_array(post_set.tag_string).map(&:first) end - + def related_tags_for_single tag = Tag.find_by_name(post_set.tag_string) @@ -53,7 +53,7 @@ module PostSetPresenters tag.related_tag_array.map(&:first) end end - + def tag_list_html(template) tag_set_presenter.tag_list_html(template) end diff --git a/app/presenters/post_set_presenters/wiki_page.rb b/app/presenters/post_set_presenters/wiki_page.rb index 1aabc7ac1..7d057b7c8 100644 --- a/app/presenters/post_set_presenters/wiki_page.rb +++ b/app/presenters/post_set_presenters/wiki_page.rb @@ -5,7 +5,7 @@ module PostSetPresenters rescue ActiveRecord::StatementInvalid, PGError [] end - + def post_previews_html(template) result = super(template) if result =~ /Nobody here but us chickens/ diff --git a/app/presenters/post_version_presenter.rb b/app/presenters/post_version_presenter.rb index b7b875e12..714da7a5e 100644 --- a/app/presenters/post_version_presenter.rb +++ b/app/presenters/post_version_presenter.rb @@ -1,10 +1,10 @@ class PostVersionPresenter < Presenter attr_reader :post_version - + def initialize(post_version) @post_version = post_version end - + def changes html = [] html << post_version.tag_array @@ -13,7 +13,7 @@ class PostVersionPresenter < Presenter html << "parent:#{post_version.parent_id}" if post_version.parent_id html.join(" ").html_safe end - + def updater_name User.id_to_name(post_version.updater_id) end diff --git a/app/presenters/presenter.rb b/app/presenters/presenter.rb index 20dfdd2ed..19497050d 100644 --- a/app/presenters/presenter.rb +++ b/app/presenters/presenter.rb @@ -2,15 +2,15 @@ class Presenter def self.h(s) CGI.escapeHTML(s) end - + def self.u(s) URI.escape(s) end - + def h(s) CGI.escapeHTML(s) end - + def u(s) CGI::escape(s) end diff --git a/app/presenters/tag_set_presenter.rb b/app/presenters/tag_set_presenter.rb index 13ee6510c..3d3cdc5c8 100644 --- a/app/presenters/tag_set_presenter.rb +++ b/app/presenters/tag_set_presenter.rb @@ -1,6 +1,6 @@ =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 + This class makes it easy to fetch the categories for all the tags in one call instead of fetching them sequentially. =end @@ -8,7 +8,7 @@ class TagSetPresenter < Presenter def initialize(tags) @tags = tags end - + def tag_list_html(template, options = {}) html = "" if @tags.present? @@ -21,10 +21,10 @@ class TagSetPresenter < Presenter html.html_safe end - + def split_tag_list_html(template, options = {}) html = "" - + if copyright_tags.any? html << 'Copyrights
' html << "" @@ -33,7 +33,7 @@ class TagSetPresenter < Presenter end html << "
" end - + if character_tags.any? html << 'Characters
' html << "" @@ -42,7 +42,7 @@ class TagSetPresenter < Presenter end html << "
" end - + if artist_tags.any? html << 'Artist
' html << "" @@ -51,7 +51,7 @@ class TagSetPresenter < Presenter end html << "
" end - + if general_tags.any? html << 'Tags
' html << "" @@ -68,15 +68,15 @@ private def general_tags @general_tags ||= categories.select {|k, v| v == Tag.categories.general} end - + def copyright_tags @copyright_tags ||= categories.select {|k, v| v == Tag.categories.copyright} end - + def character_tags @character_tags ||= categories.select {|k, v| v == Tag.categories.character} end - + def artist_tags @artist_tags ||= categories.select {|k, v| v == Tag.categories.artist} end @@ -84,23 +84,23 @@ private def categories @categories ||= Tag.categories_for(@tags) end - + def counts @counts ||= Tag.counts_for(@tags).inject({}) do |hash, x| hash[x["name"]] = x["post_count"] hash end end - + def is_index?(template) template.params[:action] == "index" end - + def build_list_item(tag, template, options) html = "" html << %{
- } current_query = template.params[:tags] || "" - + unless options[:name_only] if categories[tag] == Tag.categories.artist html << %{? } @@ -113,21 +113,21 @@ private html << %{– } end end - + humanized_tag = tag.tr("_", " ") path = options[:path_prefix] || "/posts" html << %{#{h(humanized_tag)} } - + unless options[:name_only] if counts[tag].to_i > 1_000 post_count = "#{counts[tag].to_i / 1_000}k" else post_count = counts[tag].to_s end - + html << %{#{post_count}} end - + html << "
" html end diff --git a/app/presenters/upload_presenter.rb b/app/presenters/upload_presenter.rb index d510ac869..576008529 100644 --- a/app/presenters/upload_presenter.rb +++ b/app/presenters/upload_presenter.rb @@ -2,13 +2,13 @@ class UploadPresenter < Presenter def initialize(upload) @upload = upload end - + def status(template) case @upload.status when /duplicate: (\d+)/ dup_post_id = $1 template.link_to(@upload.status.gsub(/error: RuntimeError - /, ""), template.__send__(:post_path, dup_post_id)) - + else @upload.status end diff --git a/app/presenters/user_presenter.rb b/app/presenters/user_presenter.rb index 8d1729288..ca9e1a7be 100644 --- a/app/presenters/user_presenter.rb +++ b/app/presenters/user_presenter.rb @@ -1,6 +1,6 @@ class UserPresenter attr_reader :user - + def initialize(user) @user = user end @@ -8,15 +8,15 @@ class UserPresenter def name user.pretty_name end - + def join_date user.created_at.strftime("%Y-%m-%d") end - + def level user.level_string end - + def ban_reason if user.is_banned? "#{user.ban.reason}; expires #{user.ban.expires_at}" @@ -24,24 +24,24 @@ class UserPresenter nil end end - + def posts_for_subscription(subscription) Post.where("id in (?)", subscription.post_id_array.slice(0, 6).map(&:to_i)).order("id desc") end - + def tag_links_for_subscription(template, subscription) subscription.tag_query_array.map {|x| template.link_to(x.tr("_", " "), template.posts_path(:tags => x))}.join(", ").html_safe end - + def upload_limit if user.is_contributor? return "none" end - + deleted_count = Post.for_user(user.id).deleted.count pending_count = Post.for_user(user.id).pending.count approved_count = Post.where("is_flagged = false and is_pending = false and is_deleted = false and uploader_id = ?", user.id).count - + if user.base_upload_limit limit = user.base_upload_limit - pending_count string = "base:#{user.base_upload_limit} - pending:#{pending_count}" @@ -49,7 +49,7 @@ class UserPresenter limit = 10 + (approved_count / 10) - (deleted_count / 4) - pending_count string = "base:10 + approved:(#{approved_count} / 10) - deleted:(#{deleted_count}) / 4 - pending:#{pending_count}" end - + if limit < 0 limit = 0 string += " = 0" @@ -59,59 +59,59 @@ class UserPresenter return string end - + def uploads @uploads ||= Post.where("uploader_id = ?", user.id).order("id desc").limit(6) end - + def has_uploads? user.post_upload_count > 0 end - + def favorites @favorites ||= user.favorites.limit(6).includes(:post).reorder("favorites.id desc").map(&:post) end - + def has_favorites? user.favorite_count > 0 end - + def upload_count(template) template.link_to(user.post_upload_count, template.posts_path(:tags => "user:#{user.name}")) end - + def deleted_upload_count(template) template.link_to(Post.for_user(user.id).deleted.count, template.posts_path(:tags => "status:deleted user:#{user.name}")) end - + def favorite_count(template) template.link_to(user.favorite_count, template.posts_path(:tags => "fav:#{user.name}")) end - + def comment_count(template) template.link_to(Comment.for_creator(user.id).count, template.comments_path(:search => {:creator_id => user.id}, :group_by => "comment")) end - + def post_version_count(template) template.link_to(user.post_update_count, template.post_versions_path(:search => {:updater_id => user.id})) end - + def note_version_count(template) template.link_to(user.note_update_count, template.note_versions_path(:search => {:updater_id => user.id})) end - + def wiki_page_version_count(template) template.link_to(WikiPageVersion.for_user(user.id).count, template.wiki_page_versions_path(:search => {:updater_id => user.id})) end - + def forum_post_count(template) template.link_to(ForumPost.for_user(user.id).count, template.forum_posts_path(:search => {:creator_id => user.id})) end - + def pool_version_count(template) template.link_to(PoolVersion.for_user(user.id).count, template.pool_versions_path(:search => {:updater_id => user.id})) end - + def inviter(template) if user.inviter_id template.link_to(user.inviter.name, template.user_path(user.inviter_id)) @@ -119,19 +119,19 @@ class UserPresenter "None" end end - + def approval_count(template) template.link_to(Post.where("approver_id = ?", user.id).count, template.posts_path(:tags => "approver:#{user.name}")) end - + def feedbacks(template) positive = UserFeedback.for_user(user.id).positive.count neutral = UserFeedback.for_user(user.id).neutral.count negative = UserFeedback.for_user(user.id).negative.count - + template.link_to("positive:#{positive} neutral:#{neutral} negative:#{negative}", template.user_feedbacks_path(:search => {:user_id => user.id})) end - + def subscriptions if CurrentUser.user.id == user.id user.subscriptions diff --git a/app/presenters/wiki_page_presenter.rb b/app/presenters/wiki_page_presenter.rb index bc14d780b..8797c15ce 100644 --- a/app/presenters/wiki_page_presenter.rb +++ b/app/presenters/wiki_page_presenter.rb @@ -1,26 +1,26 @@ class WikiPagePresenter attr_reader :wiki_page - + def initialize(wiki_page) @wiki_page = wiki_page end - + def excerpt wiki_page.body end - + def blurb excerpt.try(:gsub, /<.+?>/, "") end - + def consequent_tag_aliases @consequent_tag_aliases ||= TagAlias.where("consequent_name = ?", wiki_page.title) end - + def antecedent_tag_alias @antecedent_tag_alias ||= TagAlias.find_by_antecedent_name(wiki_page.title) end - + # Produce a formatted page that shows the difference between two versions of a page. def diff(other_version) pattern = Regexp.new('(?:<.+?>)|(?:[0-9_A-Za-z\x80-\xff]+[\x09\x20]?)|(?:[ \t]+)|(?:\r?\n)|(?:.+?)') diff --git a/config/application.rb b/config/application.rb index d3c023f34..7cb210549 100644 --- a/config/application.rb +++ b/config/application.rb @@ -10,7 +10,7 @@ end module Danbooru class Application < Rails::Application - + config.active_record.schema_format = :sql config.encoding = "utf-8" config.filter_parameters += [:password] diff --git a/config/danbooru_default_config.rb b/config/danbooru_default_config.rb index 8adcaadc1..493f3e94f 100644 --- a/config/danbooru_default_config.rb +++ b/config/danbooru_default_config.rb @@ -6,102 +6,102 @@ module Danbooru def version "2.1.0" end - + # The name of this Danbooru. def app_name "Danbooru" end - + # The hostname of the server. def hostname Socket.gethostname end - + # Contact email address of the admin. def contact_email "webmaster@#{server_host}" end - + def upgrade_account_email contact_email end - + # Stripped of any special characters. def safe_app_name app_name.gsub(/[^a-zA-Z0-9_-]/, "_") end - + # The default name to use for anyone who isn't logged in. def default_guest_name "Anonymous" end - + # This is a salt used to make dictionary attacks on account passwords harder. def password_salt "choujin-steiner" end - + # Set to true to allow new account signups. def enable_signups? true end - + # Set to true to give all new users privileged access. def start_as_privileged? false end - + # Set to true to give all new users contributor access. def start_as_contributor? false end - + # What method to use to store images. # local_flat: Store every image in one directory. # local_hierarchy: Store every image in a hierarchical directory, based on the post's MD5 hash. On some file systems this may be faster. def image_store :local_flat end - + # Thumbnail size def small_image_width 150 end - + # Large resize image width. Set to nil to disable. def large_image_width 850 end - + def large_image_prefix "sample-" end - + # When calculating statistics based on the posts table, gather this many posts to sample from. def post_sample_size 300 end - + # If a solid state drive is availble, cache the thumbnails on the SSD to reduce disk seek times. def ssd_path nil end - + # Where the ad banners are stored in the file system def advertisement_path nil end - + # List of memcached servers def memcached_servers %w(localhost:11211) end - + # After a post receives this many comments, new comments will no longer bump the post in comment/index. def comment_threshold 40 end - + # Members cannot post more than X comments in an hour. def member_comment_limit 2 @@ -111,12 +111,12 @@ module Danbooru def can_see_ads?(user) !user.is_privileged? end - + # Users cannot search for more than X regular tags at a time. def base_tag_query_limit 6 end - + def tag_query_limit if CurrentUser.user.present? CurrentUser.user.tag_query_limit @@ -124,43 +124,43 @@ module Danbooru base_tag_query_limit * 2 end end - + # Max number of posts to cache def tag_subscription_post_limit 200 end - + # After this many pages, the paginator will switch to sequential mode. def max_numbered_pages 1_000 end - + # Max number of tag subscriptions per user def max_tag_subscriptions 5 end - + # Maximum size of an upload. def max_file_size 25.megabytes end - + def member_comment_time_threshold 1.week.ago end - + # The name of the server the app is hosted on. def server_host Socket.gethostname end - + # Names of all Danbooru servers which serve out of the same common database. # Used in conjunction with load balancing to distribute files from one server to # the others. This should match whatever gethostname returns on the other servers. def all_server_hosts [server_host] end - + # Names of other Danbooru servers. def other_server_hosts @other_server_hosts ||= all_server_hosts.reject {|x| x == server_host} @@ -169,7 +169,7 @@ module Danbooru def remote_server_login "albert" end - + # Returns a hash mapping various tag categories to a numerical value. # Be sure to update the reverse_tag_category_mapping also. def tag_category_mapping @@ -189,7 +189,7 @@ module Danbooru "ch" => 4 } end - + def canonical_tag_category_mapping @canonical_tag_category_mapping ||= { "General" => 0, @@ -198,7 +198,7 @@ module Danbooru "Character" => 4 } end - + # Returns a hash maping numerical category values to their # string equivalent. Be sure to update the tag_category_mapping also. def reverse_tag_category_mapping @@ -209,18 +209,18 @@ module Danbooru 4 => "Character" } end - + # If enabled, users must verify their email addresses. def enable_email_verification? false end - + # Any custom code you want to insert into the default layout without # having to modify the templates. def custom_html_header_content nil end - + # The number of posts displayed per page. def posts_per_page 20 @@ -229,15 +229,15 @@ module Danbooru def is_post_restricted?(post) false end - + def is_user_restricted?(user) !user.is_privileged? end - + def is_user_advertiser?(user) user.is_admin? end - + def can_user_see_post?(user, post) if is_user_restricted?(user) && is_post_restricted?(post) false @@ -245,59 +245,59 @@ module Danbooru true end end - + def select_posts_visible_to_user(user, posts) posts.select {|x| can_user_see_post?(user, x)} end - + def max_appeals_per_day 1 end - + # Counting every post is typically expensive because it involves a sequential scan on # potentially millions of rows. If this method returns a value, then blank searches # will return that number for the fast_count call instead. def blank_tag_search_fast_count nil end - + def pixiv_login nil end - + def pixiv_password nil end - + def tinami_login nil end - + def tinami_password nil end - + def nico_seiga_login nil end - + def nico_seiga_password nil end - + def pixa_login nil end - + def pixa_password nil end - + def amazon_ses # {:smtp_server_name => "smtp server", :user_name => "user name", :ses_smtp_user_name => "smtp user name", :ses_smtp_password => "smtp password"} nil end - + def enable_dimension_autotagging true end diff --git a/config/deploy.rb b/config/deploy.rb index 02395e478..bfaf2bc09 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -47,14 +47,14 @@ namespace :data do run "mkdir #{deploy_to}/shared/data/preview" run "mkdir #{deploy_to}/shared/data/sample" end - + task :link_directories do run "rm -f #{release_path}/public/data" run "ln -s #{deploy_to}/shared/data #{release_path}/public/data" - + run "rm -f #{release_path}/public/ssd" run "ln -s /mnt/ssd#{deploy_to}/current/public #{release_path}/public/ssd" - + run "rm -f #{release_path}/public/images/advertisements" run "ln -s #{deploy_to}/shared/advertisements #{release_path}/public/images/advertisements" end @@ -72,31 +72,31 @@ namespace :deploy do maintenance_html_path = "#{current_path}/public/maintenance.html.bak" run "if [ -e #{maintenance_html_path} ] ; then mv #{maintenance_html_path} #{current_path}/public/maintenance.html ; fi" end - + desc "Makes the application web-accessible again." task :enable do maintenance_html_path = "#{current_path}/public/maintenance.html" run "if [ -e #{maintenance_html_path} ] ; then mv #{maintenance_html_path} #{current_path}/public/maintenance.html.bak ; fi" end end - + namespace :nginx do desc "Shut down Nginx" task :stop do sudo "/etc/init.d/nginx stop" end - + desc "Start Nginx" task :start do sudo "/etc/init.d/nginx start" end end - + desc "Precompiles assets" task :precompile_assets do run "cd #{current_path}; bundle exec rake assets:precompile" end - + desc "Restart the application" task :restart do run "touch #{current_path}/tmp/restart.txt" @@ -108,21 +108,21 @@ namespace :delayed_job do task :start, :roles => :app do run "cd #{current_path}; RAILS_ENV=#{rails_env} bundle exec ruby script/delayed_job --queues=default,`hostname` start" end - + desc "Stop delayed_job process" task :stop, :roles => :app do run "cd #{current_path}; RAILS_ENV=#{rails_env} bundle exec ruby script/delayed_job stop" end - + desc "Restart delayed_job process" task :restart, :roles => :app do find_and_execute_task("delayed_job:stop") find_and_execute_task("delayed_job:start") end - + task :kill, :roles => :app do procs = capture("ps -A -o pid,command").split(/\r\n|\r|\n/).grep(/delayed_job/).map(&:to_i) - + if procs.any? run "for i in #{procs.join(' ')} ; do kill -SIGTERM $i ; done" end diff --git a/config/initializers/active_record_api_extensions.rb b/config/initializers/active_record_api_extensions.rb index 0efad591e..748149b73 100644 --- a/config/initializers/active_record_api_extensions.rb +++ b/config/initializers/active_record_api_extensions.rb @@ -2,14 +2,14 @@ module Danbooru module Extensions module ActiveRecordApi extend ActiveSupport::Concern - + def serializable_hash(options = {}) options ||= {} options[:except] ||= [] options[:except] += hidden_attributes super(options) end - + def to_xml(options = {}, &block) # to_xml ignores serializable_hash options ||= {} @@ -17,7 +17,7 @@ module Danbooru options[:except] += hidden_attributes super(options, &block) end - + protected def hidden_attributes [:uploader_ip_addr, :updater_ip_addr, :creator_ip_addr, :ip_addr] diff --git a/config/initializers/active_record_extensions.rb b/config/initializers/active_record_extensions.rb index cd691ce6a..168b559fb 100644 --- a/config/initializers/active_record_extensions.rb +++ b/config/initializers/active_record_extensions.rb @@ -2,7 +2,7 @@ module Danbooru module Extensions module ActiveRecord extend ActiveSupport::Concern - + module ClassMethods def without_timeout connection.execute("SET STATEMENT_TIMEOUT = 0") unless Rails.env == "test" @@ -20,7 +20,7 @@ module Danbooru connection.execute("SET STATEMENT_TIMEOUT = 3000") unless Rails.env == "test" end end - + %w(execute select_value select_values select_all).each do |method_name| define_method("#{method_name}_sql") do |sql, *params| connection.__send__(method_name, self.class.sanitize_sql_array([sql, *params])) @@ -30,20 +30,20 @@ module Danbooru connection.__send__(method_name, sanitize_sql_array([sql, *params])) end end - + def arbitrary_sql_order_clause(ids, table_name = nil) table_name = self.class.table_name if table_name.nil? - + if ids.empty? return "#{table_name}.id desc" end - + conditions = [] - + ids.each_with_index do |x, n| conditions << "when #{x} then #{n}" end - + "case #{table_name}.id " + conditions.join(" ") + " end" end end @@ -51,7 +51,7 @@ module Danbooru end class ActiveRecord::Base - class << self + class << self public :sanitize_sql_array end diff --git a/config/initializers/core_extensions.rb b/config/initializers/core_extensions.rb index ee57bb611..d6a1a2416 100644 --- a/config/initializers/core_extensions.rb +++ b/config/initializers/core_extensions.rb @@ -12,7 +12,7 @@ module Danbooru def to_escaped_for_tsquery "'#{gsub(/'/, '\0\0').gsub(/\\/, '\0\0\0\0')}'" end - + def to_escaped_js return self.gsub(/\\/, '\0\0').gsub(/['"]/) {|m| "\\#{m}"}.gsub(/\r\n|\r|\n/, '\\n') end diff --git a/config/initializers/danbooru_config.rb b/config/initializers/danbooru_config.rb index a11e5a360..b4a0ff385 100644 --- a/config/initializers/danbooru_config.rb +++ b/config/initializers/danbooru_config.rb @@ -5,6 +5,6 @@ module Danbooru def config @configuration ||= CustomConfiguration.new end - + module_function :config end diff --git a/config/initializers/query_trace.rb b/config/initializers/query_trace.rb index 82a3d89be..daadc7cd7 100644 --- a/config/initializers/query_trace.rb +++ b/config/initializers/query_trace.rb @@ -72,7 +72,7 @@ end QueryTrace.attach_to :active_record trap('QUIT') do - # Sending 2 backspace characters removes the ^\ that is + # Sending 2 backspace characters removes the ^\ that is # printed to the console. rm_noise = "\b\b" diff --git a/config/routes.rb b/config/routes.rb index a07dac700..0700af81f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -188,7 +188,7 @@ Danbooru::Application.routes.draw do get :upgrade_information get :search end - + member do delete :cache post :upgrade @@ -210,7 +210,7 @@ Danbooru::Application.routes.draw do get :diff end end - + # aliases resources :wpages, :controller => "wiki_pages" resources :ftopics, :controller => "forum_topics" @@ -228,17 +228,17 @@ Danbooru::Application.routes.draw do match "/artist/destroy/:id" => redirect("/artists/%{id}") match "/artist/recent_changes" => redirect("/artist_versions") match "/artist/create" => redirect("/artists") - + match "/comment" => redirect {|params, req| "/comments?page=#{req.params[:page]}"} match "/comment/index" => redirect {|params, req| "/comments?page=#{req.params[:page]}"} match "/comment/show/:id" => redirect("/comments/%{id}") match "/comment/new" => redirect("/comments") match "/comment/search" => redirect("/comments/search") - + match "/favorite" => redirect {|params, req| "/favorites?page=#{req.params[:page]}"} match "/favorite/index" => redirect {|params, req| "/favorites?page=#{req.params[:page]}"} match "/favorite/list_users.json", :controller => "legacy", :action => "unavailable" - + match "/forum" => redirect {|params, req| "/forum_topics?page=#{req.params[:page]}"} match "/forum/index" => redirect {|params, req| "/forum_topics?page=#{req.params[:page]}"} match "/forum/show/:id" => redirect("/forum_posts/%{id}") @@ -251,13 +251,13 @@ Danbooru::Application.routes.draw do match "/note" => redirect {|params, req| "/notes?page=#{req.params[:page]}"} match "/note/index" => redirect {|params, req| "/notes?page=#{req.params[:page]}"} match "/note/history" => redirect("/note_versions") - + match "/pool" => redirect {|params, req| "/pools?page=#{req.params[:page]}"} match "/pool/index" => redirect {|params, req| "/pools?page=#{req.params[:page]}"} match "/pool/show/:id" => redirect("/pools/%{id}") match "/pool/history/:id" => redirect("/pool_versions?search[pool_id]=%{id}") match "/pool/recent_changes" => redirect("/pool_versions") - + match "/post/index.xml", :controller => "legacy", :action => "posts", :format => "xml" match "/post/index.json", :controller => "legacy", :action => "posts", :format => "json" match "/post/create.xml", :controller => "legacy", :action => "create_post", :format => "xml" @@ -276,22 +276,22 @@ Danbooru::Application.routes.draw do match "/post/view/:id/:tag_title" => redirect("/posts/%{id}") match "/post/view/:id" => redirect("/posts/%{id}") match "/post/flag/:id" => redirect("/posts/%{id}") - + match "/post_tag_history" => redirect {|params, req| "/post_versions?page=#{req.params[:page]}"} match "/post_tag_history/index" => redirect {|params, req| "/post_versions?page=#{req.params[:page]}"} - + match "/tag/index.xml", :controller => "legacy", :action => "tags", :format => "xml" match "/tag/index.json", :controller => "legacy", :action => "tags", :format => "json" match "/tag" => redirect {|params, req| "/tags?page=#{req.params[:page]}"} match "/tag/index" => redirect {|params, req| "/tags?page=#{req.params[:page]}"} - + match "/user/index.xml", :controller => "legacy", :action => "users", :format => "xml" match "/user/index.json", :controller => "legacy", :action => "users", :format => "json" match "/user" => redirect {|params, req| "/users?page=#{req.params[:page]}"} match "/user/index" => redirect {|params, req| "/users?page=#{req.params[:page]}"} match "/user/show/:id" => redirect("/users/%{id}") match "/user/login" => redirect("/sessions/new") - + match "/wiki" => redirect {|params, req| "/wiki_pages?page=#{req.params[:page]}"} match "/wiki/index" => redirect {|params, req| "/wiki_pages?page=#{req.params[:page]}"} match "/wiki/revert" => redirect("/wiki_pages") @@ -308,6 +308,6 @@ Danbooru::Application.routes.draw do match "/static/contact" => "static#contact", :as => "contact" match "/static/benchmark" => "static#benchmark" match "/static/name_change" => "static#name_change", :as => "name_change" - + root :to => "posts#index" end diff --git a/config/schedule.rb b/config/schedule.rb index b613464f1..0930097c6 100644 --- a/config/schedule.rb +++ b/config/schedule.rb @@ -26,7 +26,7 @@ if environment == "production" every 1.hour do runner "AmazonBackup.execute" end - + every 1.week do runner "UserPasswordResetNonce.prune!" end diff --git a/config/state_checker.rb b/config/state_checker.rb index a6f4b0a61..8a1be76f8 100644 --- a/config/state_checker.rb +++ b/config/state_checker.rb @@ -5,11 +5,11 @@ class StateChecker end private - + def secret_token_path File.expand_path("~/.danbooru/secret_token") end - + def check_secret_token unless File.exists?(secret_token_path) raise "You must create a file in #{secret_token_path} containing a secret key. It should be a string of at least 32 random characters." @@ -23,7 +23,7 @@ private def session_secret_key_path File.expand_path("~/.danbooru/session_secret_key") end - + def check_session_secret_key unless File.exists?(session_secret_key_path) raise "You must create a file in #{session_secret_key_path} containing a secret key. It should be a string of at least 32 random characters." diff --git a/db/migrate/20100204211522_create_users.rb b/db/migrate/20100204211522_create_users.rb index 7cf50a081..73eb503d3 100644 --- a/db/migrate/20100204211522_create_users.rb +++ b/db/migrate/20100204211522_create_users.rb @@ -2,7 +2,7 @@ class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.timestamps - + t.column :name, :string, :null => false t.column :password_hash, :string, :null => false t.column :email, :string @@ -11,7 +11,7 @@ class CreateUsers < ActiveRecord::Migration t.column :is_banned, :boolean, :null => false, :default => false t.column :level, :integer, :null => false, :default => 0 t.column :base_upload_limit, :integer, :null => false, :default => 10 - + # Cached data t.column :last_logged_in_at, :datetime t.column :last_forum_read_at, :datetime @@ -21,7 +21,7 @@ class CreateUsers < ActiveRecord::Migration t.column :post_update_count, :integer, :null => false, :default => 0 t.column :note_update_count, :integer, :null => false, :default => 0 t.column :favorite_count, :integer, :null => false, :default => 0 - + # Profile settings t.column :receive_email_notifications, :boolean, :null => false, :default => false t.column :comment_threshold, :integer, :null => false, :default => -1 @@ -31,7 +31,7 @@ class CreateUsers < ActiveRecord::Migration t.column :blacklisted_tags, :text t.column :time_zone, :string, :null => false, :default => "Eastern Time (US & Canada)" end - + execute "CREATE UNIQUE INDEX index_users_on_name ON users ((lower(name)))" add_index :users, :email, :unique => true end diff --git a/db/migrate/20100204214746_create_posts.rb b/db/migrate/20100204214746_create_posts.rb index 0718d7710..fa36a459f 100644 --- a/db/migrate/20100204214746_create_posts.rb +++ b/db/migrate/20100204214746_create_posts.rb @@ -2,7 +2,7 @@ class CreatePosts < ActiveRecord::Migration def self.up create_table :posts do |t| t.timestamps - + t.column :up_score, :integer, :null => false, :default => 0 t.column :down_score, :integer, :null => false, :default => 0 t.column :score, :integer, :null => false, :default => 0 @@ -21,7 +21,7 @@ class CreatePosts < ActiveRecord::Migration # Uploader t.column :uploader_id, :integer, :null => false t.column :uploader_ip_addr, "inet", :null => false - + # Approver t.column :approver_id, :integer @@ -50,12 +50,12 @@ class CreatePosts < ActiveRecord::Migration t.column :file_size, :integer, :null => false t.column :image_width, :integer, :null => false t.column :image_height, :integer, :null => false - + # Parent t.column :parent_id, :integer t.column :has_children, :boolean, :null => false, :default => false end - + add_index :posts, :md5, :unique => true add_index :posts, :created_at add_index :posts, :last_commented_at @@ -102,7 +102,7 @@ class CreatePosts < ActiveRecord::Migration HEADLINE = pg_catalog.prsd_headline, LEXTYPES = testprs_lextype )" - + execute "CREATE INDEX index_posts_on_tags_index ON posts USING gin (tag_index)" execute "CREATE TEXT SEARCH CONFIGURATION public.danbooru (PARSER = public.testparser)" execute "ALTER TEXT SEARCH CONFIGURATION public.danbooru ADD MAPPING FOR WORD WITH SIMPLE" diff --git a/db/migrate/20100205162521_create_tags.rb b/db/migrate/20100205162521_create_tags.rb index 4502a8f05..927cf359e 100644 --- a/db/migrate/20100205162521_create_tags.rb +++ b/db/migrate/20100205162521_create_tags.rb @@ -8,7 +8,7 @@ class CreateTags < ActiveRecord::Migration t.column :related_tags_updated_at, :datetime t.timestamps end - + add_index :tags, :name, :unique => true execute "create index index_tags_on_name_pattern on tags (name text_pattern_ops)" end diff --git a/db/migrate/20100205163027_create_post_versions.rb b/db/migrate/20100205163027_create_post_versions.rb index 6e78af561..75bd7a77c 100644 --- a/db/migrate/20100205163027_create_post_versions.rb +++ b/db/migrate/20100205163027_create_post_versions.rb @@ -2,7 +2,7 @@ class CreatePostVersions < ActiveRecord::Migration def self.up create_table :post_versions do |t| t.timestamps - + t.column :post_id, :integer, :null => false t.column :tags, :text, :null => false, :default => "" t.column :rating, :char @@ -11,7 +11,7 @@ class CreatePostVersions < ActiveRecord::Migration t.column :updater_id, :integer, :null => false t.column :updater_ip_addr, "inet", :null => false end - + add_index :post_versions, :post_id add_index :post_versions, :updater_id add_index :post_versions, :updater_ip_addr diff --git a/db/migrate/20100205224030_create_uploads.rb b/db/migrate/20100205224030_create_uploads.rb index f3d2d7a14..a55e4d444 100644 --- a/db/migrate/20100205224030_create_uploads.rb +++ b/db/migrate/20100205224030_create_uploads.rb @@ -14,7 +14,7 @@ class CreateUploads < ActiveRecord::Migration t.column :md5_confirmation, :string t.timestamps end - + add_index :uploads, :uploader_id add_index :uploads, :uploader_ip_addr end diff --git a/db/migrate/20100211025616_create_pools.rb b/db/migrate/20100211025616_create_pools.rb index b75dec4d0..b8fb224ad 100644 --- a/db/migrate/20100211025616_create_pools.rb +++ b/db/migrate/20100211025616_create_pools.rb @@ -10,7 +10,7 @@ class CreatePools < ActiveRecord::Migration t.column :is_deleted, :boolean, :null => false, :default => false t.timestamps end - + add_index :pools, :name add_index :pools, :creator_id end diff --git a/db/migrate/20100211181944_create_favorites.rb b/db/migrate/20100211181944_create_favorites.rb index 04dd8d36f..c3f38fb4d 100644 --- a/db/migrate/20100211181944_create_favorites.rb +++ b/db/migrate/20100211181944_create_favorites.rb @@ -1,6 +1,6 @@ class CreateFavorites < ActiveRecord::Migration TABLE_COUNT = 100 - + def self.up # this is a dummy table and should not be used create_table "favorites" do |t| @@ -14,20 +14,20 @@ class CreateFavorites < ActiveRecord::Migration check (user_id % 100 = #{i}) ) inherits (favorites) EOS - + add_index "favorites_#{i}", :user_id add_index "favorites_#{i}", :post_id end - + fragment = [] - + 1.upto(TABLE_COUNT - 1) do |i| fragment << <<-EOS elsif (NEW.user_id % 100 = #{i}) then insert into favorites_#{i} values (NEW.*); EOS end - + execute <<-EOS create or replace function favorites_insert_trigger() returns trigger as $$ @@ -41,7 +41,7 @@ class CreateFavorites < ActiveRecord::Migration $$ language plpgsql EOS - + execute <<-EOS create trigger insert_favorites_trigger before insert on favorites @@ -51,7 +51,7 @@ class CreateFavorites < ActiveRecord::Migration def self.down drop_table "favorites" - + 0.upto(TABLE_COUNT - 1) do |i| drop_table "favorites_#{i}" end diff --git a/db/migrate/20100211191709_create_tag_aliases.rb b/db/migrate/20100211191709_create_tag_aliases.rb index 791591bd6..04ba2e5a4 100644 --- a/db/migrate/20100211191709_create_tag_aliases.rb +++ b/db/migrate/20100211191709_create_tag_aliases.rb @@ -9,7 +9,7 @@ class CreateTagAliases < ActiveRecord::Migration t.column :status, :text, :null => false, :default => "pending" t.timestamps end - + add_index :tag_aliases, :antecedent_name add_index :tag_aliases, :consequent_name end diff --git a/db/migrate/20100211191716_create_tag_implications.rb b/db/migrate/20100211191716_create_tag_implications.rb index 2e2e70ebb..c68deada6 100644 --- a/db/migrate/20100211191716_create_tag_implications.rb +++ b/db/migrate/20100211191716_create_tag_implications.rb @@ -10,7 +10,7 @@ class CreateTagImplications < ActiveRecord::Migration t.column :status, :text, :null => false, :default => "pending" t.timestamps end - + add_index :tag_implications, :antecedent_name add_index :tag_implications, :consequent_name end diff --git a/db/migrate/20100213181847_create_comments.rb b/db/migrate/20100213181847_create_comments.rb index c3edea4b6..24654ad34 100644 --- a/db/migrate/20100213181847_create_comments.rb +++ b/db/migrate/20100213181847_create_comments.rb @@ -9,7 +9,7 @@ class CreateComments < ActiveRecord::Migration t.column :score, :integer, :null => false, :default => 0 t.timestamps end - + add_index :comments, :post_id execute "CREATE INDEX index_comments_on_body_index ON comments USING GIN (body_index)" execute "CREATE TRIGGER trigger_comments_on_update BEFORE INSERT OR UPDATE ON comments FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger('body_index', 'pg_catalog.english', 'body')" diff --git a/db/migrate/20100213183712_create_comment_votes.rb b/db/migrate/20100213183712_create_comment_votes.rb index 2c3f2f5b0..c7e4610a0 100644 --- a/db/migrate/20100213183712_create_comment_votes.rb +++ b/db/migrate/20100213183712_create_comment_votes.rb @@ -6,7 +6,7 @@ class CreateCommentVotes < ActiveRecord::Migration t.column :score, :integer, :null => false t.timestamps end - + add_index :comment_votes, :comment_id add_index :comment_votes, :user_id add_index :comment_votes, :created_at diff --git a/db/migrate/20100214080557_create_artist_versions.rb b/db/migrate/20100214080557_create_artist_versions.rb index e222d8453..a50b47ed4 100644 --- a/db/migrate/20100214080557_create_artist_versions.rb +++ b/db/migrate/20100214080557_create_artist_versions.rb @@ -12,7 +12,7 @@ class CreateArtistVersions < ActiveRecord::Migration t.column :is_banned, :boolean, :null => false, :default => false t.timestamps end - + add_index :artist_versions, :artist_id add_index :artist_versions, :name add_index :artist_versions, :updater_id diff --git a/db/migrate/20100214080605_create_artist_urls.rb b/db/migrate/20100214080605_create_artist_urls.rb index b5bcd3eec..b30b1a5ef 100644 --- a/db/migrate/20100214080605_create_artist_urls.rb +++ b/db/migrate/20100214080605_create_artist_urls.rb @@ -6,11 +6,11 @@ class CreateArtistUrls < ActiveRecord::Migration t.column :normalized_url, :text, :null => false t.timestamps end - + add_index :artist_urls, :artist_id add_index :artist_urls, :normalized_url add_index :artist_urls, :url - + execute "create index index_artist_urls_on_url_pattern on artist_urls (url text_pattern_ops)" execute "create index index_artist_urls_on_normalized_url_pattern on artist_urls (normalized_url text_pattern_ops)" end diff --git a/db/migrate/20100215182234_create_wiki_pages.rb b/db/migrate/20100215182234_create_wiki_pages.rb index 40523f6a9..9f85ce257 100644 --- a/db/migrate/20100215182234_create_wiki_pages.rb +++ b/db/migrate/20100215182234_create_wiki_pages.rb @@ -8,7 +8,7 @@ class CreateWikiPages < ActiveRecord::Migration t.column :is_locked, :boolean, :null => false, :default => false t.timestamps end - + add_index :wiki_pages, :title, :unique => true execute "CREATE INDEX index_wiki_pages_on_body_index_index ON wiki_pages USING GIN (body_index)" execute "CREATE TRIGGER trigger_wiki_pages_on_update BEFORE INSERT OR UPDATE ON wiki_pages FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger('body_index', 'public.danbooru', 'body', 'title')" diff --git a/db/migrate/20100215213756_create_wiki_page_versions.rb b/db/migrate/20100215213756_create_wiki_page_versions.rb index a6e0ea2ca..7ef0d0515 100644 --- a/db/migrate/20100215213756_create_wiki_page_versions.rb +++ b/db/migrate/20100215213756_create_wiki_page_versions.rb @@ -9,7 +9,7 @@ class CreateWikiPageVersions < ActiveRecord::Migration t.column :is_locked, :boolean, :null => false t.timestamps end - + add_index :wiki_page_versions, :wiki_page_id end diff --git a/db/migrate/20100215223541_create_post_votes.rb b/db/migrate/20100215223541_create_post_votes.rb index e790f690b..56c60dc9a 100644 --- a/db/migrate/20100215223541_create_post_votes.rb +++ b/db/migrate/20100215223541_create_post_votes.rb @@ -6,7 +6,7 @@ class CreatePostVotes < ActiveRecord::Migration t.column :score, :integer, :null => false t.timestamps end - + add_index :post_votes, :post_id add_index :post_votes, :user_id end diff --git a/db/migrate/20100215224629_create_advertisements.rb b/db/migrate/20100215224629_create_advertisements.rb index 8c5bd9915..67fafc14d 100644 --- a/db/migrate/20100215224629_create_advertisements.rb +++ b/db/migrate/20100215224629_create_advertisements.rb @@ -11,7 +11,7 @@ class CreateAdvertisements < ActiveRecord::Migration t.column :is_work_safe, :boolean, :null => false, :default => false t.timestamps end - + add_index :advertisements, :ad_type end diff --git a/db/migrate/20100215224635_create_advertisement_hits.rb b/db/migrate/20100215224635_create_advertisement_hits.rb index 578dcc6c6..f152ffee3 100644 --- a/db/migrate/20100215224635_create_advertisement_hits.rb +++ b/db/migrate/20100215224635_create_advertisement_hits.rb @@ -5,7 +5,7 @@ class CreateAdvertisementHits < ActiveRecord::Migration t.column :ip_addr, "inet", :null => false t.timestamps end - + add_index :advertisement_hits, :advertisement_id add_index :advertisement_hits, :created_at end diff --git a/db/migrate/20100215225710_create_bans.rb b/db/migrate/20100215225710_create_bans.rb index 4715aecf9..3e0c6e49a 100644 --- a/db/migrate/20100215225710_create_bans.rb +++ b/db/migrate/20100215225710_create_bans.rb @@ -7,7 +7,7 @@ class CreateBans < ActiveRecord::Migration t.column :expires_at, :datetime, :null => false t.timestamps end - + add_index :bans, :user_id add_index :bans, :expires_at add_index :bans, :banner_id diff --git a/db/migrate/20100215230642_create_user_feedback.rb b/db/migrate/20100215230642_create_user_feedback.rb index f61a5b7f4..49d5bd3cf 100644 --- a/db/migrate/20100215230642_create_user_feedback.rb +++ b/db/migrate/20100215230642_create_user_feedback.rb @@ -7,7 +7,7 @@ class CreateUserFeedback < ActiveRecord::Migration t.column :body, :text, :null => false t.timestamps end - + add_index :user_feedback, :user_id add_index :user_feedback, :creator_id end diff --git a/db/migrate/20100219230537_create_dmails.rb b/db/migrate/20100219230537_create_dmails.rb index 828ef9a3f..61fc4136d 100644 --- a/db/migrate/20100219230537_create_dmails.rb +++ b/db/migrate/20100219230537_create_dmails.rb @@ -11,9 +11,9 @@ class CreateDmails < ActiveRecord::Migration t.column :is_deleted, :boolean, :null => false, :default => false t.timestamps end - + add_index :dmails, :owner_id - + execute "CREATE INDEX index_dmails_on_message_index ON dmails USING GIN (message_index)" execute "CREATE TRIGGER trigger_dmails_on_update BEFORE INSERT OR UPDATE ON dmails FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger('message_index', 'pg_catalog.english', 'title', 'body')" end diff --git a/db/migrate/20100221003655_create_forum_topics.rb b/db/migrate/20100221003655_create_forum_topics.rb index 73219279b..5f0845ffc 100644 --- a/db/migrate/20100221003655_create_forum_topics.rb +++ b/db/migrate/20100221003655_create_forum_topics.rb @@ -11,7 +11,7 @@ class CreateForumTopics < ActiveRecord::Migration t.column :text_index, "tsvector", :null => false t.timestamps end - + add_index :forum_topics, :creator_id execute "CREATE INDEX index_forum_topics_on_text_index ON forum_topics USING GIN (text_index)" diff --git a/db/migrate/20100223001012_create_post_disapprovals.rb b/db/migrate/20100223001012_create_post_disapprovals.rb index 8ce9c2e39..3ca5ccbd5 100644 --- a/db/migrate/20100223001012_create_post_disapprovals.rb +++ b/db/migrate/20100223001012_create_post_disapprovals.rb @@ -5,7 +5,7 @@ class CreatePostDisapprovals < ActiveRecord::Migration t.column :post_id, :integer, :null => false t.timestamps end - + add_index :post_disapprovals, :user_id add_index :post_disapprovals, :post_id end diff --git a/db/migrate/20100224171915_create_notes.rb b/db/migrate/20100224171915_create_notes.rb index 235263b5a..69fbbe362 100644 --- a/db/migrate/20100224171915_create_notes.rb +++ b/db/migrate/20100224171915_create_notes.rb @@ -12,7 +12,7 @@ class CreateNotes < ActiveRecord::Migration t.column :body_index, "tsvector", :null => false t.timestamps end - + add_index :notes, :creator_id add_index :notes, :post_id execute "CREATE INDEX index_notes_on_body_index ON notes USING GIN (body_index)" diff --git a/db/migrate/20100224172146_create_note_versions.rb b/db/migrate/20100224172146_create_note_versions.rb index c6104be72..fde7aaa47 100644 --- a/db/migrate/20100224172146_create_note_versions.rb +++ b/db/migrate/20100224172146_create_note_versions.rb @@ -13,7 +13,7 @@ class CreateNoteVersions < ActiveRecord::Migration t.column :body, :text, :null => false t.timestamps end - + add_index :note_versions, :note_id add_index :note_versions, :post_id add_index :note_versions, :updater_id diff --git a/db/migrate/20100307073438_create_tag_subscriptions.rb b/db/migrate/20100307073438_create_tag_subscriptions.rb index 02bebb969..932c71476 100644 --- a/db/migrate/20100307073438_create_tag_subscriptions.rb +++ b/db/migrate/20100307073438_create_tag_subscriptions.rb @@ -10,7 +10,7 @@ class CreateTagSubscriptions < ActiveRecord::Migration t.column :is_opted_in, :boolean, :null => false, :default => false t.timestamps end - + add_index :tag_subscriptions, :creator_id add_index :tag_subscriptions, :name end diff --git a/db/migrate/20100309211553_create_janitor_trials.rb b/db/migrate/20100309211553_create_janitor_trials.rb index d16fd7c9d..dbb995599 100644 --- a/db/migrate/20100309211553_create_janitor_trials.rb +++ b/db/migrate/20100309211553_create_janitor_trials.rb @@ -6,7 +6,7 @@ class CreateJanitorTrials < ActiveRecord::Migration t.column :original_level, :integer, :null => false t.timestamps end - + add_index :janitor_trials, :user_id end diff --git a/db/migrate/20100318213503_create_ip_bans.rb b/db/migrate/20100318213503_create_ip_bans.rb index ba5d3d423..cd8035047 100644 --- a/db/migrate/20100318213503_create_ip_bans.rb +++ b/db/migrate/20100318213503_create_ip_bans.rb @@ -6,7 +6,7 @@ class CreateIpBans < ActiveRecord::Migration t.column :reason, :text, :null => false t.timestamps end - + add_index :ip_bans, :ip_addr, :unique => true end diff --git a/db/migrate/20100826232512_create_delayed_jobs.rb b/db/migrate/20100826232512_create_delayed_jobs.rb index 9e3475a4a..0c6a50396 100644 --- a/db/migrate/20100826232512_create_delayed_jobs.rb +++ b/db/migrate/20100826232512_create_delayed_jobs.rb @@ -11,7 +11,7 @@ class CreateDelayedJobs < ActiveRecord::Migration table.string :locked_by # Who is working on this object (if locked) table.timestamps end - + add_index :delayed_jobs, :run_at end diff --git a/db/migrate/20110328215652_create_post_flags.rb b/db/migrate/20110328215652_create_post_flags.rb index b151acc1a..f52f09c00 100644 --- a/db/migrate/20110328215652_create_post_flags.rb +++ b/db/migrate/20110328215652_create_post_flags.rb @@ -8,7 +8,7 @@ class CreatePostFlags < ActiveRecord::Migration t.column :is_resolved, :boolean, :null => false, :default => false t.timestamps end - + add_index :post_flags, :post_id add_index :post_flags, :creator_id add_index :post_flags, :creator_ip_addr diff --git a/db/migrate/20110328215701_create_post_appeals.rb b/db/migrate/20110328215701_create_post_appeals.rb index 27b889bea..b238ae8bf 100644 --- a/db/migrate/20110328215701_create_post_appeals.rb +++ b/db/migrate/20110328215701_create_post_appeals.rb @@ -7,7 +7,7 @@ class CreatePostAppeals < ActiveRecord::Migration t.column :reason, :text t.timestamps end - + add_index :post_appeals, :post_id add_index :post_appeals, :creator_id add_index :post_appeals, :creator_ip_addr diff --git a/db/migrate/20110607194023_create_pool_versions.rb b/db/migrate/20110607194023_create_pool_versions.rb index 194b7595e..5d5fb97e3 100644 --- a/db/migrate/20110607194023_create_pool_versions.rb +++ b/db/migrate/20110607194023_create_pool_versions.rb @@ -7,7 +7,7 @@ class CreatePoolVersions < ActiveRecord::Migration t.column :updater_ip_addr, "inet", :null => false t.timestamps end - + add_index :pool_versions, :pool_id add_index :pool_versions, :updater_id add_index :pool_versions, :updater_ip_addr diff --git a/db/migrate/20111101212358_create_news_updates.rb b/db/migrate/20111101212358_create_news_updates.rb index 13773d5e7..7825828ca 100644 --- a/db/migrate/20111101212358_create_news_updates.rb +++ b/db/migrate/20111101212358_create_news_updates.rb @@ -6,7 +6,7 @@ class CreateNewsUpdates < ActiveRecord::Migration t.column :updater_id, :integer, :null => false t.timestamps end - + add_index :news_updates, :created_at end end diff --git a/db/migrate/20130305005138_add_bcrypt_fields_to_users.rb b/db/migrate/20130305005138_add_bcrypt_fields_to_users.rb index 5e2b54bbf..f1292e897 100644 --- a/db/migrate/20130305005138_add_bcrypt_fields_to_users.rb +++ b/db/migrate/20130305005138_add_bcrypt_fields_to_users.rb @@ -1,7 +1,7 @@ class AddBcryptFieldsToUsers < ActiveRecord::Migration def change execute "set statement_timeout = 0" - + add_column :users, :bcrypt_password_hash, :text end end diff --git a/db/seeds.rb b/db/seeds.rb index 96bfbcf4d..2007ef34c 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -8,7 +8,7 @@ if User.count == 0 :password => "password1", :password_confirmation => "password1" ) - + 0.upto(100) do |i| User.create( :name => i.to_s * 5, @@ -32,7 +32,7 @@ if Upload.count == 0 height = rand(2000) + 100 url = "http://ipsumimage.appspot.com/#{width}x#{height}" tags = (i * i * i).to_s.scan(/./).uniq.join(" ") - + Upload.create(:source => url, :content_type => "image/gif", :rating => "q", :tag_string => tags, :server => Socket.gethostname) end else @@ -64,7 +64,7 @@ if Note.count == 0 Post.all.each do |post| rand(10).times do note = Note.create(:post_id => post.id, :x => 0, :y => 0, :width => 100, :height => 100, :body => Time.now.to_f.to_s) - + rand(30).times do |i| note.update_attributes(:body => (i * i).to_s) end @@ -85,7 +85,7 @@ end if TagAlias.count == 0 puts "Creating tag aliases" - + 100.upto(199) do |i| TagAlias.create(:antecedent_name => i.to_s, :consequent_name => (i * 100).to_s) end @@ -105,7 +105,7 @@ end if Pool.count == 0 puts "Creating pools" - + 1.upto(20) do |i| pool = Pool.create(:name => i.to_s) rand(33).times do |j| @@ -122,16 +122,16 @@ if Favorite.count == 0 post.add_favorite!(user) post.add_favorite!(CurrentUser.user) end -else +else puts "Skipping favorites" end if ForumTopic.count == 0 puts "Creating forum posts" - + 100.times do |i| topic = ForumTopic.create(:title => Time.now.to_f.to_s) - + rand(100).times do |j| post = ForumPost.create(:topic_id => topic.id, :body => Time.now.to_f.to_s) end diff --git a/lib/danbooru/paginator/active_record_extension.rb b/lib/danbooru/paginator/active_record_extension.rb index dd00bbca0..63ff78c46 100644 --- a/lib/danbooru/paginator/active_record_extension.rb +++ b/lib/danbooru/paginator/active_record_extension.rb @@ -4,18 +4,18 @@ module Danbooru module Paginator module ActiveRecordExtension extend ActiveSupport::Concern - + module ClassMethods def paginate(page, options = {}) @paginator_options = options - + if use_sequential_paginator?(page) paginate_sequential(page) else paginate_numbered(page) end end - + def use_sequential_paginator?(page) page =~ /[ab]\d+/i end @@ -32,11 +32,11 @@ module Danbooru def paginate_sequential_before(before_id = nil) c = limit(records_per_page) - + if before_id.to_i > 0 c = c.where("id < ?", before_id.to_i) end - + c.reorder("id desc").tap do |obj| obj.extend(SequentialCollectionExtension) obj.sequential_paginator_mode = :before @@ -49,14 +49,14 @@ module Danbooru obj.sequential_paginator_mode = :after end end - + def paginate_numbered(page) page = [page.to_i, 1].max - + if page > Danbooru.config.max_numbered_pages raise ::Danbooru::Paginator::PaginationError.new("You cannot go beyond page #{Danbooru.config.max_numbered_pages}. Please narrow your search terms.") end - + limit(records_per_page).offset((page - 1) * records_per_page).tap do |obj| obj.extend(NumberedCollectionExtension) if records_per_page > 0 @@ -67,11 +67,11 @@ module Danbooru obj.current_page = page end end - + def records_per_page option_for(:limit).to_i end - + # When paginating large tables, we want to avoid doing an expensive count query # when the result won't even be used. So when calling paginate you can pass in # an optional :search_count key which points to the search params. If these params @@ -86,7 +86,7 @@ module Danbooru limit = 1000 end limit - + when :count if @paginator_options.has_key?(:search_count) && @paginator_options[:search_count].blank? 1_000_000 @@ -95,14 +95,14 @@ module Danbooru else nil end - + end end # taken from kaminari (https://github.com/amatsuda/kaminari) def total_count return option_for(:count) if option_for(:count) - + c = except(:offset, :limit, :order) c = c.reorder(nil) c = c.count diff --git a/lib/danbooru/paginator/numbered_collection_extension.rb b/lib/danbooru/paginator/numbered_collection_extension.rb index b3dc48ace..a552eb296 100644 --- a/lib/danbooru/paginator/numbered_collection_extension.rb +++ b/lib/danbooru/paginator/numbered_collection_extension.rb @@ -2,11 +2,11 @@ module Danbooru module Paginator module NumberedCollectionExtension attr_accessor :current_page, :total_pages - + def is_first_page? current_page == 1 end - + def is_last_page? current_page >= total_pages end diff --git a/lib/danbooru/paginator/sequential_collection_extension.rb b/lib/danbooru/paginator/sequential_collection_extension.rb index 85a240168..071b3a853 100644 --- a/lib/danbooru/paginator/sequential_collection_extension.rb +++ b/lib/danbooru/paginator/sequential_collection_extension.rb @@ -2,15 +2,15 @@ module Danbooru module Paginator module SequentialCollectionExtension attr_accessor :sequential_paginator_mode - + def is_first_page? size == 0 end - + def is_last_page? size == 0 end - + def to_a if sequential_paginator_mode == :before super diff --git a/lib/danbooru_image_resizer/danbooru_image_resizer.rb b/lib/danbooru_image_resizer/danbooru_image_resizer.rb index 860ab6649..649519b9a 100644 --- a/lib/danbooru_image_resizer/danbooru_image_resizer.rb +++ b/lib/danbooru_image_resizer/danbooru_image_resizer.rb @@ -7,28 +7,28 @@ module Danbooru # wider than it is tall geometry = "#{Danbooru.config.small_image_width}x#{Danbooru.config.small_image_width}>" end - + image.change_geometry(geometry) do |new_width, new_height, img| img.resize!(new_width, new_height) width = new_width height = new_height end - + image = flatten(image, width, height) - + image.write(write_path) do self.quality = resize_quality end - + image.destroy! FileUtils.chmod(0664, write_path) end - + def flatten(image, width, height) if image.alpha? # since jpeg can't represent transparency, we need to create an image list, # put a white image on the bottom, then flatten it. - + list = Magick::ImageList.new list.new_image(width, height) do self.background_color = "#FFFFFF" diff --git a/lib/imagesize/setup.rb b/lib/imagesize/setup.rb index 424a5f37c..9f0c8267a 100755 --- a/lib/imagesize/setup.rb +++ b/lib/imagesize/setup.rb @@ -659,7 +659,7 @@ module FileOperations def ruby(*args) command config('rubyprog'), *args end - + def make(task = nil) command(*[config('makeprog'), task].compact) end @@ -722,7 +722,7 @@ module HookScriptAPI def srcdirectory?(path) File.dir?(srcfile(path)) end - + def srcfile?(path) File.file?(srcfile(path)) end @@ -826,7 +826,7 @@ class ToplevelInstaller __send__ "exec_#{task}" end end - + def run_metaconfigs @config.load_script "#{@ardir}/metaconfig" end @@ -1404,7 +1404,7 @@ class Installer end # picked up many entries from cvs-1.11.1/src/ignore.c - JUNK_FILES = %w( + JUNK_FILES = %w( core RCSLOG tags TAGS .make.state .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb *~ *.old *.bak *.BAK *.orig *.rej _$* *$ diff --git a/lib/imagesize/test/test_image_size.rb b/lib/imagesize/test/test_image_size.rb index 46d743115..6da7e81fa 100755 --- a/lib/imagesize/test/test_image_size.rb +++ b/lib/imagesize/test/test_image_size.rb @@ -3,9 +3,9 @@ require './test/test_helper.rb' class TestImageSize < Test::Unit::TestCase def setup - @files = ['4_1_2.gif', '2-4-7.png', 'tokyo_tower.jpg', 'bmp.bmp', - 'ppm.ppm', 'pgm.pgm', 'pbm.pbm', - 'cursor.xbm', 'tiff.tiff', 'test.xpm', + @files = ['4_1_2.gif', '2-4-7.png', 'tokyo_tower.jpg', 'bmp.bmp', + 'ppm.ppm', 'pgm.pgm', 'pbm.pbm', + 'cursor.xbm', 'tiff.tiff', 'test.xpm', 'tower_e.gif.psd', 'detect.swf'] @results = [ ['GIF' ,668,481], diff --git a/script/fixes/005.rb b/script/fixes/005.rb index e96efa537..29e2543a8 100644 --- a/script/fixes/005.rb +++ b/script/fixes/005.rb @@ -6,7 +6,7 @@ Post.where("image_width > 850").find_each do |post| if !post.is_image? next end - + if !File.exists?(post.file_path) puts "NOT FOUND: #{post.id}" next @@ -16,19 +16,19 @@ Post.where("image_width > 850").find_each do |post| puts "NOT FOUND: #{post.id}" next end - + resize = false - + if !File.exists?(post.large_file_path) puts "LARGE NOT FOUND: #{post.id}" resize = true end - + if File.size(post.large_file_path) == 0 puts "LARGE NOT FOUND: #{post.id}" resize = true end - + if !resize File.open(post.large_file_path, "r") do |file| image_size = ImageSize.new(file) @@ -39,7 +39,7 @@ Post.where("image_width > 850").find_each do |post| end end end - + if resize puts "RESIZING #{post.id}" upload = Upload.new diff --git a/test/factories/tag.rb b/test/factories/tag.rb index 3ea55a4e6..f0b988acf 100644 --- a/test/factories/tag.rb +++ b/test/factories/tag.rb @@ -5,7 +5,7 @@ FactoryGirl.define do category {Tag.categories.general} related_tags "" related_tags_updated_at {Time.now} - + factory(:artist_tag) do category {Tag.categories.artist} end diff --git a/test/factories/tag_alias.rb b/test/factories/tag_alias.rb index d5f5bc6d6..e0b022750 100644 --- a/test/factories/tag_alias.rb +++ b/test/factories/tag_alias.rb @@ -2,7 +2,7 @@ FactoryGirl.define do factory :tag_alias do antecedent_name "aaa" consequent_name "bbb" - + after(:create) do |tag_alias| tag_alias.process! end diff --git a/test/factories/tag_implication.rb b/test/factories/tag_implication.rb index 99da38b1f..e328fad8a 100644 --- a/test/factories/tag_implication.rb +++ b/test/factories/tag_implication.rb @@ -2,7 +2,7 @@ FactoryGirl.define do factory :tag_implication do antecedent_name "aaa" consequent_name "bbb" - + after(:create) do |tag_implication| tag_implication.process! end diff --git a/test/factories/upload.rb b/test/factories/upload.rb index 83db31400..7aa0b5f43 100644 --- a/test/factories/upload.rb +++ b/test/factories/upload.rb @@ -9,7 +9,7 @@ FactoryGirl.define do status "pending" server Socket.gethostname source "xxx" - + factory(:source_upload) do source "http://www.google.com/intl/en_ALL/images/logo.gif" end diff --git a/test/factories/user.rb b/test/factories/user.rb index 79c4663a9..8a9557936 100644 --- a/test/factories/user.rb +++ b/test/factories/user.rb @@ -9,7 +9,7 @@ FactoryGirl.define do level 20 last_logged_in_at {Time.now} favorite_count 0 - + factory(:banned_user) do is_banned true ban {|x| x.association(:ban)} diff --git a/test/functional/advertisements_controller_test.rb b/test/functional/advertisements_controller_test.rb index 844868812..a17d84b05 100644 --- a/test/functional/advertisements_controller_test.rb +++ b/test/functional/advertisements_controller_test.rb @@ -6,27 +6,27 @@ class AdvertisementsControllerTest < ActionController::TestCase @ad = FactoryGirl.create(:advertisement) @advertiser = FactoryGirl.create(:admin_user) end - + should "get the new page" do get :new, {}, {:user_id => @advertiser.id} assert_response :success end - + should "get the edit page" do get :edit, {:id => @ad.id}, {:user_id => @advertiser.id} assert_response :success end - + should "get the index page" do get :index, {}, {:user_id => @advertiser.id} assert_response :success end - + should "get the show page" do get :show, {:id => @ad.id}, {:user_id => @advertiser.id} assert_response :success end - + should "create an ad" do assert_difference("Advertisement.count", 1) do post :create, {:advertisement => FactoryGirl.attributes_for(:advertisement)}, {:user_id => @advertiser.id} @@ -34,21 +34,21 @@ class AdvertisementsControllerTest < ActionController::TestCase ad = Advertisement.last assert_redirected_to(advertisement_path(ad)) end - + should "update an ad" do post :update, {:id => @ad.id, :advertisement => {:width => 100}}, {:user_id => @advertiser.id} ad = Advertisement.last assert_equal(100, ad.width) assert_redirected_to(advertisement_path(ad)) end - + should "delete an ad" do assert_difference("Advertisement.count", -1) do post :destroy, {:id => @ad.id}, {:user_id => @advertiser.id} end assert_redirected_to(advertisements_path) end - + should "block non-advertisers" do regular_user = FactoryGirl.create(:user) get :index, {}, {:user_id => regular_user.id} diff --git a/test/functional/artist_versions_controller_test.rb b/test/functional/artist_versions_controller_test.rb index caee0f4b1..8d2f09507 100644 --- a/test/functional/artist_versions_controller_test.rb +++ b/test/functional/artist_versions_controller_test.rb @@ -7,17 +7,17 @@ class ArtistVersionsControllerTest < ActionController::TestCase CurrentUser.ip_addr = "127.0.0.1" @artist = FactoryGirl.create(:artist) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "get the index page" do get :index assert_response :success end - + should "get the index page when searching for something" do get :index, {:search => {:name => @artist.name}} assert_response :success diff --git a/test/functional/artists_controller_test.rb b/test/functional/artists_controller_test.rb index 2ea722932..61d57aa16 100644 --- a/test/functional/artists_controller_test.rb +++ b/test/functional/artists_controller_test.rb @@ -8,38 +8,38 @@ class ArtistsControllerTest < ActionController::TestCase @artist = FactoryGirl.create(:artist) @user = FactoryGirl.create(:user) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "get the new page" do get :new, {}, {:user_id => @user.id} assert_response :success end - + should "get the edit page" do get :edit, {:id => @artist.id}, {:user_id => @user.id} assert_response :success end - + should "get the show page" do get :show, {:id => @artist.id} assert_response :success end - + should "get the show page for a negated tag" do @artist.update_attribute(:name, "-aaa") get :show, {:id => @artist.id} assert_response :success end - + should "get the index page" do get :index assert_response :success end - + should "create an artist" do assert_difference("Artist.count", 1) do post :create, {:artist => FactoryGirl.attributes_for(:artist)}, {:user_id => @user.id} @@ -47,14 +47,14 @@ class ArtistsControllerTest < ActionController::TestCase artist = Artist.last assert_redirected_to(artist_path(artist)) end - + should "update an artist" do post :update, {:id => @artist.id, :artist => {:name => "xxx"}}, {:user_id => @user.id} @artist.reload assert_equal("xxx", @artist.name) assert_redirected_to(artist_path(@artist)) end - + should "revert an artist" do @artist.update_attributes(:name => "xyz") @artist.update_attributes(:name => "abc") diff --git a/test/functional/bans_controller_test.rb b/test/functional/bans_controller_test.rb index 380845026..bd6e320d9 100644 --- a/test/functional/bans_controller_test.rb +++ b/test/functional/bans_controller_test.rb @@ -9,32 +9,32 @@ class BansControllerTest < ActionController::TestCase @user = FactoryGirl.create(:user) @ban = FactoryGirl.create(:ban, :user_id => @user.id) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "get the new page" do get :new, {}, {:user_id => @mod.id} assert_response :success end - + should "get the edit page" do get :edit, {:id => @ban.id}, {:user_id => @mod.id} assert_response :success end - + should "get the show page" do get :show, {:id => @ban.id} assert_response :success end - + should "get the index page" do get :index assert_response :success end - + should "create a ban" do assert_difference("Ban.count", 1) do post :create, {:ban => {:duration => 60, :reason => "xxx", :user_id => @user.id}}, {:user_id => @mod.id} @@ -42,14 +42,14 @@ class BansControllerTest < ActionController::TestCase ban = Ban.last assert_redirected_to(ban_path(ban)) end - + should "update a ban" do post :update, {:id => @ban.id, :ban => {:reason => "xxx", :duration => 60}}, {:user_id => @mod.id} @ban.reload assert_equal("xxx", @ban.reason) assert_redirected_to(ban_path(@ban)) end - + should "destroy a ban" do assert_difference("Ban.count", -1) do post :destroy, {:id => @ban.id}, {:user_id => @mod.id} diff --git a/test/functional/comment_votes_controller_test.rb b/test/functional/comment_votes_controller_test.rb index 1bc9ef58b..7f9ef7960 100644 --- a/test/functional/comment_votes_controller_test.rb +++ b/test/functional/comment_votes_controller_test.rb @@ -8,19 +8,19 @@ class CommentVotesControllerTest < ActionController::TestCase Danbooru.config.stubs(:member_comment_time_threshold).returns(1.week.from_now) @comment = FactoryGirl.create(:comment) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "create a vote" do assert_difference("CommentVote.count", 1) do post :create, {:format => "js", :comment_id => @comment.id, :score => 1}, {:user_id => @user.id} assert_response :success end end - + should "fail silently on errors" do FactoryGirl.create(:comment_vote, :comment => @comment) assert_difference("CommentVote.count", 0) do diff --git a/test/functional/comments_controller_test.rb b/test/functional/comments_controller_test.rb index a8f216faa..41fbeceb8 100644 --- a/test/functional/comments_controller_test.rb +++ b/test/functional/comments_controller_test.rb @@ -10,7 +10,7 @@ class CommentsControllerTest < ActionController::TestCase @comment = FactoryGirl.create(:comment, :post => @post) @user = FactoryGirl.create(:moderator_user) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil @@ -21,20 +21,20 @@ class CommentsControllerTest < ActionController::TestCase get :index, {:group_by => "post"} assert_response :success end - + should "render by comment" do get :index, {:group_by => "comment"} assert_response :success end end - + context "update action" do should "update the comment" do post :update, {:id => @comment.id, :comment => {:body => "abc"}}, {:user_id => @comment.creator_id} assert_redirected_to post_path(@comment.post) end end - + context "create action"do should "create a comment" do assert_difference("Comment.count", 1) do diff --git a/test/functional/dmails_controller_test.rb b/test/functional/dmails_controller_test.rb index 2c0d544bf..5690f2ed8 100644 --- a/test/functional/dmails_controller_test.rb +++ b/test/functional/dmails_controller_test.rb @@ -9,18 +9,18 @@ class DmailsControllerTest < ActionController::TestCase CurrentUser.ip_addr = "127.0.0.1" @dmail = FactoryGirl.create(:dmail, :owner => @user) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "new action" do should "get the page" do get :new, {}, {:user_id => @user.id} assert_response :success end - + context "with a respond_to_id" do should "prefill the fields" do get :new, {:respond_to_id => @dmail}, {:user_id => @user.id} @@ -28,7 +28,7 @@ class DmailsControllerTest < ActionController::TestCase assert_not_nil assigns(:dmail) assert_equal(@dmail.from_id, assigns(:dmail).to_id) end - + context "and a forward flag" do should "not populate the to field" do get :new, {:respond_to_id => @dmail, :forward => true}, {:user_id => @user.id} @@ -39,7 +39,7 @@ class DmailsControllerTest < ActionController::TestCase end end end - + context "index action" do should "show dmails owned by the current user" do get :index, {:owner_id_equals => @dmail.owner_id, :folder => "sent"}, {:user_id => @dmail.owner_id} @@ -50,32 +50,32 @@ class DmailsControllerTest < ActionController::TestCase assert_response :success assert_equal(1, assigns[:dmails].size) end - + should "not show dmails not owned by the current user" do get :index, {:owner_id_equals => @dmail.owner_id}, {:user_id => @unrelated_user.id} assert_response :success assert_equal(0, assigns[:dmails].size) end end - + context "show action" do should "show dmails owned by the current user" do get :show, {:id => @dmail.id}, {:user_id => @dmail.owner_id} assert_response :success end - + should "not show dmails not owned by the current user" do assert_raise(User::PrivilegeError) do get :show, {:id => @dmail.id}, {:user_id => @unrelated_user.id} end end end - + context "create action" do setup do @user_2 = FactoryGirl.create(:user) end - + should "create two messages, one for the sender and one for the recipient" do assert_difference("Dmail.count", 2) do dmail_attribs = {:to_id => @user_2.id, :title => "abc", :body => "abc"} @@ -84,7 +84,7 @@ class DmailsControllerTest < ActionController::TestCase end end end - + context "destroy action" do should "allow deletion if the dmail is owned by the current user" do assert_difference("Dmail.count", -1) do @@ -92,7 +92,7 @@ class DmailsControllerTest < ActionController::TestCase assert_redirected_to dmails_path end end - + should "not allow deletion if the dmail is not owned by the current user" do assert_difference("Dmail.count", 0) do assert_raises(User::PrivilegeError) do diff --git a/test/functional/favorites_controller_test.rb b/test/functional/favorites_controller_test.rb index e44a1e6b8..c25c73507 100644 --- a/test/functional/favorites_controller_test.rb +++ b/test/functional/favorites_controller_test.rb @@ -7,32 +7,32 @@ class FavoritesControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @post = FactoryGirl.create(:post) @post.add_favorite!(@user) end - + context "with a specified tags parameter" do should "redirect to the posts controller" do get :index, {:tags => "fav:#{@user.name} abc"}, {:user_id => @user} assert_redirected_to(posts_path(:tags => "fav:#{@user.name} abc")) end end - + should "display the current user's favorites" do get :index, {}, {:user_id => @user.id} assert_response :success assert_not_nil(assigns(:favorite_set)) end end - + context "create action" do setup do @post = FactoryGirl.create(:post) @@ -44,13 +44,13 @@ class FavoritesControllerTest < ActionController::TestCase end end end - + context "destroy action" do setup do @post = FactoryGirl.create(:post) @post.add_favorite!(@user) end - + should "remove the favorite from the current user" do assert_difference("Favorite.count", -1) do post :destroy, {:format => "js", :id => @post.id}, {:user_id => @user.id} diff --git a/test/functional/forum_posts_controller_test.rb b/test/functional/forum_posts_controller_test.rb index e4647560c..0b672fdb8 100644 --- a/test/functional/forum_posts_controller_test.rb +++ b/test/functional/forum_posts_controller_test.rb @@ -11,25 +11,25 @@ class ForumPostsControllerTest < ActionController::TestCase @forum_topic = FactoryGirl.create(:forum_topic, :title => "my forum topic", :creator => @user) @forum_post = FactoryGirl.create(:forum_post, :topic_id => @forum_topic.id, :body => "xxx") end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do should "list all forum posts" do get :index assert_response :success end - + context "with search conditions" do should "list all matching forum posts" do get :index, {:search => {:body_matches => "xxx"}} assert_response :success assert_equal(1, assigns(:forum_posts).size) end - + should "list nothing for when the search matches nothing" do get :index, {:search => {:body_matches => "bababa"}} assert_response :success @@ -37,32 +37,32 @@ class ForumPostsControllerTest < ActionController::TestCase end end end - + context "edit action" do should "render if the editor is the creator of the topic" do get :edit, {:id => @forum_post.id}, {:user_id => @user.id} assert_response :success end - + should "render if the editor is a moderator" do get :edit, {:id => @forum_post.id}, {:user_id => @mod.id} assert_response :success end - + should "fail if the editor is not the creator of the topic and is not a moderator" do assert_raises(User::PrivilegeError) do get :edit, {:id => @forum_post.id}, {:user_id => @other_user.id} end end end - + context "new action" do should "render" do get :new, {}, {:user_id => @user.id, :topic_id => @forum_topic.id}, {:user_id => @user.id} assert_response :success end end - + context "create action" do should "create a new forum post" do assert_difference("ForumPost.count", 1) do @@ -73,7 +73,7 @@ class ForumPostsControllerTest < ActionController::TestCase assert_redirected_to(forum_topic_path(@forum_topic, :page => 1)) end end - + context "destroy action" do should "destroy the posts" do CurrentUser.user = @mod @@ -83,12 +83,12 @@ class ForumPostsControllerTest < ActionController::TestCase assert_equal(true, @forum_post.is_deleted?) end end - + context "undelete action" do setup do @forum_post.update_attribute(:is_deleted, true) end - + should "restore the post" do post :undelete, {:id => @forum_post.id}, {:user_id => @user.id} assert_redirected_to(forum_post_path(@forum_post)) diff --git a/test/functional/forum_topics_controller_test.rb b/test/functional/forum_topics_controller_test.rb index 812a7da9b..964156ce9 100644 --- a/test/functional/forum_topics_controller_test.rb +++ b/test/functional/forum_topics_controller_test.rb @@ -10,25 +10,25 @@ class ForumTopicsControllerTest < ActionController::TestCase @mod = FactoryGirl.create(:moderator_user) @forum_topic = FactoryGirl.create(:forum_topic, :title => "my forum topic", :creator => @user) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do should "list all forum topics" do get :index assert_response :success end - + context "with search conditions" do should "list all matching forum topics" do get :index, {:search => {:title_matches => "forum"}} assert_response :success assert_equal(1, assigns(:forum_topics).size) end - + should "list nothing for when the search matches nothing" do get :index, {:search => {:title_matches => "bababa"}} assert_response :success @@ -36,32 +36,32 @@ class ForumTopicsControllerTest < ActionController::TestCase end end end - + context "edit action" do should "render if the editor is the creator of the topic" do get :edit, {:id => @forum_topic.id}, {:user_id => @user.id} assert_response :success end - + should "render if the editor is a moderator" do get :edit, {:id => @forum_topic.id}, {:user_id => @mod.id} assert_response :success end - + should "fail if the editor is not the creator of the topic and is not a moderator" do assert_raises(User::PrivilegeError) do get :edit, {:id => @forum_topic.id}, {:user_id => @other_user.id} end end end - + context "new action" do should "render" do get :new, {}, {:user_id => @user.id} assert_response :success end end - + context "create action" do should "create a new forum topic and post" do assert_difference(["ForumPost.count", "ForumTopic.count"], 1) do @@ -72,12 +72,12 @@ class ForumTopicsControllerTest < ActionController::TestCase assert_redirected_to(forum_topic_path(forum_topic)) end end - + context "destroy action" do setup do @post = FactoryGirl.create(:forum_post, :topic_id => @forum_topic.id) end - + should "destroy the topic and any associated posts" do post :destroy, {:id => @forum_topic.id}, {:user_id => @user.id} assert_redirected_to(forum_topic_path(@forum_topic)) @@ -85,12 +85,12 @@ class ForumTopicsControllerTest < ActionController::TestCase assert_equal(true, @forum_topic.is_deleted?) end end - + context "undelete action" do setup do @forum_topic.update_attribute(:is_deleted, true) end - + should "restore the topic" do post :undelete, {:id => @forum_topic.id}, {:user_id => @user.id} assert_redirected_to(forum_topic_path(@forum_topic)) diff --git a/test/functional/ip_bans_controller_test.rb b/test/functional/ip_bans_controller_test.rb index b4ef9d7f5..f6a30d952 100644 --- a/test/functional/ip_bans_controller_test.rb +++ b/test/functional/ip_bans_controller_test.rb @@ -7,7 +7,7 @@ class IpBansControllerTest < ActionController::TestCase CurrentUser.user = @admin CurrentUser.ip_addr = "127.0.0.1" end - + context "new action" do should "render" do get :new, {}, {:user_id => @admin.id} @@ -22,17 +22,17 @@ class IpBansControllerTest < ActionController::TestCase end end end - + context "index action" do setup do FactoryGirl.create(:ip_ban) end - + should "render" do get :index, {}, {:user_id => @admin.id} assert_response :success end - + context "with search parameters" do should "render" do get :index, {:search => {:ip_addr => "1.2.3.4"}}, {:user_id => @admin.id} @@ -40,12 +40,12 @@ class IpBansControllerTest < ActionController::TestCase end end end - + context "destroy action" do setup do @ip_ban = FactoryGirl.create(:ip_ban) end - + should "destroy an ip ban" do assert_difference("IpBan.count", -1) do post :destroy, {:id => @ip_ban.id, :format => "js"}, {:user_id => @admin.id} diff --git a/test/functional/janitor_trials_controller_test.rb b/test/functional/janitor_trials_controller_test.rb index 135d217c3..8d90b9c15 100644 --- a/test/functional/janitor_trials_controller_test.rb +++ b/test/functional/janitor_trials_controller_test.rb @@ -8,11 +8,11 @@ class JanitorTrialsControllerTest < ActionController::TestCase CurrentUser.user = @admin CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil end - + context "new action" do should "render" do get :new, {}, {:user_id => @admin.id} @@ -27,12 +27,12 @@ class JanitorTrialsControllerTest < ActionController::TestCase end end end - + context "promote action" do setup do @janitor_trial = FactoryGirl.create(:janitor_trial, :user_id => @user.id) end - + should "promote the janitor trial" do assert_difference("JanitorTrial.count", -1) do post :promote, {:id => @janitor_trial.id}, {:user_id => @admin.id} @@ -41,12 +41,12 @@ class JanitorTrialsControllerTest < ActionController::TestCase assert(@user.is_janitor?) end end - + context "demote action" do setup do @janitor_trial = FactoryGirl.create(:janitor_trial, :user_id => @user.id) end - + should "demote the janitor trial" do assert_difference("JanitorTrial.count", -1) do post :demote, {:id => @janitor_trial.id}, {:user_id => @admin.id} @@ -55,17 +55,17 @@ class JanitorTrialsControllerTest < ActionController::TestCase assert(!@user.is_janitor?) end end - + context "index action" do setup do FactoryGirl.create(:janitor_trial) end - + should "render" do get :index, {}, {:user_id => @admin.id} assert_response :success end - + context "with search parameters" do should "render" do get :index, {:search => {:user_name => @user.name}}, {:user_id => @admin.id} diff --git a/test/functional/maintenance/user/login_reminders_controller_test.rb b/test/functional/maintenance/user/login_reminders_controller_test.rb index f33357fe1..324ec9682 100644 --- a/test/functional/maintenance/user/login_reminders_controller_test.rb +++ b/test/functional/maintenance/user/login_reminders_controller_test.rb @@ -17,7 +17,7 @@ module Maintenance CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "render the new page" do get :new assert_response :success diff --git a/test/functional/maintenance/user/password_resets_controller_test.rb b/test/functional/maintenance/user/password_resets_controller_test.rb index 1ba087270..b6be2d84f 100644 --- a/test/functional/maintenance/user/password_resets_controller_test.rb +++ b/test/functional/maintenance/user/password_resets_controller_test.rb @@ -16,18 +16,18 @@ module Maintenance CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "render the new page" do get :new assert_response :success end - + context "create action" do context "given invalid parameters" do setup do post :create, {:nonce => {:email => ""}} end - + should "not create a new nonce" do assert_equal(0, UserPasswordResetNonce.count) end @@ -40,7 +40,7 @@ module Maintenance assert_equal(0, ActionMailer::Base.deliveries.size) end end - + context "given valid parameters" do setup do post :create, {:nonce => {:email => @user.email}} @@ -49,7 +49,7 @@ module Maintenance should "create a new nonce" do assert_equal(1, UserPasswordResetNonce.where(:email => @user.email).count) end - + should "redirect to the new page" do assert_redirected_to new_maintenance_user_password_reset_path end @@ -70,7 +70,7 @@ module Maintenance assert_response :success end end - + context "with valid parameters" do setup do @user = FactoryGirl.create(:user) @@ -78,24 +78,24 @@ module Maintenance ActionMailer::Base.deliveries.clear get :edit, :email => @nonce.email, :key => @nonce.key end - + should "succeed" do assert_response :success end end end - + context "update action" do context "with invalid parameters" do setup do get :update end - + should "fail" do assert_redirected_to new_maintenance_user_password_reset_path end end - + context "with valid parameters" do setup do @user = FactoryGirl.create(:user) @@ -104,20 +104,20 @@ module Maintenance @old_password = @user.bcrypt_password_hash post :update, :email => @nonce.email, :key => @nonce.key end - + should "succeed" do assert_redirected_to new_maintenance_user_password_reset_path end - + should "send an email" do assert_equal(1, ActionMailer::Base.deliveries.size) end - + should "change the password" do @user.reload assert_not_equal(@old_password, @user.bcrypt_password_hash) end - + should "delete the nonce" do assert_equal(0, UserPasswordResetNonce.count) end diff --git a/test/functional/moderator/dashboards_controller_test.rb b/test/functional/moderator/dashboards_controller_test.rb index 8a62b3590..dbdff63fd 100644 --- a/test/functional/moderator/dashboards_controller_test.rb +++ b/test/functional/moderator/dashboards_controller_test.rb @@ -15,63 +15,63 @@ module Moderator setup do @mod_action = FactoryGirl.create(:mod_action) end - + should "render" do assert_equal(1, ModAction.count) get :show, {}, {:user_id => @admin.id} assert_response :success end end - + context "for user feedbacks" do setup do @feedback = FactoryGirl.create(:user_feedback) end - + should "render" do assert_equal(1, UserFeedback.count) get :show, {}, {:user_id => @admin.id} assert_response :success end end - + context "for wiki pages" do setup do @wiki_page = FactoryGirl.create(:wiki_page) end - + should "render" do assert_equal(1, WikiPageVersion.count) get :show, {}, {:user_id => @admin.id} assert_response :success end end - + context "for tags and uploads" do setup do @post = FactoryGirl.create(:post) end - + should "render" do assert_equal(1, PostVersion.count) get :show, {}, {:user_id => @admin.id} assert_response :success end end - + context "for notes"do setup do @post = FactoryGirl.create(:post) @note = FactoryGirl.create(:note, :post_id => @post.id) end - + should "render" do assert_equal(1, NoteVersion.count) get :show, {}, {:user_id => @admin.id} assert_response :success end end - + context "for comments" do setup do @users = (0..5).map {FactoryGirl.create(:user)} @@ -79,32 +79,32 @@ module Moderator CurrentUser.scoped(@users[0], "1.2.3.4") do @comment = FactoryGirl.create(:comment) end - + @users.each do |user| CurrentUser.scoped(user, "1.2.3.4") do @comment.vote!(-1) end end end - + should "render" do get :show, {}, {:user_id => @admin.id} assert_response :success end end - + context "for artists" do setup do @artist = FactoryGirl.create(:artist) end - + should "render" do get :show, {}, {:user_id => @admin.id} assert_equal(1, ArtistVersion.count) assert_response :success end end - + context "for flags" do setup do @post = FactoryGirl.create(:post) @@ -116,7 +116,7 @@ module Moderator assert_response :success end end - + context "for appeals" do setup do @post = FactoryGirl.create(:post, :is_deleted => true) diff --git a/test/functional/moderator/invitations_controller_test.rb b/test/functional/moderator/invitations_controller_test.rb index b38664816..d7cc72242 100644 --- a/test/functional/moderator/invitations_controller_test.rb +++ b/test/functional/moderator/invitations_controller_test.rb @@ -8,23 +8,23 @@ module Moderator CurrentUser.user = @mod CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all - + @user_1 = FactoryGirl.create(:user) @user_2 = FactoryGirl.create(:user, :inviter_id => @mod.id) end - + should "render the new page" do get :new, {:invitation => {:name => @user_1.name}}, {:user_id => @mod.id} assert_response :success end - + should "create a new invite" do post :create, {:invitation => {:user_id => @user_1.id, :level => User::Levels::CONTRIBUTOR}}, {:user_id => @mod.id} assert_redirected_to(moderator_invitations_path) @user_1.reload assert_equal(User::Levels::CONTRIBUTOR, @user_1.level) end - + should "list invites" do get :index assert_response :success diff --git a/test/functional/moderator/ip_addrs_controller_test.rb b/test/functional/moderator/ip_addrs_controller_test.rb index 1ced07095..9ee5ba2a6 100644 --- a/test/functional/moderator/ip_addrs_controller_test.rb +++ b/test/functional/moderator/ip_addrs_controller_test.rb @@ -15,7 +15,7 @@ module Moderator get :index, {:search => {:ip_addr => "127.0.0.1"}}, {:user_id => @user.id} assert_response :success end - + should "find by user id" do get :index, {:search => {:user_id => @user.id.to_s}}, {:user_id => @user.id} assert_response :success @@ -25,7 +25,7 @@ module Moderator get :index, {:search => {:user_name => @user.name}}, {:user_id => @user.id} assert_response :success end - + should "render the search page" do get :search, {}, {:user_id => @user.id} assert_response :success diff --git a/test/functional/moderator/post/approvals_controller_test.rb b/test/functional/moderator/post/approvals_controller_test.rb index 0fad190cb..a9df343a0 100644 --- a/test/functional/moderator/post/approvals_controller_test.rb +++ b/test/functional/moderator/post/approvals_controller_test.rb @@ -8,10 +8,10 @@ module Moderator @admin = FactoryGirl.create(:admin_user) CurrentUser.user = @admin CurrentUser.ip_addr = "127.0.0.1" - + @post = FactoryGirl.create(:post, :is_pending => true) end - + context "create action" do should "render" do post :create, {:post_id => @post.id, :format => "js"}, {:user_id => @admin.id} diff --git a/test/functional/moderator/post/disapprovals_controller_test.rb b/test/functional/moderator/post/disapprovals_controller_test.rb index 40a8bda3e..5d62a2629 100644 --- a/test/functional/moderator/post/disapprovals_controller_test.rb +++ b/test/functional/moderator/post/disapprovals_controller_test.rb @@ -8,10 +8,10 @@ module Moderator @admin = FactoryGirl.create(:admin_user) CurrentUser.user = @admin CurrentUser.ip_addr = "127.0.0.1" - + @post = FactoryGirl.create(:post, :is_pending => true) end - + context "create action" do should "render" do assert_difference("PostDisapproval.count", 1) do diff --git a/test/functional/moderator/post/posts_controller_test.rb b/test/functional/moderator/post/posts_controller_test.rb index 4eb449dc5..1eb02ea51 100644 --- a/test/functional/moderator/post/posts_controller_test.rb +++ b/test/functional/moderator/post/posts_controller_test.rb @@ -9,12 +9,12 @@ module Moderator CurrentUser.user = @admin CurrentUser.ip_addr = "127.0.0.1" end - + context "delete action" do setup do @post = FactoryGirl.create(:post) end - + should "render" do post :delete, {:id => @post.id, :reason => "xxx", :format => "js", :commit => "Delete"}, {:user_id => @admin.id} @post.reload @@ -26,7 +26,7 @@ module Moderator setup do @post = FactoryGirl.create(:post, :is_deleted => true) end - + should "render" do post :undelete, {:id => @post.id, :format => "js"}, {:user_id => @admin.id} assert_response :success diff --git a/test/functional/moderator/post/queues_controller_test.rb b/test/functional/moderator/post/queues_controller_test.rb index d6e934109..ec5a95744 100644 --- a/test/functional/moderator/post/queues_controller_test.rb +++ b/test/functional/moderator/post/queues_controller_test.rb @@ -8,10 +8,10 @@ module Moderator @admin = FactoryGirl.create(:admin_user) CurrentUser.user = @admin CurrentUser.ip_addr = "127.0.0.1" - + @post = FactoryGirl.create(:post, :is_pending => true) end - + context "show action" do should "render" do get :show, {}, {:user_id => @admin.id} diff --git a/test/functional/moderator/tags_controller_test.rb b/test/functional/moderator/tags_controller_test.rb index b54764b90..41e4484f6 100644 --- a/test/functional/moderator/tags_controller_test.rb +++ b/test/functional/moderator/tags_controller_test.rb @@ -9,7 +9,7 @@ module Moderator CurrentUser.ip_addr = "127.0.0.1" @post = FactoryGirl.create(:post) end - + should "render the edit action" do get :edit, {}, {:user_id => @user.id} assert_response :success @@ -19,7 +19,7 @@ module Moderator post :update, {:tag => {:predicate => "aaa", :consequent => "bbb"}}, {:user_id => @user.id} assert_redirected_to edit_moderator_tag_path end - + should "fail gracefully if the update action fails" do post :update, {:tag => {:predicate => "", :consequent => "bbb"}}, {:user_id => @user.id} assert_redirected_to edit_moderator_tag_path diff --git a/test/functional/news_updates_controller_test.rb b/test/functional/news_updates_controller_test.rb index 690955125..d6ca95299 100644 --- a/test/functional/news_updates_controller_test.rb +++ b/test/functional/news_updates_controller_test.rb @@ -8,47 +8,47 @@ class NewsUpdatesControllerTest < ActionController::TestCase CurrentUser.ip_addr = "127.0.0.1" @news_update = FactoryGirl.create(:news_update) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do should "render" do get :index, {}, :user_id => @admin.id assert_response :success end end - + context "new action" do should "render" do get :new, {}, :user_id => @admin.id assert_response :success end end - + context "edit action" do should "render" do get :edit, {:id => @news_update.id}, {:user_id => @admin.id} assert_response :success end end - + context "update action" do should "work" do post :update, {:id => @news_update.id, :news_update => {:message => "zzz"}}, {:user_id => @admin.id} assert_redirected_to(news_updates_path) end end - + context "create action" do should "work" do post :create, {:news_update => {:message => "zzz"}}, {:user_id => @admin.id} assert_redirected_to(news_updates_path) end end - + context "destroy action" do should "work" do post :destroy, {:id => @news_update.id, :format => "js"}, {:user_id => @admin.id} diff --git a/test/functional/note_versions_controller_test.rb b/test/functional/note_versions_controller_test.rb index dae829f0f..89dd9d12c 100644 --- a/test/functional/note_versions_controller_test.rb +++ b/test/functional/note_versions_controller_test.rb @@ -7,33 +7,33 @@ class NoteVersionsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @note = FactoryGirl.create(:note) @user_2 = FactoryGirl.create(:user) - + CurrentUser.scoped(@user_2, "1.2.3.4") do @note.update_attributes(:body => "1 2") end - + CurrentUser.scoped(@user, "1.2.3.4") do @note.update_attributes(:body => "1 2 3") end end - + should "list all versions" do get :index assert_response :success assert_not_nil(assigns(:note_versions)) assert_equal(3, assigns(:note_versions).size) end - + should "list all versions that match the search criteria" do get :index, {:search => {:updater_id => @user_2.id}} assert_response :success diff --git a/test/functional/notes_controller_test.rb b/test/functional/notes_controller_test.rb index d35b3ee50..1c96ed88e 100644 --- a/test/functional/notes_controller_test.rb +++ b/test/functional/notes_controller_test.rb @@ -8,27 +8,27 @@ class NotesControllerTest < ActionController::TestCase CurrentUser.ip_addr = "127.0.0.1" @post = FactoryGirl.create(:post) end - + teardown do CurrentUser.user = nil end - + context "index action" do setup do FactoryGirl.create(:note) end - + should "list all notes" do get :index assert_response :success end - + should "list all notes (with search)" do get :index, {:search => {:body_matches => "abc"}} assert_response :success end end - + context "create action" do should "create a note" do assert_difference("Note.count", 1) do @@ -36,38 +36,38 @@ class NotesControllerTest < ActionController::TestCase end end end - + context "update action" do setup do @note = FactoryGirl.create(:note) end - + should "update a note" do post :update, {:id => @note.id, :note => {:body => "xyz"}}, {:user_id => @user.id} @note.reload assert_equal("xyz", @note.body) end end - + context "destroy action" do setup do @note = FactoryGirl.create(:note) end - + should "destroy a note" do post :destroy, {:id => @note.id}, {:user_id => @user.id} @note.reload assert_equal(false, @note.is_active?) end end - + context "revert action" do setup do @note = FactoryGirl.create(:note, :body => "000") @note.update_attributes(:body => "111") @note.update_attributes(:body => "222") end - + should "revert to a previous version" do post :revert, {:id => @note.id, :version_id => @note.versions(true).first.id} @note.reload diff --git a/test/functional/pool_elements_controller_test.rb b/test/functional/pool_elements_controller_test.rb index 143c821ed..3a3b11675 100644 --- a/test/functional/pool_elements_controller_test.rb +++ b/test/functional/pool_elements_controller_test.rb @@ -10,18 +10,18 @@ class PoolElementsControllerTest < ActionController::TestCase @post = FactoryGirl.create(:post) @pool = FactoryGirl.create(:pool, :name => "abc") end - + teardown do CurrentUser.user = nil end - + context "create action" do should "add a post to a pool" do post :create, {:pool_id => @pool.id, :post_id => @post.id, :format => "json"}, {:user_id => @user.id} @pool.reload assert_equal([@post.id], @pool.post_id_array) end - + should "add a post to a pool once and only once" do @pool.add!(@post) post :create, {:pool_id => @pool.id, :post_id => @post.id, :format => "json"}, {:user_id => @user.id} @@ -29,18 +29,18 @@ class PoolElementsControllerTest < ActionController::TestCase assert_equal([@post.id], @pool.post_id_array) end end - + context "destroy action" do setup do @pool.add!(@post) end - + should "remove a post from a pool" do post :destroy, {:pool_id => @pool.id, :post_id => @post.id, :format => "json"}, {:user_id => @user.id} @pool.reload assert_equal([], @pool.post_id_array) end - + should "do nothing if the post is not a member of the pool" do @pool.remove!(@post) post :destroy, {:pool_id => @pool.id, :post_id => @post.id, :format => "json"}, {:user_id => @user.id} diff --git a/test/functional/pool_versions_controller_test.rb b/test/functional/pool_versions_controller_test.rb index 14b1f68ac..3e99ddbbe 100644 --- a/test/functional/pool_versions_controller_test.rb +++ b/test/functional/pool_versions_controller_test.rb @@ -7,34 +7,34 @@ class PoolVersionsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @pool = FactoryGirl.create(:pool) @user_2 = FactoryGirl.create(:user) @user_3 = FactoryGirl.create(:user) - + CurrentUser.scoped(@user_2, "1.2.3.4") do @pool.update_attributes(:post_ids => "1 2") end - + CurrentUser.scoped(@user_3, "5.6.7.8") do @pool.update_attributes(:post_ids => "1 2 3 4") end end - + should "list all versions" do get :index assert_response :success assert_not_nil(assigns(:pool_versions)) assert_equal(3, assigns(:pool_versions).size) end - + should "list all versions that match the search criteria" do get :index, {:search => {:updater_id => @user_2.id}} assert_response :success diff --git a/test/functional/pools_controller_test.rb b/test/functional/pools_controller_test.rb index c9ee3ab91..a487b5eb3 100644 --- a/test/functional/pools_controller_test.rb +++ b/test/functional/pools_controller_test.rb @@ -9,38 +9,38 @@ class PoolsControllerTest < ActionController::TestCase CurrentUser.ip_addr = "127.0.0.1" @post = FactoryGirl.create(:post) end - + teardown do CurrentUser.user = nil end - + context "index action" do setup do FactoryGirl.create(:pool, :name => "abc") end - + should "list all pools" do get :index assert_response :success end - + should "list all pools (with search)" do get :index, {:search => {:name_matches => "abc"}} assert_response :success end end - + context "show action" do setup do @pool = FactoryGirl.create(:pool) end - + should "render" do get :show, {:id => @pool.id} assert_response :success end end - + context "create action" do should "create a pool" do assert_difference("Pool.count", 1) do @@ -48,45 +48,45 @@ class PoolsControllerTest < ActionController::TestCase end end end - + context "update action" do setup do @pool = FactoryGirl.create(:pool) end - + should "update a pool" do post :update, {:id => @pool.id, :pool => {:name => "xyz"}}, {:user_id => @user.id} @pool.reload assert_equal("xyz", @pool.name) end end - + context "destroy action" do setup do @pool = FactoryGirl.create(:pool) end - + should "destroy a pool" do post :destroy, {:id => @pool.id}, {:user_id => @mod.id} @pool.reload assert_equal(true, @pool.is_deleted?) end end - + context "undelete action" do setup do @pool = FactoryGirl.create(:pool) @pool.is_deleted = true @pool.save end - + should "restore a pool" do post :undelete, {:id => @pool.id}, {:user_id => @mod.id} @pool.reload assert_equal(false, @pool.is_deleted?) end end - + context "revert action" do setup do @post_2 = FactoryGirl.create(:post) @@ -95,7 +95,7 @@ class PoolsControllerTest < ActionController::TestCase @pool.update_attributes(:post_ids => "#{@post.id} #{@post_2.id}") CurrentUser.ip_addr = "127.0.0.1" end - + should "revert to a previous version" do assert_equal(2, PoolVersion.count) version = @pool.versions(true).first diff --git a/test/functional/post_appeals_controller_test.rb b/test/functional/post_appeals_controller_test.rb index 52869291f..66b685d35 100644 --- a/test/functional/post_appeals_controller_test.rb +++ b/test/functional/post_appeals_controller_test.rb @@ -7,30 +7,30 @@ class PostAppealsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "new action" do should "render" do get :new, {}, {:user_id => @user.id} assert_response :success end end - + context "index action" do setup do @post = FactoryGirl.create(:post, :is_deleted => true) @post_appeal = FactoryGirl.create(:post_appeal, :post => @post) end - + should "render" do get :index, {}, {:user_id => @user.id} assert_response :success end - + context "with search parameters" do should "render" do get :index, {:search => {:post_id => @post_appeal.post_id}}, {:user_id => @user.id} @@ -38,12 +38,12 @@ class PostAppealsControllerTest < ActionController::TestCase end end end - + context "create action" do - setup do + setup do @post = FactoryGirl.create(:post, :is_deleted => true) end - + should "create a new appeal" do assert_difference("PostAppeal.count", 1) do post :create, {:format => "js", :post_appeal => {:post_id => @post.id, :reason => "xxx"}}, {:user_id => @user.id} diff --git a/test/functional/post_flags_controller_test.rb b/test/functional/post_flags_controller_test.rb index 4d665e6dc..cbf05d361 100644 --- a/test/functional/post_flags_controller_test.rb +++ b/test/functional/post_flags_controller_test.rb @@ -7,30 +7,30 @@ class PostFlagsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "new action" do should "render" do get :new, {}, {:user_id => @user.id} assert_response :success end end - + context "index action" do setup do @post = FactoryGirl.create(:post) @post_flag = FactoryGirl.create(:post_flag, :post => @post) end - + should "render" do get :index, {}, {:user_id => @user.id} assert_response :success end - + context "with search parameters" do should "render" do get :index, {:search => {:post_id => @post_flag.post_id}}, {:user_id => @user.id} @@ -38,12 +38,12 @@ class PostFlagsControllerTest < ActionController::TestCase end end end - + context "create action" do - setup do + setup do @post = FactoryGirl.create(:post) end - + should "create a new flag" do assert_difference("PostFlag.count", 1) do post :create, {:format => "js", :post_flag => {:post_id => @post.id, :reason => "xxx"}}, {:user_id => @user.id} diff --git a/test/functional/post_versions_controller_test.rb b/test/functional/post_versions_controller_test.rb index 4378e99d3..3405d16ae 100644 --- a/test/functional/post_versions_controller_test.rb +++ b/test/functional/post_versions_controller_test.rb @@ -7,25 +7,25 @@ class PostVersionsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @post = FactoryGirl.create(:post) @post.update_attributes(:tag_string => "1 2", :source => "xxx") @post.update_attributes(:tag_string => "2 3", :rating => "e") end - + should "list all versions" do get :index assert_response :success assert_not_nil(assigns(:post_versions)) end - + should "list all versions that match the search criteria" do get :index, {:search => {:post_id => @post.id}} assert_response :success diff --git a/test/functional/post_votes_controller_test.rb b/test/functional/post_votes_controller_test.rb index 1d596b31f..538e08f7e 100644 --- a/test/functional/post_votes_controller_test.rb +++ b/test/functional/post_votes_controller_test.rb @@ -8,12 +8,12 @@ class PostVotesControllerTest < ActionController::TestCase CurrentUser.ip_addr = "127.0.0.1" @post = FactoryGirl.create(:post) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "create action" do should "increment a post's score if the score is positive" do post :create, {:post_id => @post.id, :score => "up", :format => "js"}, {:user_id => @user.id} @@ -21,12 +21,12 @@ class PostVotesControllerTest < ActionController::TestCase @post.reload assert_equal(1, @post.score) end - + context "for a post that has already been voted on" do setup do @post.vote!("up") end - + should "fail silently on an error" do assert_nothing_raised do post :create, {:post_id => @post.id, :score => "up", :format => "js"}, {:user_id => @user.id} diff --git a/test/functional/posts_controller_test.rb b/test/functional/posts_controller_test.rb index 452c60888..aada53541 100644 --- a/test/functional/posts_controller_test.rb +++ b/test/functional/posts_controller_test.rb @@ -9,18 +9,18 @@ class PostsControllerTest < ActionController::TestCase @post = FactoryGirl.create(:post, :uploader_id => @user.id, :tag_string => "aaaa") MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do should "render" do get :index assert_response :success end - + context "with a search" do should "render" do get :index, {:tags => "aaaa"} @@ -28,29 +28,29 @@ class PostsControllerTest < ActionController::TestCase end end end - + context "show action" do should "render" do get :show, {:id => @post.id} assert_response :success end end - + context "update action" do should "work" do post :update, {:id => @post.id, :post => {:tag_string => "bbb"}}, {:user_id => @user.id} assert_redirected_to post_path(@post) - + @post.reload assert_equal("bbb", @post.tag_string) end end - + context "revert action" do setup do @post.update_attributes(:tag_string => "zzz") end - + should "work" do @version = @post.versions(true).first assert_equal("aaaa", @version.tags) diff --git a/test/functional/sessions_controller_test.rb b/test/functional/sessions_controller_test.rb index d32a7e586..aba793d05 100644 --- a/test/functional/sessions_controller_test.rb +++ b/test/functional/sessions_controller_test.rb @@ -5,14 +5,14 @@ class SessionsControllerTest < ActionController::TestCase setup do @user = FactoryGirl.create(:user) end - + context "new action" do should "render" do get :new assert_response :success end end - + context "create action" do should "create a new session" do post :create, {:name => @user.name, :password => "password"} @@ -20,18 +20,18 @@ class SessionsControllerTest < ActionController::TestCase assert_equal(@user.id, session[:user_id]) end end - + context "destroy action" do setup do CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "clear the session" do post :destroy, {}, {:user_id => @user.id} assert_redirected_to posts_path diff --git a/test/functional/tag_alias_corrections_controller_test.rb b/test/functional/tag_alias_corrections_controller_test.rb index 6a3163f54..629dc4d91 100644 --- a/test/functional/tag_alias_corrections_controller_test.rb +++ b/test/functional/tag_alias_corrections_controller_test.rb @@ -10,19 +10,19 @@ class TagAliasCorrectionsControllerTest < ActionController::TestCase Delayed::Worker.delay_jobs = false @tag_alias = FactoryGirl.create(:tag_alias, :antecedent_name => "aaa", :consequent_name => "bbb") end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "show action" do should "render" do get :show, {:tag_alias_id => @tag_alias.id}, {:user => @admin.id} assert_response :success end end - + context "create action" do should "render" do post :create, {:tag_alias_id => @tag_alias.id, :commit => "Fix"}, {:user => @admin.id} diff --git a/test/functional/tag_alias_requests_controller_test.rb b/test/functional/tag_alias_requests_controller_test.rb index 3272ed316..ba47c9fee 100644 --- a/test/functional/tag_alias_requests_controller_test.rb +++ b/test/functional/tag_alias_requests_controller_test.rb @@ -9,19 +9,19 @@ class TagAliasRequestsControllerTest < ActionController::TestCase MEMCACHE.flush_all Delayed::Worker.delay_jobs = false end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "new action" do should "render" do get :new, {}, {:user => @user.id} assert_response :success end end - + context "create action" do should "render" do assert_difference("ForumTopic.count", 1) do diff --git a/test/functional/tag_aliases_controller_test.rb b/test/functional/tag_aliases_controller_test.rb index 9a08faf22..828d44398 100644 --- a/test/functional/tag_aliases_controller_test.rb +++ b/test/functional/tag_aliases_controller_test.rb @@ -9,28 +9,28 @@ class TagAliasesControllerTest < ActionController::TestCase MEMCACHE.flush_all Delayed::Worker.delay_jobs = false end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @tag_alias = FactoryGirl.create(:tag_alias, :antecedent_name => "aaa", :consequent_name => "bbb") end - + should "list all tag aliass" do get :index assert_response :success end - + should "list all tag_aliass (with search)" do get :index, {:search => {:antecedent_name => "aaa"}} assert_response :success end end - + context "create action" do should "create a tag alias" do assert_difference("TagAlias.count", 1) do @@ -43,7 +43,7 @@ class TagAliasesControllerTest < ActionController::TestCase setup do @tag_alias = FactoryGirl.create(:tag_alias) end - + should "destroy a tag_alias" do assert_difference("TagAlias.count", -1) do post :destroy, {:id => @tag_alias.id}, {:user_id => @user.id} diff --git a/test/functional/tag_implication_requests_controller.rb b/test/functional/tag_implication_requests_controller.rb index 0cbf03247..93711b062 100644 --- a/test/functional/tag_implication_requests_controller.rb +++ b/test/functional/tag_implication_requests_controller.rb @@ -9,19 +9,19 @@ class TagImplicationRequestsControllerTest < ActionController::TestCase MEMCACHE.flush_all Delayed::Worker.delay_jobs = false end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "new action" do should "render" do get :new, {}, {:user => @user.id} assert_response :success end end - + context "create action" do should "render" do assert_difference("ForumTopic.count", 1) do diff --git a/test/functional/tag_implications_controller_test.rb b/test/functional/tag_implications_controller_test.rb index fb7589d9f..e8fa8dc7e 100644 --- a/test/functional/tag_implications_controller_test.rb +++ b/test/functional/tag_implications_controller_test.rb @@ -9,22 +9,22 @@ class TagImplicationsControllerTest < ActionController::TestCase MEMCACHE.flush_all Delayed::Worker.delay_jobs = false end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @tag_implication = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb", :creator => @user) end - + should "list all tag implications" do get :index assert_response :success end - + should "list all tag_implications (with search)" do get :index, {:search => {:antecedent_name => "aaa"}} assert_response :success @@ -38,12 +38,12 @@ class TagImplicationsControllerTest < ActionController::TestCase end end end - + context "destroy action" do setup do @tag_implication = FactoryGirl.create(:tag_implication, :creator => @user) end - + should "destroy a tag_implication" do assert_difference("TagImplication.count", -1) do post :destroy, {:id => @tag_implication.id}, {:user_id => @user.id} diff --git a/test/functional/tag_subscriptions_controller_test.rb b/test/functional/tag_subscriptions_controller_test.rb index a342e1ac5..05a8c24e3 100644 --- a/test/functional/tag_subscriptions_controller_test.rb +++ b/test/functional/tag_subscriptions_controller_test.rb @@ -7,17 +7,17 @@ class TagSubscriptionsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @tag_subscription = FactoryGirl.create(:tag_subscription, :name => "aaa") end - + should "list all visible tag subscriptions" do get :index assert_response :success @@ -28,31 +28,31 @@ class TagSubscriptionsControllerTest < ActionController::TestCase setup do @tag_subscription = FactoryGirl.create(:tag_subscription, :name => "aaa") end - + should "list all visible tag subscriptions" do get :posts, {:id => @tag_subscription.creator_id} assert_response :success end end - + context "edit action" do setup do @tag_subscription = FactoryGirl.create(:tag_subscription) end - + should "render" do get :edit, {:id => @tag_subscription.id}, {:user_id => @user.id} assert_response :success end end - + context "new action" do should "render" do get :new, {}, {:user_id => @user.id} assert_response :success end end - + context "create action" do should "create a new tag subscription" do assert_difference("TagSubscription.count", 1) do @@ -60,12 +60,12 @@ class TagSubscriptionsControllerTest < ActionController::TestCase end end end - + context "destroy action" do setup do @tag_subscription = FactoryGirl.create(:tag_subscription) end - + should "destroy the posts" do assert_difference("TagSubscription.count", -1) do post :destroy, {:id => @tag_subscription.id}, {:user_id => @user.id} diff --git a/test/functional/tags_controller_test.rb b/test/functional/tags_controller_test.rb index 15d1187b8..7cda4d76b 100644 --- a/test/functional/tags_controller_test.rb +++ b/test/functional/tags_controller_test.rb @@ -7,33 +7,33 @@ class TagsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "edit action" do setup do @tag = FactoryGirl.create(:tag, :name => "aaa") end - + should "render" do get :edit, {:id => @tag.id}, {:user_id => @user.id} assert_response :success end end - + context "index action" do setup do @tag = FactoryGirl.create(:tag, :name => "aaa") end - + should "render" do get :index assert_response :success end - + context "with search parameters" do should "render" do get :index, {:search => {:name_matches => "aaa"}} @@ -41,23 +41,23 @@ class TagsControllerTest < ActionController::TestCase end end end - + context "show action" do - setup do + setup do @tag = FactoryGirl.create(:tag) end - + should "render" do get :show, {:id => @tag.id} assert_response :success end end - + context "update action" do setup do @tag = FactoryGirl.create(:tag) end - + should "update the tag" do post :update, {:id => @tag.id, :tag => {:category => "1"}}, {:user_id => @user.id} assert_redirected_to tag_path(@tag) diff --git a/test/functional/uploads_controller_test.rb b/test/functional/uploads_controller_test.rb index 3b32840cc..4472ff6fe 100644 --- a/test/functional/uploads_controller_test.rb +++ b/test/functional/uploads_controller_test.rb @@ -7,23 +7,23 @@ class UploadsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "new action" do should "render" do get :new, {}, {:user_id => @user.id} assert_response :success end - + context "for a post that has already been uploaded" do setup do @post = FactoryGirl.create(:post, :source => "aaa") end - + should "initialize the post" do get :new, {:url => "aaa"}, {:user_id => @user.id} assert_response :success @@ -31,17 +31,17 @@ class UploadsControllerTest < ActionController::TestCase end end end - + context "index action" do setup do @upload = FactoryGirl.create(:source_upload) end - + should "render" do get :index, {}, {:user_id => @user.id} assert_response :success end - + context "with search parameters" do should "render" do get :index, {:search => {:source => @upload.source}}, {:user_id => @user.id} @@ -49,18 +49,18 @@ class UploadsControllerTest < ActionController::TestCase end end end - + context "show action" do setup do @upload = FactoryGirl.create(:jpg_upload) end - + should "render" do get :show, {:id => @upload.id}, {:user_id => @user.id} assert_response :success end end - + context "create action" do should "create a new upload" do assert_difference("Upload.count", 1) do @@ -70,12 +70,12 @@ class UploadsControllerTest < ActionController::TestCase end end end - + context "update action" do setup do @upload = FactoryGirl.create(:jpg_upload) end - + should "process an unapproval" do post :update, {:id => @upload.id}, {:user_id => @user.id} @upload.reload diff --git a/test/functional/user_feedbacks_controller_test.rb b/test/functional/user_feedbacks_controller_test.rb index aff6d7028..9e88ae3a6 100644 --- a/test/functional/user_feedbacks_controller_test.rb +++ b/test/functional/user_feedbacks_controller_test.rb @@ -8,40 +8,40 @@ class UserFeedbacksControllerTest < ActionController::TestCase CurrentUser.user = @critic CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "new action" do should "render" do get :new, {}, {:user_id => @critic.id} assert_response :success end end - + context "edit action" do setup do @user_feedback = FactoryGirl.create(:user_feedback) end - + should "render" do get :edit, {:id => @user_feedback.id}, {:user_id => @critic.id} assert_response :success end end - + context "index action" do setup do @user_feedback = FactoryGirl.create(:user_feedback) end - + should "render" do get :index, {}, {:user_id => @user.id} assert_response :success end - + context "with search parameters" do should "render" do get :index, {:search => {:user_id => @user.id}}, {:user_id => @critic.id} @@ -49,7 +49,7 @@ class UserFeedbacksControllerTest < ActionController::TestCase end end end - + context "create action" do should "create a new feedback" do assert_difference("UserFeedback.count", 1) do @@ -59,12 +59,12 @@ class UserFeedbacksControllerTest < ActionController::TestCase end end end - + context "destroy action" do setup do @user_feedback = FactoryGirl.create(:user_feedback) end - + should "delete a feedback" do assert_difference "UserFeedback.count", -1 do post :destroy, {:id => @user_feedback.id}, {:user_id => @critic.id} diff --git a/test/functional/users_controller_test.rb b/test/functional/users_controller_test.rb index 6c4e49fd8..485214d68 100644 --- a/test/functional/users_controller_test.rb +++ b/test/functional/users_controller_test.rb @@ -7,38 +7,38 @@ class UsersControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil end - + context "index action" do setup do FactoryGirl.create(:user, :name => "abc") end - + should "list all users" do get :index assert_response :success end - + should "list all users (with search)" do get :index, {:search => {:name_matches => "abc"}} assert_response :success end end - + context "show action" do setup do @user = FactoryGirl.create(:user) end - + should "render" do get :show, {:id => @user.id} assert_response :success end end - + context "create action" do should "create a user" do assert_difference("User.count", 1) do @@ -48,23 +48,23 @@ class UsersControllerTest < ActionController::TestCase end end end - + context "edit action" do setup do @user = FactoryGirl.create(:user) end - + should "render" do get :edit, {:id => @user.id}, {:user_id => @user.id} assert_response :success end end - + context "update action" do setup do @user = FactoryGirl.create(:user) end - + should "update a user" do post :update, {:id => @user.id, :user => {:name => "xyz"}}, {:user_id => @user.id} @user.reload diff --git a/test/functional/wiki_page_versions_controller_test.rb b/test/functional/wiki_page_versions_controller_test.rb index 84ba92600..e8d55ef3e 100644 --- a/test/functional/wiki_page_versions_controller_test.rb +++ b/test/functional/wiki_page_versions_controller_test.rb @@ -7,25 +7,25 @@ class WikiPageVersionsControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "index action" do setup do @wiki_page = FactoryGirl.create(:wiki_page) @wiki_page.update_attributes(:body => "1 2") @wiki_page.update_attributes(:body => "2 3") end - + should "list all versions" do get :index assert_response :success assert_not_nil(assigns(:wiki_page_versions)) end - + should "list all versions that match the search criteria" do get :index, {:search => {:wiki_page_id => @wiki_page.id}} assert_response :success diff --git a/test/functional/wiki_pages_controller_test.rb b/test/functional/wiki_pages_controller_test.rb index a14127666..7450e414d 100644 --- a/test/functional/wiki_pages_controller_test.rb +++ b/test/functional/wiki_pages_controller_test.rb @@ -8,45 +8,45 @@ class WikiPagesControllerTest < ActionController::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil end - + context "index action" do setup do @wiki_page_abc = FactoryGirl.create(:wiki_page, :title => "abc") @wiki_page_def = FactoryGirl.create(:wiki_page, :title => "def") end - + should "list all wiki_pages" do get :index assert_response :success end - + should "list all wiki_pages (with search)" do get :index, {:search => {:title => "abc"}} assert_redirected_to(wiki_page_path(@wiki_page_abc)) end end - + context "show action" do setup do @wiki_page = FactoryGirl.create(:wiki_page) end - + should "render" do get :show, {:id => @wiki_page.id} assert_response :success end - + should "render for a negated tag" do @wiki_page.update_attribute(:title, "-aaa") get :show, {:id => @wiki_page.id} assert_response :success end end - + context "create action" do should "create a wiki_page" do assert_difference("WikiPage.count", 1) do @@ -54,38 +54,38 @@ class WikiPagesControllerTest < ActionController::TestCase end end end - + context "update action" do setup do @wiki_page = FactoryGirl.create(:wiki_page) end - + should "update a wiki_page" do post :update, {:id => @wiki_page.id, :wiki_page => {:body => "xyz"}}, {:user_id => @user.id} @wiki_page.reload assert_equal("xyz", @wiki_page.body) end end - + context "destroy action" do setup do @wiki_page = FactoryGirl.create(:wiki_page) end - + should "destroy a wiki_page" do assert_difference("WikiPage.count", -1) do post :destroy, {:id => @wiki_page.id}, {:user_id => @mod.id} end end end - + context "revert action" do setup do @wiki_page = FactoryGirl.create(:wiki_page, :body => "1") @wiki_page.update_attributes(:body => "1 2") @wiki_page.update_attributes(:body => "1 2 3") end - + should "revert to a previous version" do version = @wiki_page.versions(true).first assert_equal("1", version.body) diff --git a/test/test_helper.rb b/test/test_helper.rb index 647c4ba6d..d1481479d 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -18,7 +18,7 @@ module UploadTestMethods define_method(:original_filename) {filename} define_method(:content_type) {content_type} end - + tempfile end @@ -33,12 +33,12 @@ end class ActionController::TestCase include UploadTestMethods - + def assert_authentication_passes(action, http_method, role, params, session) __send__(http_method, action, params, session.merge(:user_id => @users[role].id)) assert_response :success end - + def assert_authentication_fails(action, http_method, role) __send__(http_method, action, params, session.merge(:user_id => @users[role].id)) assert_redirected_to(new_sessions_path) diff --git a/test/unit/advertisement_test.rb b/test/unit/advertisement_test.rb index 5f23f9d53..f1e320fc3 100644 --- a/test/unit/advertisement_test.rb +++ b/test/unit/advertisement_test.rb @@ -6,11 +6,11 @@ class AdvertisementTest < ActiveSupport::TestCase Danbooru.config.stubs(:advertisement_path).returns("/tmp") @ad = FactoryGirl.create(:advertisement, :file => upload_jpeg("#{Rails.root}/test/files/test.jpg")) end - + teardown do FileUtils.rm_f(Dir.glob("#{Rails.root}/public/images/advertisements/*.jpg")) end - + should "create new hit records" do assert_difference("AdvertisementHit.count") do @ad.hit!("0.0.0.0") @@ -20,7 +20,7 @@ class AdvertisementTest < ActiveSupport::TestCase assert_equal(1, @ad.hit_sum(1.day.ago, 1.day.from_now)) assert_equal(0, @ad.hit_sum(2.days.ago, 1.day.ago)) end - + should "know its preview height and preview width" do assert_equal(100, @ad.preview_width) assert_equal(67, @ad.preview_height) diff --git a/test/unit/alias_and_implication_importer_test.rb b/test/unit/alias_and_implication_importer_test.rb index ceff062bf..e4c7032fe 100644 --- a/test/unit/alias_and_implication_importer_test.rb +++ b/test/unit/alias_and_implication_importer_test.rb @@ -7,44 +7,44 @@ class AliasAndImplicationImporterTest < ActiveSupport::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "given a valid list" do setup do @list = "create alias abc -> def\ncreate implication aaa -> bbb\n" @importer = AliasAndImplicationImporter.new(@list, nil) end - + should "process it" do assert_difference("Delayed::Job.count", 4) do @importer.process! end end end - + context "given a list with an invalid command" do setup do @list = "zzzz abc -> def\n" @importer = AliasAndImplicationImporter.new(@list, nil) end - + should "throw an exception" do assert_raises(RuntimeError) do @importer.process! end end end - + context "given a list with a logic error" do setup do @list = "remove alias zzz -> yyy\n" @importer = AliasAndImplicationImporter.new(@list, nil) end - + should "throw an exception" do assert_raises(RuntimeError) do @importer.process! diff --git a/test/unit/artist_test.rb b/test/unit/artist_test.rb index c33e5e052..d5b8907cb 100644 --- a/test/unit/artist_test.rb +++ b/test/unit/artist_test.rb @@ -13,22 +13,22 @@ class ArtistTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "with a matching tag alias" do setup do @tag_alias = FactoryGirl.create(:tag_alias, :antecedent_name => "aaa", :consequent_name => "bbb") @artist = FactoryGirl.create(:artist, :name => "aaa") end - + should "know it has an alias" do assert_equal(true, @artist.has_tag_alias?) end - + should "know its alias" do assert_equal("bbb", @artist.tag_alias_name) end end - + context "that has been banned" do setup do @post = FactoryGirl.create(:post, :tag_string => "aaa") @@ -36,16 +36,16 @@ class ArtistTest < ActiveSupport::TestCase @artist.ban! @post.reload end - + should "delete the post" do assert(@post.is_deleted?) end - + should "create a new tag implication" do assert_equal(1, TagImplication.where(:antecedent_name => "aaa", :consequent_name => "banned_artist").count) end end - + should "create a new wiki page to store any note information" do artist = nil assert_difference("WikiPage.count") do @@ -55,7 +55,7 @@ class ArtistTest < ActiveSupport::TestCase assert_equal("testing", artist.wiki_page.body) assert_equal(artist.name, artist.wiki_page.title) end - + should "update the wiki page when notes are assigned" do artist = FactoryGirl.create(:artist, :name => "aaa", :notes => "testing") artist.update_attribute(:notes, "kokoko") @@ -63,12 +63,12 @@ class ArtistTest < ActiveSupport::TestCase assert_equal("kokoko", artist.notes) assert_equal("kokoko", artist.wiki_page.body) end - + should "normalize its name" do artist = FactoryGirl.create(:artist, :name => " AAA BBB ") assert_equal("aaa_bbb", artist.name) end - + should "resolve ambiguous urls" do bobross = FactoryGirl.create(:artist, :name => "bob_ross", :url_string => "http://artists.com/bobross/image.jpg") bob = FactoryGirl.create(:artist, :name => "bob", :url_string => "http://artists.com/bob/image.jpg") @@ -76,13 +76,13 @@ class ArtistTest < ActiveSupport::TestCase assert_equal(1, matches.size) assert_equal("bob", matches.first.name) end - + should "parse urls" do artist = FactoryGirl.create(:artist, :name => "rembrandt", :url_string => "http://rembrandt.com/test.jpg http://aaa.com") artist.reload assert_equal(["http://aaa.com", "http://rembrandt.com/test.jpg"], artist.urls.map(&:to_s).sort) end - + should "make sure old urls are deleted" do artist = FactoryGirl.create(:artist, :name => "rembrandt", :url_string => "http://rembrandt.com/test.jpg") artist.url_string = "http://not.rembrandt.com/test.jpg" @@ -97,32 +97,32 @@ class ArtistTest < ActiveSupport::TestCase a3 = FactoryGirl.create(:artist, :name => "minko", :url_string => "https://minko.com/x/test.jpg") assert_equal(["rembrandt"], Artist.find_all_by_url("http://rembrandt.com/x/test.jpg").map(&:name)) - assert_equal(["rembrandt"], Artist.find_all_by_url("http://rembrandt.com/x/another.jpg").map(&:name)) + assert_equal(["rembrandt"], Artist.find_all_by_url("http://rembrandt.com/x/another.jpg").map(&:name)) assert_equal([], Artist.find_all_by_url("http://nonexistent.com/test.jpg").map(&:name)) assert_equal(["minko"], Artist.find_all_by_url("https://minko.com/x/test.jpg").map(&:name)) assert_equal(["minko"], Artist.find_all_by_url("http://minko.com/x/test.jpg").map(&:name)) end - + should "not allow duplicates" do FactoryGirl.create(:artist, :name => "warhol", :url_string => "http://warhol.com/x/a/image.jpg\nhttp://warhol.com/x/b/image.jpg") assert_equal(["warhol"], Artist.find_all_by_url("http://warhol.com/x/test.jpg").map(&:name)) end - + should "hide deleted artists" do FactoryGirl.create(:artist, :name => "warhol", :url_string => "http://warhol.com/a/image.jpg", :is_active => false) assert_equal([], Artist.find_all_by_url("http://warhol.com/a/image.jpg").map(&:name)) end - + should "normalize its other names" do artist = FactoryGirl.create(:artist, :name => "a1", :other_names_comma => "aaa, bbb, ccc ddd") assert_equal("aaa, bbb, ccc_ddd", artist.other_names_comma) end - + should "search on its name should return results" do artist = FactoryGirl.create(:artist, :name => "artist") assert_not_nil(Artist.search(:name => "artist").first) end - + should "search on other names should return matches" do artist = FactoryGirl.create(:artist, :name => "artist", :other_names_comma => "aaa, ccc ddd") assert_nil(Artist.other_names_match("artist").first) @@ -131,7 +131,7 @@ class ArtistTest < ActiveSupport::TestCase assert_not_nil(Artist.search(:name => "other:aaa").first) assert_not_nil(Artist.search(:name => "aaa").first) end - + should "search on group name and return matches" do cat_or_fish = FactoryGirl.create(:artist, :name => "cat_or_fish") yuu = FactoryGirl.create(:artist, :name => "yuu", :group_name => "cat_or_fish") @@ -139,19 +139,19 @@ class ArtistTest < ActiveSupport::TestCase assert_equal("yuu", cat_or_fish.member_names) assert_not_nil(Artist.search(:name => "group:cat_or_fish").first) end - + should "have an associated wiki" do user = FactoryGirl.create(:user) CurrentUser.user = user artist = FactoryGirl.create(:artist, :name => "max", :wiki_page_attributes => {:title => "xxx", :body => "this is max"}) assert_not_nil(artist.wiki_page) assert_equal("this is max", artist.wiki_page.body) - + artist.update_attributes({:wiki_page_attributes => {:id => artist.wiki_page.id, :body => "this is hoge mark ii"}}) assert_equal("this is hoge mark ii", artist.wiki_page(true).body) CurrentUser.user = nil end - + should "revert to prior versions" do user = FactoryGirl.create(:user) reverter = FactoryGirl.create(:user) @@ -159,12 +159,12 @@ class ArtistTest < ActiveSupport::TestCase assert_difference("ArtistVersion.count") do artist = FactoryGirl.create(:artist, :other_names => "yyy") end - + assert_difference("ArtistVersion.count") do artist.other_names = "xxx" artist.save end - + first_version = ArtistVersion.first assert_equal("yyy", first_version.other_names) artist.revert_to!(first_version) diff --git a/test/unit/artist_url_test.rb b/test/unit/artist_url_test.rb index eaf4da618..5537ea906 100644 --- a/test/unit/artist_url_test.rb +++ b/test/unit/artist_url_test.rb @@ -7,7 +7,7 @@ class ArtistUrlTest < ActiveSupport::TestCase CurrentUser.user = FactoryGirl.create(:user) CurrentUser.ip_addr = "127.0.0.1" end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil @@ -22,7 +22,7 @@ class ArtistUrlTest < ActiveSupport::TestCase assert_equal("http://monet.com/", url.url) assert_equal("http://monet.com/", url.normalized_url) end - + should "normalise https" do url = FactoryGirl.create(:artist_url, :url => "https://google.com") assert_equal("https://google.com", url.url) @@ -38,7 +38,7 @@ class ArtistUrlTest < ActiveSupport::TestCase assert_equal("http://blog-imgs-55.fc2.com/monet", url.url) assert_equal("http://blog.fc2.com/monet/", url.normalized_url) end - + should "normalize pixiv urls" do url = FactoryGirl.create(:artist_url, :url => "http://img55.pixiv.net/monet") assert_equal("http://img55.pixiv.net/monet", url.url) diff --git a/test/unit/ban_test.rb b/test/unit/ban_test.rb index 432ed6155..cc86567a4 100644 --- a/test/unit/ban_test.rb +++ b/test/unit/ban_test.rb @@ -8,20 +8,20 @@ class BanTest < ActiveSupport::TestCase CurrentUser.user = @banner CurrentUser.ip_addr = "127.0.0.1" end - + teardown do @banner = nil CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "not be valid against another admin" do user = FactoryGirl.create(:admin_user) ban = FactoryGirl.build(:ban, :user => user, :banner => @banner) ban.save assert(ban.errors.any?) end - + should "be valid against anyone who is not an admin" do user = FactoryGirl.create(:moderator_user) ban = FactoryGirl.create(:ban, :user => user, :banner => @banner) @@ -44,20 +44,20 @@ class BanTest < ActiveSupport::TestCase assert(ban.errors.empty?) end end - + context "created by a moderator" do setup do @banner = FactoryGirl.create(:moderator_user) CurrentUser.user = @banner CurrentUser.ip_addr = "127.0.0.1" end - + teardown do @banner = nil CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "not be valid against an admin or moderator" do user = FactoryGirl.create(:admin_user) ban = FactoryGirl.build(:ban, :user => user, :banner => @banner) @@ -69,7 +69,7 @@ class BanTest < ActiveSupport::TestCase ban.save assert(ban.errors.any?) end - + should "be valid against anyone who is not an admin or a moderator" do user = FactoryGirl.create(:janitor_user) ban = FactoryGirl.create(:ban, :user => user, :banner => @banner) @@ -88,20 +88,20 @@ class BanTest < ActiveSupport::TestCase assert(ban.errors.empty?) end end - + context "created by a janitor" do setup do - @banner = FactoryGirl.create(:janitor_user) + @banner = FactoryGirl.create(:janitor_user) CurrentUser.user = @banner CurrentUser.ip_addr = "127.0.0.1" end - + teardown do @banner = nil CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "always be invalid" do user = FactoryGirl.create(:admin_user) ban = FactoryGirl.build(:ban, :user => user, :banner => @banner) @@ -143,7 +143,7 @@ class BanTest < ActiveSupport::TestCase CurrentUser.user = nil assert_not_nil(ban.expires_at) end - + should "update the user's feedback" do user = FactoryGirl.create(:user) admin = FactoryGirl.create(:admin_user) @@ -164,31 +164,31 @@ class BanTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" @user = FactoryGirl.create(:user) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "when only expired bans exist" do setup do @ban = FactoryGirl.create(:ban, :user => @user, :banner => @admin, :duration => -1) end - + should "not return expired bans" do assert(!Ban.is_banned?(@user)) end end - + context "when active bans still exist" do setup do @ban = FactoryGirl.create(:ban, :user => @user, :banner => @admin, :duration => 1) end - + should "return active bans" do assert(Ban.is_banned?(@user)) end end - end + end end end diff --git a/test/unit/comment_test.rb b/test/unit/comment_test.rb index 0a35d3cb7..1f8de75a2 100644 --- a/test/unit/comment_test.rb +++ b/test/unit/comment_test.rb @@ -8,31 +8,31 @@ class CommentTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "created by a limited user" do setup do Danbooru.config.stubs(:member_comment_limit).returns(5) Danbooru.config.stubs(:member_comment_time_threshold).returns(1.week.ago) end - + should "fail creation" do comment = FactoryGirl.build(:comment) comment.save assert_equal(["Creator can not post comments within 1 week of sign up, and can only post 5 comments per hour after that"], comment.errors.full_messages) end end - + context "created by an unlimited user" do setup do Danbooru.config.stubs(:member_comment_limit).returns(100) Danbooru.config.stubs(:member_comment_time_threshold).returns(1.week.from_now) end - + context "that is then deleted" do setup do @post = FactoryGirl.create(:post) @@ -40,7 +40,7 @@ class CommentTest < ActiveSupport::TestCase @comment.destroy @post.reload end - + should "nullify the last_commented_at field" do assert_nil(@post.last_commented_at) end diff --git a/test/unit/current_user_test.rb b/test/unit/current_user_test.rb index ac586df80..f207e3c28 100644 --- a/test/unit/current_user_test.rb +++ b/test/unit/current_user_test.rb @@ -5,37 +5,37 @@ class ArtistTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "The current user" do should "be set only within the scope of the block" do user = FactoryGirl.create(:user) - + assert_nil(CurrentUser.user) assert_nil(CurrentUser.ip_addr) - + CurrentUser.user = user CurrentUser.ip_addr = "1.2.3.4" - + assert_not_nil(CurrentUser.user) assert_equal(user.id, CurrentUser.user.id) assert_equal("1.2.3.4", CurrentUser.ip_addr) end end - + context "A scoped current user" do should "reset the current user after the block has exited" do user1 = FactoryGirl.create(:user) - user2 = FactoryGirl.create(:user) + user2 = FactoryGirl.create(:user) CurrentUser.user = user1 CurrentUser.scoped(user2, nil) do assert_equal(user2.id, CurrentUser.user.id) end assert_equal(user1.id, CurrentUser.user.id) end - + should "reset the current user even if an exception is thrown" do user1 = FactoryGirl.create(:user) - user2 = FactoryGirl.create(:user) + user2 = FactoryGirl.create(:user) CurrentUser.user = user1 assert_raises(RuntimeError) do CurrentUser.scoped(user2, nil) do diff --git a/test/unit/dmail_test.rb b/test/unit/dmail_test.rb index d5066a66a..6e72a168d 100644 --- a/test/unit/dmail_test.rb +++ b/test/unit/dmail_test.rb @@ -11,16 +11,16 @@ class DmailTest < ActiveSupport::TestCase ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] end - + teardown do CurrentUser.user = nil end - + context "from a banned user" do setup do @user.update_attribute(:is_banned, true) end - + should "not validate" do dmail = FactoryGirl.build(:dmail, :title => "xxx", :owner => @user) dmail.save @@ -28,7 +28,7 @@ class DmailTest < ActiveSupport::TestCase assert_equal(["Sender is banned and cannot send messages"], dmail.errors.full_messages) end end - + context "search" do should "return results based on title contents" do dmail = FactoryGirl.create(:dmail, :title => "xxx", :owner => @user) @@ -37,7 +37,7 @@ class DmailTest < ActiveSupport::TestCase matches = Dmail.search_message("aaa") assert(matches.empty?) end - + should "return results based on body contents" do dmail = FactoryGirl.create(:dmail, :body => "xxx", :owner => @user) matches = Dmail.search_message("xxx") @@ -46,14 +46,14 @@ class DmailTest < ActiveSupport::TestCase assert(matches.empty?) end end - + should "should parse user names" do dmail = FactoryGirl.build(:dmail, :owner => @user) dmail.to_id = nil dmail.to_name = @user.name assert(dmail.to_id == @user.id) end - + should "construct a response" do dmail = FactoryGirl.create(:dmail, :owner => @user) response = dmail.build_response @@ -61,7 +61,7 @@ class DmailTest < ActiveSupport::TestCase assert_equal(dmail.from_id, response.to_id) assert_equal(dmail.to_id, response.from_id) end - + should "create a copy for each user" do @new_user = FactoryGirl.create(:user) assert_difference("Dmail.count", 2) do @@ -82,14 +82,14 @@ class DmailTest < ActiveSupport::TestCase Dmail.create_split(:to_id => user.id, :title => "foo", :body => "foo") end end - + should "be marked as read after the user reads it" do dmail = FactoryGirl.create(:dmail, :owner => @user) assert(!dmail.is_read?) dmail.mark_as_read! assert(dmail.is_read?) end - + should "notify the recipient he has mail" do dmail = FactoryGirl.create(:dmail, :owner => @user) assert(dmail.to(true).has_mail?) diff --git a/test/unit/downloads/file_test.rb b/test/unit/downloads/file_test.rb index 24fd99a29..740f1ee92 100644 --- a/test/unit/downloads/file_test.rb +++ b/test/unit/downloads/file_test.rb @@ -8,32 +8,32 @@ module Downloads @tempfile = Tempfile.new("danbooru-test") @download = Downloads::File.new(@source, @tempfile.path) end - + teardown do @tempfile.close end - + should "stream a file from an HTTP source" do @download.http_get_streaming do |resp| assert_equal("200", resp.code) assert(resp["Content-Length"].to_i > 0, "File should be larger than 0 bytes") end end - + should "throw an exception when the file is larger than the maximum" do assert_raise(Downloads::File::Error) do @download.http_get_streaming(:max_size => 1) do |resp| end end end - + should "store the file in the tempfile path" do @download.download! assert_equal(@source, @download.source) assert(::File.exists?(@tempfile.path), "temp file should exist") assert(::File.size(@tempfile.path) > 0, "should have data") end - + should "initialize the content type" do @download.download! assert_match(/image\/gif/, @download.content_type) diff --git a/test/unit/downloads/nico_seiga_test.rb b/test/unit/downloads/nico_seiga_test.rb index 296318eda..df25b6b7f 100644 --- a/test/unit/downloads/nico_seiga_test.rb +++ b/test/unit/downloads/nico_seiga_test.rb @@ -8,7 +8,7 @@ module Downloads # @tempfile = Tempfile.new("danbooru-test") # @download = Downloads::File.new(@source, @tempfile.path) end - + should "work" do # @download.download! # assert_equal(201248, ::File.size(@tempfile.path)) diff --git a/test/unit/downloads/pixa_test.rb b/test/unit/downloads/pixa_test.rb index 680448fba..9de136009 100644 --- a/test/unit/downloads/pixa_test.rb +++ b/test/unit/downloads/pixa_test.rb @@ -1,5 +1,5 @@ # require 'test_helper' -# +# # module Downloads # class PixaTest < ActiveSupport::TestCase # context "a download for a pixa image" do @@ -8,7 +8,7 @@ # @tempfile = Tempfile.new("danbooru-test") # @download = Downloads::File.new(@source, @tempfile.path) # end -# +# # should "work" do # @download.download! # assert_equal(104627, ::File.size(@tempfile.path)) diff --git a/test/unit/downloads/pixiv_test.rb b/test/unit/downloads/pixiv_test.rb index 5b5f17784..9d5ffdeb1 100644 --- a/test/unit/downloads/pixiv_test.rb +++ b/test/unit/downloads/pixiv_test.rb @@ -9,12 +9,12 @@ module Downloads @download = Downloads::File.new(@source, @tempfile.path) @download.download! end - + should "instead download the big version" do assert_equal("http://img65.pixiv.net/img/kiyoringo/21755794_big_p2.png", @download.source) end end - + context "a download for a html page" do setup do @source = "http://www.pixiv.net/member_illust.php?mode=big&illust_id=23828655" @@ -23,12 +23,12 @@ module Downloads @download = Downloads::File.new(@source, @tempfile.path) @download.download! end - + should "work" do assert_equal(185778, ::File.size(@tempfile.path)) end end - + context "a download for a small image" do setup do @source = "http://img02.pixiv.net/img/wanwandoh/4348318_m.jpg" @@ -36,11 +36,11 @@ module Downloads @download = Downloads::File.new(@source, @tempfile.path) @download.download! end - + should "instead download the original version" do assert_equal("http://img02.pixiv.net/img/wanwandoh/4348318.jpg", @download.source) end - + should "work" do assert_equal(185778, ::File.size(@tempfile.path)) end diff --git a/test/unit/downloads/tinami_test.rb b/test/unit/downloads/tinami_test.rb index 66eae0229..78981c0c5 100644 --- a/test/unit/downloads/tinami_test.rb +++ b/test/unit/downloads/tinami_test.rb @@ -1,5 +1,5 @@ # require 'test_helper' -# +# # module Downloads # class TinamiTest < ActiveSupport::TestCase # context "a download for a pixa image" do @@ -8,7 +8,7 @@ # @tempfile = Tempfile.new("danbooru-test") # @download = Downloads::File.new(@source, @tempfile.path) # end -# +# # should "work" do # @download.download! # assert_equal(201248, ::File.size(@tempfile.path)) diff --git a/test/unit/dtext_test.rb b/test/unit/dtext_test.rb index 68dc72188..98d49203c 100644 --- a/test/unit/dtext_test.rb +++ b/test/unit/dtext_test.rb @@ -4,18 +4,18 @@ class DTextTest < ActiveSupport::TestCase def p(s) DText.parse(s) end - + def test_sanitize assert_equal('<
', p("<")) assert_equal('>
', p(">")) assert_equal('&
', p("&")) end - + def test_wiki_links assert_equal("a b c
", p("a [[b]] c")) assert_equal("a spoiler c
", p("a [[spoiler]] c")) end - + def test_spoilers assert_equal("this is
an inline spoiler
.
", p("this is [spoiler]an inline spoiler[/spoiler].")) assert_equal("this is
a block spoiler
.
", p("this is\n\n[spoiler]\na block spoiler\n[/spoiler].")) @@ -23,24 +23,24 @@ class DTextTest < ActiveSupport::TestCase assert_equal("", p("[spoiler]this is a spoiler with no closing tag\nnew text")) assert_equal("this is a spoiler with no closing tag
new text\n", p("[spoiler]this is [spoiler]a nested[/spoiler] spoiler[/spoiler]")) end - + def test_paragraphs assert_equal("this is
\n\na nested
spoiler
\na
", p("a")) assert_equal("abc
", p("abc")) assert_equal("a
", p("a\nb\nc")) assert_equal("
b
ca
b
", p("a\n\nb")) end - + def test_headers assert_equal("header
", p("h1. header")) assert_equal("header
paragraph
", p("h1.header\n\nparagraph")) end - + def test_quote_blocks assert_equal('', p("[quote]\ntest\n[/quote]")) assert_equal("test
\n", p("[quote]\na\n[quote]\nb\n[/quote]\nc\n[/quote]")) end - + def test_urls assert_equal('a
\n\nb
c
\na http://test.com b
', p('a http://test.com b')) assert_equal('', p("http://test.com\nb")) @@ -49,7 +49,7 @@ class DTextTest < ActiveSupport::TestCase assert_equal('a http://test.com. b
', p('a http://test.com. b')) assert_equal('a (http://test.com) b
', p('a (http://test.com) b')) end - + # def test_links # assert_equal('', p('[url=http://test.com]test[/url]')) # assert_equal('"1" 2
', p('"1" [url=http://two.com]2[/url]')) @@ -61,29 +61,29 @@ class DTextTest < ActiveSupport::TestCase assert_equal('"1" 2
', p('"1" "2":http://two.com')) assert_equal('"1" 2 & 3
', p('"1" "2 & 3":http://three.com')) end - + # def test_aliased_urls # assert_equal('a bob. b
', p('a [url=http://test.com]bob[/url]. b')) # assert_equal('', p('[i][url=http://test.com]bob[/url][/i]')) # end - + def test_lists assert_equal('', p('* a')) assert_equal('
- a
', p("* a\n* b").gsub(/\n/, "")) assert_equal('
- a
- b
', p("* a\n** b").gsub(/\n/, "")) assert_equal('', p("* post #1").gsub(/\n/, "")) end - + def test_inline assert_equal('', p("{{tag}}")) assert_equal('', p("{{tag1 tag2}}")) assert_equal('', p("{{<3}}")) end - + def test_extra_newlines assert_equal('
- a
- b
a
b
', p("a\n\n\n\n\n\n\nb\n\n\n\n")) end - + def test_complex_links assert_equal("", p("[[1|2 3]] | [[4|5 6]]")) assert_equal("Tags (Tagging Guidelines | Tag Checklist | Tag Groups)
", p("Tags [b]([[howto:tag|Tagging Guidelines]] | [[howto:tag_checklist|Tag Checklist]] | [[Tag Groups]])[/b]")) diff --git a/test/unit/favorite_test.rb b/test/unit/favorite_test.rb index 2f07593fe..371d5c5c9 100644 --- a/test/unit/favorite_test.rb +++ b/test/unit/favorite_test.rb @@ -8,7 +8,7 @@ class FavoriteTest < ActiveSupport::TestCase MEMCACHE.flush_all Favorite # need to force loading the favorite model end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil @@ -18,41 +18,41 @@ class FavoriteTest < ActiveSupport::TestCase should "delete from all tables" do user1 = FactoryGirl.create(:user) p1 = FactoryGirl.create(:post) - + user1.add_favorite!(p1) assert_equal(1, Favorite.count) - + Favorite.destroy_all(:user_id => user1.id, :post_id => p1.id) assert_equal(0, Favorite.count) end - + should "know which table it belongs to" do user1 = FactoryGirl.create(:user) - user2 = FactoryGirl.create(:user) + user2 = FactoryGirl.create(:user) p1 = FactoryGirl.create(:post) p2 = FactoryGirl.create(:post) - + user1.add_favorite!(p1) user1.add_favorite!(p2) user2.add_favorite!(p1) - + favorites = user1.favorites.order("id desc") assert_equal(2, favorites.count) assert_equal(p2.id, favorites[0].post_id) assert_equal(p1.id, favorites[1].post_id) - + favorites = user2.favorites.order("id desc") assert_equal(1, favorites.count) assert_equal(p1.id, favorites[0].post_id) end - + should "not allow duplicates" do user1 = FactoryGirl.create(:user) p1 = FactoryGirl.create(:post) p2 = FactoryGirl.create(:post) user1.add_favorite!(p1) user1.add_favorite!(p1) - + assert_equal(1, user1.favorites.count) end end diff --git a/test/unit/forum_post_test.rb b/test/unit/forum_post_test.rb index 07c785809..f5929d7cc 100644 --- a/test/unit/forum_post_test.rb +++ b/test/unit/forum_post_test.rb @@ -8,12 +8,12 @@ class ForumPostTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" @topic = FactoryGirl.create(:forum_topic) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "that belongs to a topic with several pages of posts" do setup do Danbooru.config.stubs(:posts_per_page).returns(3) @@ -22,7 +22,7 @@ class ForumPostTest < ActiveSupport::TestCase @posts << FactoryGirl.create(:forum_post, :topic_id => @topic.id, :body => rand(100_000)) end end - + should "know which page it's on" do assert_equal(2, @posts[3].forum_topic_page) assert_equal(2, @posts[4].forum_topic_page) @@ -30,26 +30,26 @@ class ForumPostTest < ActiveSupport::TestCase assert_equal(3, @posts[6].forum_topic_page) end end - + context "belonging to a locked topic" do setup do @post = FactoryGirl.create(:forum_post, :topic_id => @topic.id, :body => "zzz") @topic.update_attribute(:is_locked, true) @post.reload end - + should "not be updateable" do @post.update_attributes(:body => "xxx") @post.reload assert_equal("zzz", @post.body) end - + should "not be deletable" do @post.destroy assert_equal(1, ForumPost.count) end end - + should "update its parent when saved" do sleep 1 original_topic_updated_at = @topic.updated_at @@ -57,37 +57,37 @@ class ForumPostTest < ActiveSupport::TestCase @topic.reload assert_not_equal(original_topic_updated_at, @topic.updated_at) end - + should "be searchable by body content" do post = FactoryGirl.create(:forum_post, :topic_id => @topic.id, :body => "xxx") assert_equal(1, ForumPost.body_matches("xxx").count) assert_equal(0, ForumPost.body_matches("aaa").count) end - + should "initialize its creator" do post = FactoryGirl.create(:forum_post, :topic_id => @topic.id) assert_equal(@user.id, post.creator_id) end - + context "that is deleted" do setup do @post = FactoryGirl.create(:forum_post, :topic_id => @topic.id) @post.update_attribute(:is_deleted, true) @topic.reload end - + should "also delete the topic" do assert(@topic.is_deleted) end end - + context "updated by a second user" do setup do @post = FactoryGirl.create(:forum_post, :topic_id => @topic.id) @second_user = FactoryGirl.create(:user) CurrentUser.user = @second_user end - + should "record its updater" do @post.update_attributes(:body => "abc") assert_equal(@second_user.id, @post.updater_id) diff --git a/test/unit/forum_topic_test.rb b/test/unit/forum_topic_test.rb index ece7e7353..ceea59e9a 100644 --- a/test/unit/forum_topic_test.rb +++ b/test/unit/forum_topic_test.rb @@ -8,48 +8,48 @@ class ForumTopicTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" @topic = FactoryGirl.create(:forum_topic, :title => "xxx") end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "constructed with nested attributes for its original post" do should "create a matching forum post" do assert_difference(["ForumTopic.count", "ForumPost.count"], 1) do @topic = FactoryGirl.create(:forum_topic, :title => "abc", :original_post_attributes => {:body => "abc"}) - end + end end end - + should "be searchable by title" do assert_equal(1, ForumTopic.title_matches("xxx").count) assert_equal(0, ForumTopic.title_matches("aaa").count) end - + should "initialize its creator" do assert_equal(@user.id, @topic.creator_id) end - + context "updated by a second user" do setup do @second_user = FactoryGirl.create(:user) CurrentUser.user = @second_user end - + should "record its updater" do @topic.update_attributes(:title => "abc") assert_equal(@second_user.id, @topic.updater_id) end end - + context "with multiple posts that has been deleted" do setup do 5.times do FactoryGirl.create(:forum_post, :topic_id => @topic.id) end end - + should "delete any associated posts" do assert_difference("ForumPost.count", -5) do @topic.destroy diff --git a/test/unit/ip_ban_test.rb b/test/unit/ip_ban_test.rb index 019201cca..8188f1c40 100644 --- a/test/unit/ip_ban_test.rb +++ b/test/unit/ip_ban_test.rb @@ -8,7 +8,7 @@ class IpBanTest < ActiveSupport::TestCase MEMCACHE.flush_all Danbooru.config.stubs(:member_comment_time_threshold).returns(1.week.from_now) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil @@ -19,7 +19,7 @@ class IpBanTest < ActiveSupport::TestCase counts = IpBan.count_by_ip_addr("comments", [comment.creator_id], "creator_id", "ip_addr") assert_equal([{"ip_addr" => "127.0.0.1", "count" => "1"}], counts) end - + should "be able to count any updates from a user, groupiny by IP address" do CurrentUser.scoped(@user, "1.2.3.4") do comment = FactoryGirl.create(:comment, :body => "aaa") diff --git a/test/unit/janitor_trial_test.rb b/test/unit/janitor_trial_test.rb index 0fcd42615..aff540e2e 100644 --- a/test/unit/janitor_trial_test.rb +++ b/test/unit/janitor_trial_test.rb @@ -9,19 +9,19 @@ class JanitorTrialTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "upon creation" do should "create a dmail when testing a new janitor" do assert_difference("Dmail.count", 2) do JanitorTrial.create(:user_id => @user.id) end end - + should "toggle the janitor flag on the user" do janitor_trial = JanitorTrial.create(:user_id => @user.id) @user.reload @@ -33,19 +33,19 @@ class JanitorTrialTest < ActiveSupport::TestCase setup do @janitor_trial = FactoryGirl.create(:janitor_trial, :user_id => @user.id) end - + should "create a negative feedback record" do assert_difference("UserFeedback.count", 1) do @janitor_trial.demote! end end end - + context "upon promotion" do setup do @janitor_trial = FactoryGirl.create(:janitor_trial, :user_id => @user.id) end - + should "destroy the trial object" do assert_difference("JanitorTrial.count", -1) do @janitor_trial.promote! diff --git a/test/unit/maintenance/user/login_reminder_mailer_test.rb b/test/unit/maintenance/user/login_reminder_mailer_test.rb index 43febdeb0..887b3217a 100644 --- a/test/unit/maintenance/user/login_reminder_mailer_test.rb +++ b/test/unit/maintenance/user/login_reminder_mailer_test.rb @@ -7,7 +7,7 @@ module Maintenance setup do @user = FactoryGirl.create(:user) end - + should "send the notie" do LoginReminderMailer.notice(@user).deliver assert !ActionMailer::Base.deliveries.empty? diff --git a/test/unit/moderator/ip_addr_search_test.rb b/test/unit/moderator/ip_addr_search_test.rb index e3587baff..6f162ea37 100644 --- a/test/unit/moderator/ip_addr_search_test.rb +++ b/test/unit/moderator/ip_addr_search_test.rb @@ -11,17 +11,17 @@ module Moderator FactoryGirl.create(:comment) MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "find by ip addr" do @search = IpAddrSearch.new(:ip_addr => "127.0.0.1") assert_equal({@user.id.to_s => 2}, @search.execute) end - + should "find by user id" do @search = IpAddrSearch.new(:user_id => @user.id.to_s) assert_equal({"127.0.0.1" => 2}, @search.execute) diff --git a/test/unit/moderator/tag_batch_change_test.rb b/test/unit/moderator/tag_batch_change_test.rb index 11c54a3de..6780a64e7 100644 --- a/test/unit/moderator/tag_batch_change_test.rb +++ b/test/unit/moderator/tag_batch_change_test.rb @@ -9,7 +9,7 @@ module Moderator CurrentUser.ip_addr = "127.0.0.1" @post = FactoryGirl.create(:post, :tag_string => "aaa") end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil @@ -21,7 +21,7 @@ module Moderator @post.reload assert_equal("bbb", @post.tag_string) end - + should "raise an error if there is no predicate" do tag_batch_change = TagBatchChange.new("", "bbb", @user, "127.0.0.1") assert_raises(TagBatchChange::Error) do diff --git a/test/unit/note_test.rb b/test/unit/note_test.rb index fee01a7f2..b23193a0f 100644 --- a/test/unit/note_test.rb +++ b/test/unit/note_test.rb @@ -8,35 +8,35 @@ class NoteTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "for a post that already has a note" do setup do @post = FactoryGirl.create(:post) @note = FactoryGirl.create(:note, :post => @post) end - + context "when the note is deleted the post" do setup do @note.toggle!(:is_active) end - + should "null out its last_noted_at_field" do @post.reload assert_nil(@post.last_noted_at) end end end - + context "creating a note" do setup do @post = FactoryGirl.create(:post) end - + should "create a version" do assert_difference("NoteVersion.count", 1) do @note = FactoryGirl.create(:note, :post => @post) @@ -45,7 +45,7 @@ class NoteTest < ActiveSupport::TestCase assert_equal(1, @note.versions.count) assert_equal(@note.body, @note.versions.first.body) end - + should "update the post's last_noted_at field" do assert_nil(@post.last_noted_at) @note = FactoryGirl.create(:note, :post => @post) @@ -64,29 +64,29 @@ class NoteTest < ActiveSupport::TestCase @note.save end assert_equal(["Post is note locked"], @note.errors.full_messages) - end + end end end - + context "updating a note" do setup do @post = FactoryGirl.create(:post) @note = FactoryGirl.create(:note, :post => @post) end - + should "increment the updater's note_update_count" do assert_difference("CurrentUser.note_update_count", 1) do @note.update_attributes(:body => "zzz") end end - + should "update the post's last_noted_at field" do assert_nil(@post.last_noted_at) @note.update_attributes(:x => 1000) @post.reload assert_equal(@post.last_noted_at.to_i, @note.updated_at.to_i) end - + should "create a version" do assert_difference("NoteVersion.count", 1) do @note.update_attributes(:body => "fafafa") @@ -94,19 +94,19 @@ class NoteTest < ActiveSupport::TestCase assert_equal(2, @note.versions.count) assert_equal("fafafa", @note.versions.last.body) end - + context "for a note-locked post" do setup do @post.update_attribute(:is_note_locked, true) end - + should "fail" do @note.update_attributes(:x => 1000) assert_equal(["Post is note locked"], @note.errors.full_messages) end end end - + context "when notes have been vandalized by one user" do setup do @vandal = FactoryGirl.create(:user) @@ -115,7 +115,7 @@ class NoteTest < ActiveSupport::TestCase @note.update_attributes(:x => 2000, :y => 2000) end end - + context "the act of undoing all changes by that user" do should "revert any affected notes" do Note.undo_changes_by_user(@vandal.id) @@ -130,13 +130,13 @@ class NoteTest < ActiveSupport::TestCase setup do @note = FactoryGirl.create(:note, :body => "aaa") end - + context "where the body contains the string 'aaa'" do should "return a hit" do assert_equal(1, Note.body_matches("aaa").count) end end - + context "where the body contains the string 'bbb'" do should "return no hits" do assert_equal(0, Note.body_matches("bbb").count) diff --git a/test/unit/pool_test.rb b/test/unit/pool_test.rb index 512bbd791..2e6d592c2 100644 --- a/test/unit/pool_test.rb +++ b/test/unit/pool_test.rb @@ -7,36 +7,36 @@ class PoolTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "A name" do setup do @pool = FactoryGirl.create(:pool, :name => "xxx") end - + should "be mapped to a pool id" do assert_equal(@pool.id, Pool.name_to_id("xxx")) end end - + context "An id number" do setup do @pool = FactoryGirl.create(:pool) end - + should "be mapped to a pool id" do assert_equal(@pool.id, Pool.name_to_id(@pool.id.to_s)) end - + should "be mapped to its name" do assert_equal(@pool.name, Pool.id_to_name(@pool.id)) end end - + context "Reverting a pool" do setup do @pool = FactoryGirl.create(:pool) @@ -54,7 +54,7 @@ class PoolTest < ActiveSupport::TestCase CurrentUser.ip_addr = "1.2.3.8" @pool.revert_to!(@pool.versions.all[1]) end - + should "have the correct versions" do assert_equal(6, @pool.versions.size) assert_equal("", @pool.versions.all[0].post_ids) @@ -63,51 +63,51 @@ class PoolTest < ActiveSupport::TestCase assert_equal("#{@p1.id} #{@p2.id} #{@p3.id}", @pool.versions.all[3].post_ids) assert_equal("#{@p2.id} #{@p3.id}", @pool.versions.all[4].post_ids) end - + should "update its post_ids" do assert_equal("#{@p1.id}", @pool.post_ids) end - + should "update any old posts that were removed" do @p2.reload assert_equal("", @p2.pool_string) end - + should "update any new posts that were added" do @p1.reload assert_equal("pool:#{@pool.id}", @p1.pool_string) end end - + context "Updating a pool" do setup do @pool = FactoryGirl.create(:pool) @p1 = FactoryGirl.create(:post) @p2 = FactoryGirl.create(:post) end - + context "by adding a new post" do setup do @pool.add!(@p1) end - + should "add the post to the pool" do assert_equal("#{@p1.id}", @pool.post_ids) end - + should "add the pool to the post" do assert_equal("pool:#{@pool.id}", @p1.pool_string) end - + should "increment the post count" do assert_equal(1, @pool.post_count) end - + context "to a pool that already has the post" do setup do @pool.add!(@p1) end - + should "not double add the post to the pool" do assert_equal("#{@p1.id}", @pool.post_ids) end @@ -121,12 +121,12 @@ class PoolTest < ActiveSupport::TestCase end end end - + context "by removing a post" do setup do @pool.add!(@p1) end - + context "that is in the pool" do setup do @pool.remove!(@p1) @@ -144,26 +144,26 @@ class PoolTest < ActiveSupport::TestCase assert_equal(0, @pool.post_count) end end - + context "that is not in the pool" do setup do @pool.remove!(@p2) end - + should "not affect the pool" do assert_equal("#{@p1.id}", @pool.post_ids) end - + should "not affect the post" do assert_equal("pool:#{@pool.id}", @p1.pool_string) end - + should "not affect the post count" do assert_equal(1, @pool.post_count) end end end - + should "create new versions for each distinct user" do assert_equal(1, @pool.versions(true).size) @pool.post_ids = "#{@p1.id}" @@ -174,24 +174,24 @@ class PoolTest < ActiveSupport::TestCase @pool.save assert_equal(2, @pool.versions(true).size) end - + should "know what its post ids were previously" do @pool.post_ids = "#{@p1.id}" assert_equal("", @pool.post_ids_was) assert_equal([], @pool.post_id_array_was) end - + should "normalize its name" do @pool.update_attributes(:name => "A B") assert_equal("A_B", @pool.name) end - + should "normalize its post ids" do @pool.update_attributes(:post_ids => " 1 2 ") assert_equal("1 2", @pool.post_ids) end end - + context "An existing pool" do setup do @pool = FactoryGirl.create(:pool) @@ -207,20 +207,20 @@ class PoolTest < ActiveSupport::TestCase @pool.reload # clear cached neighbors @p3_neighbors = @pool.neighbors(@p3) end - + context "that is synchronized" do setup do @pool.reload @pool.post_ids = "#{@p2.id}" @pool.synchronize! end - + should "update the pool" do @pool.reload assert_equal(1, @pool.post_count) assert_equal("#{@p2.id}", @pool.post_ids) end - + should "update the posts" do @p1.reload @p2.reload @@ -230,17 +230,17 @@ class PoolTest < ActiveSupport::TestCase assert_equal("", @p3.pool_string) end end - + should "find the neighbors for the first post" do assert_nil(@p1_neighbors.previous) assert_equal(@p2.id, @p1_neighbors.next) end - + should "find the neighbors for the middle post" do assert_equal(@p1.id, @p2_neighbors.previous) assert_equal(@p3.id, @p2_neighbors.next) end - + should "find the neighbors for the last post" do assert_equal(@p2.id, @p3_neighbors.previous) assert_nil(@p3_neighbors.next) @@ -252,7 +252,7 @@ class PoolTest < ActiveSupport::TestCase user = FactoryGirl.create(:user) CurrentUser.user = user end - + should "have a name starting with anon" do pool = Pool.create_anonymous assert_match(/^anon:\d+$/, pool.name) diff --git a/test/unit/post_appeal_test.rb b/test/unit/post_appeal_test.rb index ff7a46d8a..bc44b4324 100644 --- a/test/unit/post_appeal_test.rb +++ b/test/unit/post_appeal_test.rb @@ -14,24 +14,24 @@ class PostAppealTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "a user" do setup do @post = FactoryGirl.create(:post, :tag_string => "aaa", :is_deleted => true) end - + should "not be able to appeal a post more than twice" do assert_difference("PostAppeal.count", 1) do @post_appeal = PostAppeal.create(:post => @post, :reason => "aaa") end - + assert_difference("PostAppeal.count", 0) do @post_appeal = PostAppeal.create(:post => @post, :reason => "aaa") end - + assert_equal(["You have already appealed this post"], @post_appeal.errors.full_messages) end - + should "not be able to appeal more than 5 posts in 24 hours" do @post_appeal = PostAppeal.new(:post => @post, :reason => "aaa") @post_appeal.expects(:appeal_count_for_creator).returns(5) @@ -40,7 +40,7 @@ class PostAppealTest < ActiveSupport::TestCase end assert_equal(["You can appeal at most 5 post a day"], @post_appeal.errors.full_messages) end - + should "not be able to appeal an active post" do @post.update_attribute(:is_deleted, false) assert_difference("PostAppeal.count", 0) do @@ -48,7 +48,7 @@ class PostAppealTest < ActiveSupport::TestCase end assert_equal(["Post is active"], @post_appeal.errors.full_messages) end - + should "initialize its creator" do @post_appeal = PostAppeal.create(:post => @post, :reason => "aaa") assert_equal(@alice.id, @post_appeal.creator_id) diff --git a/test/unit/post_disapproval_test.rb b/test/unit/post_disapproval_test.rb index 3355197ce..4cd5a30c0 100644 --- a/test/unit/post_disapproval_test.rb +++ b/test/unit/post_disapproval_test.rb @@ -13,13 +13,13 @@ class PostDisapprovalTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "A post disapproval" do setup do @post_1 = FactoryGirl.create(:post, :is_pending => true) @post_2 = FactoryGirl.create(:post, :is_pending => true) end - + context "made by alice" do setup do @disapproval = PostDisapproval.create(:user => @alice, :post => @post_1) @@ -29,7 +29,7 @@ class PostDisapprovalTest < ActiveSupport::TestCase setup do CurrentUser.user = @alice end - + should "remove the associated post from alice's moderation queue" do assert(!Post.available_for_moderation(false).map(&:id).include?(@post_1.id)) assert(Post.available_for_moderation(false).map(&:id).include?(@post_2.id)) @@ -41,7 +41,7 @@ class PostDisapprovalTest < ActiveSupport::TestCase @brittony = FactoryGirl.create(:moderator_user) CurrentUser.user = @brittony end - + should "not remove the associated post from brittony's moderation queue" do assert(Post.available_for_moderation(false).map(&:id).include?(@post_1.id)) assert(Post.available_for_moderation(false).map(&:id).include?(@post_2.id)) @@ -55,7 +55,7 @@ class PostDisapprovalTest < ActiveSupport::TestCase @user = FactoryGirl.create(:user) @disapproval = PostDisapproval.create(:user => @user, :post => @post) end - + should "be pruned" do assert_difference("PostDisapproval.count", -1) do PostDisapproval.prune! diff --git a/test/unit/post_flag_test.rb b/test/unit/post_flag_test.rb index 270eceac9..be1e75bb1 100644 --- a/test/unit/post_flag_test.rb +++ b/test/unit/post_flag_test.rb @@ -13,24 +13,24 @@ class PostFlagTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "a user" do setup do @post = FactoryGirl.create(:post, :tag_string => "aaa") end - + should "not be able to flag a post more than twice" do assert_difference("PostFlag.count", 1) do @post_flag = PostFlag.create(:post => @post, :reason => "aaa", :is_resolved => false) end - + assert_difference("PostFlag.count", 0) do @post_flag = PostFlag.create(:post => @post, :reason => "aaa", :is_resolved => false) end - + assert_equal(["You have already flagged this post"], @post_flag.errors.full_messages) end - + should "not be able to flag more than 10 posts in 24 hours" do @post_flag = PostFlag.new(:post => @post, :reason => "aaa", :is_resolved => false) @post_flag.expects(:flag_count_for_creator).returns(10) @@ -39,7 +39,7 @@ class PostFlagTest < ActiveSupport::TestCase end assert_equal(["You can flag 10 posts a day"], @post_flag.errors.full_messages) end - + should "not be able to flag a deleted post" do @post.update_attribute(:is_deleted, true) assert_difference("PostFlag.count", 0) do @@ -47,7 +47,7 @@ class PostFlagTest < ActiveSupport::TestCase end assert_equal(["Post is deleted"], @post_flag.errors.full_messages) end - + should "initialize its creator" do @post_flag = PostFlag.create(:post => @post, :reason => "aaa", :is_resolved => false) assert_equal(@alice.id, @post_flag.creator_id) diff --git a/test/unit/post_pruner_test.rb b/test/unit/post_pruner_test.rb index e3167128d..95d57a7fd 100644 --- a/test/unit/post_pruner_test.rb +++ b/test/unit/post_pruner_test.rb @@ -6,7 +6,7 @@ class PostPrunerTest < ActiveSupport::TestCase CurrentUser.user = @user CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all - + @flagger = FactoryGirl.create(:user) @old_post = FactoryGirl.create(:post, :created_at => 5.days.ago, :is_pending => true) @unresolved_flagged_post = FactoryGirl.create(:post, :is_flagged => true) @@ -16,25 +16,25 @@ class PostPrunerTest < ActiveSupport::TestCase @unresolved_post_flag = FactoryGirl.create(:post_flag, :created_at => 5.days.ago, :is_resolved => false, :post_id => @unresolved_flagged_post.id) @resolved_post_flag = FactoryGirl.create(:post_flag, :created_at => 5.days.ago, :is_resolved => true, :post_id => @resolved_flagged_post.id) end - + PostPruner.new.prune! end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "prune old pending posts" do @old_post.reload assert(@old_post.is_deleted?) end - + should "prune old flagged posts that are still unresolved" do @unresolved_flagged_post.reload assert(@unresolved_flagged_post.is_deleted?) end - + should "not prune old flagged posts that are resolved" do @resolved_flagged_post.reload assert(!@resolved_flagged_post.is_deleted?) diff --git a/test/unit/post_sets/favorite_test.rb b/test/unit/post_sets/favorite_test.rb index 28a42e2ef..e9257a823 100644 --- a/test/unit/post_sets/favorite_test.rb +++ b/test/unit/post_sets/favorite_test.rb @@ -16,12 +16,12 @@ module PostSets @post_1.add_favorite!(@user) @post_3.add_favorite!(@user) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "a favorite set for before the most recent post" do setup do id = ::Favorite.where(:user_id => @user.id, :post_id => @post_3.id).first.id @@ -36,7 +36,7 @@ module PostSets end end end - + context "a favorite set for after the second most recent post" do setup do id = ::Favorite.where(:user_id => @user.id, :post_id => @post_2.id).first.id @@ -51,7 +51,7 @@ module PostSets end end end - + context "a favorite set for page 2" do setup do ::Favorite.stubs(:records_per_page).returns(1) @@ -65,7 +65,7 @@ module PostSets end end end - + context "a favorite set with no page specified" do setup do ::Favorite.stubs(:records_per_page).returns(1) diff --git a/test/unit/post_sets/pool_test.rb b/test/unit/post_sets/pool_test.rb index 9e99e080b..2f9d9a846 100644 --- a/test/unit/post_sets/pool_test.rb +++ b/test/unit/post_sets/pool_test.rb @@ -17,12 +17,12 @@ module PostSets @pool.add!(@post_1) @pool.add!(@post_3) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "a post pool set for page 2" do setup do @set = PostSets::Pool.new(@pool, 2) @@ -33,16 +33,16 @@ module PostSets assert_equal(1, @set.posts.size) assert_equal(@post_1.id, @set.posts.first.id) end - + should "know the total number of pages" do assert_equal(3, @set.total_pages) end - + should "know the current page" do assert_equal(2, @set.current_page) end end - + context "a post pool set with no page specified" do setup do @set = PostSets::Pool.new(@pool) diff --git a/test/unit/post_sets/post_test.rb b/test/unit/post_sets/post_test.rb index cbf433256..d6ef6b825 100644 --- a/test/unit/post_sets/post_test.rb +++ b/test/unit/post_sets/post_test.rb @@ -14,46 +14,46 @@ module PostSets @post_2 = FactoryGirl.create(:post, :tag_string => "b") @post_3 = FactoryGirl.create(:post, :tag_string => "c") end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "a set for page 2" do setup do @set = PostSets::Post.new("", 2) ::Post.stubs(:records_per_page).returns(1) end - + should "return the second element" do assert_equal(@post_2.id, @set.posts.first.id) end end - + context "a set for the 'a' tag query" do setup do @post_4 = FactoryGirl.create(:post, :tag_string => "a") @post_5 = FactoryGirl.create(:post, :tag_string => "a") end - + context "with no page" do setup do @set = PostSets::Post.new("a") ::Post.stubs(:records_per_page).returns(1) end - + should "return the first element" do assert_equal(@post_5.id, @set.posts.first.id) end end - + context "for before the first element" do setup do @set = PostSets::Post.new("a", "b#{@post_5.id}") ::Post.stubs(:records_per_page).returns(1) end - + should "return the second element" do assert_equal(@post_4.id, @set.posts.first.id) end @@ -64,40 +64,40 @@ module PostSets @set = PostSets::Post.new("a", "a#{@post_4.id}") @set.stubs(:records_per_page).returns(1) end - + should "return the first element" do assert_equal(@post_5.id, @set.posts.first.id) end end end - + context "a set for the 'a b' tag query" do setup do @set = PostSets::Post.new("a b") end - + should "know it isn't a single tag" do assert(!@set.is_single_tag?) end end - + context "a set going to the 1,001st page" do setup do @set = PostSets::Post.new("a", 1_001) end - + should "fail" do assert_raises(Danbooru::Paginator::PaginationError) do @set.posts end end end - + context "a set for the 'a b c' tag query" do setup do @set = PostSets::Post.new("a b c") end - + context "for a non-privileged user" do should "fail" do assert_raises(PostSets::SearchError) do @@ -105,12 +105,12 @@ module PostSets end end end - + context "for a privileged user" do setup do CurrentUser.user = FactoryGirl.create(:privileged_user) end - + should "pass" do assert_nothing_raised do @set.posts @@ -118,44 +118,44 @@ module PostSets end end end - + context "a set for the 'a' tag query" do setup do @set = PostSets::Post.new("a") end - + should "know it is a single tag" do assert(@set.is_single_tag?) end - + should "normalize its tag query" do assert_equal("a", @set.tag_string) end - + should "know the count" do assert_equal(1, @set.posts.total_count) end - + should "find the posts" do assert_equal(@post_1.id, @set.posts.first.id) end - + context "that has a matching wiki page" do setup do @wiki_page = FactoryGirl.create(:wiki_page, :title => "a") end - + should "find the wiki page" do assert_not_nil(@set.wiki_page) assert_equal(@wiki_page.id, @set.wiki_page.id) end end - + context "that has a matching artist" do setup do @artist = FactoryGirl.create(:artist, :name => "a") end - + should "find the artist" do assert_not_nil(@set.artist) assert_equal(@artist.id, @set.artist.id) diff --git a/test/unit/post_test.rb b/test/unit/post_test.rb index 6b048d866..3c0b05b43 100644 --- a/test/unit/post_test.rb +++ b/test/unit/post_test.rb @@ -8,54 +8,54 @@ class PostTest < ActiveSupport::TestCase MEMCACHE.flush_all Delayed::Worker.delay_jobs = false end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "Deletion:" do context "Annihilating a post" do setup do @post = FactoryGirl.create(:post) end - + context "that is status locked" do setup do @post.update_attributes({:is_status_locked => true}, :as => :admin) end - + should "not destroy the record" do @post.annihilate! assert_equal(1, Post.where("id = ?", @post.id).count) end end - + should "destroy the record" do @post.annihilate! assert_equal([], @post.errors.full_messages) assert_equal(0, Post.where("id = ?", @post.id).count) end end - + context "Deleting a post" do setup do Danbooru.config.stubs(:blank_tag_search_fast_count).returns(nil) end - + context "that is status locked" do setup do @post = FactoryGirl.create(:post) @post.update_attributes({:is_status_locked => true}, :as => :admin) end - + should "fail" do @post.delete! assert_equal(["Is status locked ; cannot delete post"], @post.errors.full_messages) assert_equal(1, Post.where("id = ?", @post.id).count) end end - + should "update the fast count" do post = FactoryGirl.create(:post, :tag_string => "aaa") assert_equal(1, Post.fast_count) @@ -64,14 +64,14 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, Post.fast_count) assert_equal(1, Post.fast_count("aaa")) end - + should "toggle the is_deleted flag" do post = FactoryGirl.create(:post) assert_equal(false, post.is_deleted?) post.delete! assert_equal(true, post.is_deleted?) end - + should "not decrement the tag counts" do post = FactoryGirl.create(:post, :tag_string => "aaa") assert_equal(1, Tag.find_by_name("aaa").post_count) @@ -80,7 +80,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "Parenting:" do context "Assignining a parent to a post" do should "update the has_children flag on the parent" do @@ -90,7 +90,7 @@ class PostTest < ActiveSupport::TestCase p1.reload assert(p1.has_children?, "Parent not updated after child was added") end - + should "update the has_children flag on the old parent" do p1 = FactoryGirl.create(:post) p2 = FactoryGirl.create(:post) @@ -108,7 +108,7 @@ class PostTest < ActiveSupport::TestCase post.save assert(post.errors[:parent].any?, "Parent should be invalid") end - + # should "fail if the parent has a parent" do # p1 = FactoryGirl.create(:post) # c1 = FactoryGirl.create(:post, :parent_id => p1.id) @@ -117,7 +117,7 @@ class PostTest < ActiveSupport::TestCase # assert(c2.errors[:parent].any?, "Parent should be invalid") # end end - + context "Destroying a post with" do context "a parent" do should "reset the has_children flag of the parent" do @@ -127,7 +127,7 @@ class PostTest < ActiveSupport::TestCase p1.reload assert_equal(false, p1.has_children?) end - + should "reassign favorites to the parent" do p1 = FactoryGirl.create(:post) c1 = FactoryGirl.create(:post, :parent_id => p1.id) @@ -148,7 +148,7 @@ class PostTest < ActiveSupport::TestCase assert(!p1.has_children?, "Parent should not have children") end end - + context "one child" do should "remove the has_children flag" do p1 = FactoryGirl.create(:post) @@ -156,7 +156,7 @@ class PostTest < ActiveSupport::TestCase p1.delete! assert_equal(false, p1.has_children?) end - + should "remove the parent of that child" do p1 = FactoryGirl.create(:post) c1 = FactoryGirl.create(:post, :parent_id => p1.id) @@ -165,7 +165,7 @@ class PostTest < ActiveSupport::TestCase assert_nil(c1.parent) end end - + context "two or more children" do should "reparent all children to the first child" do p1 = FactoryGirl.create(:post) @@ -182,7 +182,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "Undestroying a post with a parent" do should "create a new approver" do new_user = FactoryGirl.create(:moderator_user) @@ -195,7 +195,7 @@ class PostTest < ActiveSupport::TestCase p1.reload assert_equal(new_user.id, c1.approver_id) end - + should "not preserve the parent's has_children flag" do p1 = FactoryGirl.create(:post) c1 = FactoryGirl.create(:post, :parent_id => p1.id) @@ -213,25 +213,25 @@ class PostTest < ActiveSupport::TestCase setup do @post = FactoryGirl.create(:post, :is_deleted => true) end - + context "that is status locked" do setup do @post.update_attributes({:is_status_locked => true}, :as => :admin) end - + should "not allow undeletion" do @post.undelete! assert_equal(["Is status locked ; cannot undelete post"], @post.errors.full_messages) assert_equal(true, @post.is_deleted?) end end - + should "be undeleted" do @post.undelete! @post.reload assert_equal(false, @post.is_deleted?) end - + should "be appealed" do assert_difference("PostAppeal.count", 1) do @post.appeal!("xxx") @@ -240,7 +240,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, @post.appeals.count) end end - + context "An approved post" do should "be flagged" do post = FactoryGirl.create(:post) @@ -250,7 +250,7 @@ class PostTest < ActiveSupport::TestCase assert(post.is_flagged?, "Post should be flagged.") assert_equal(1, post.flags.count) end - + should "not be flagged if no reason is given" do post = FactoryGirl.create(:post) assert_difference("PostFlag.count", 0) do @@ -260,20 +260,20 @@ class PostTest < ActiveSupport::TestCase end end end - - context "An unapproved post" do + + context "An unapproved post" do should "preserve the approver's identity when approved" do post = FactoryGirl.create(:post, :is_pending => true) post.approve! assert_equal(post.approver_id, CurrentUser.id) end - + context "that was uploaded by person X" do setup do @post = FactoryGirl.create(:post) @post.flag!("reason") end - + should "not allow person X to approve that post" do assert_raises(Post::ApprovalError) do CurrentUser.scoped(@post.uploader, "127.0.0.1") do @@ -284,7 +284,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(["You cannot approve a post you uploaded"], @post.errors.full_messages) end end - + context "that was previously approved by person X" do setup do @user = FactoryGirl.create(:janitor_user, :name => "xxx") @@ -292,7 +292,7 @@ class PostTest < ActiveSupport::TestCase @post = FactoryGirl.create(:post, :approver_id => @user.id) @post.flag!("bad") end - + should "not allow person X to reapprove that post" do CurrentUser.scoped(@user, "127.0.0.1") do assert_raises(Post::ApprovalError) do @@ -300,7 +300,7 @@ class PostTest < ActiveSupport::TestCase end end end - + should "allow person Y to approve the post" do CurrentUser.scoped(@user2, "127.0.0.1") do assert_nothing_raised do @@ -309,7 +309,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "that has been reapproved" do should "no longer be flagged or pending" do post = FactoryGirl.create(:post) @@ -328,19 +328,19 @@ class PostTest < ActiveSupport::TestCase @post = FactoryGirl.create(:post) @post.update_attributes({:is_status_locked => true}, :as => :admin) end - + should "not allow new flags" do assert_raises(PostFlag::Error) do @post.flag!("wrong") end end - + should "not allow new appeals" do assert_raises(PostAppeal::Error) do @post.appeal!("wrong") end end - + should "not allow approval" do assert_raises(Post::ApprovalError) do @post.approve! @@ -354,7 +354,7 @@ class PostTest < ActiveSupport::TestCase setup do @post = FactoryGirl.create(:post) end - + context "with an artist tag that is then changed to copyright" do setup do Delayed::Worker.delay_jobs = false @@ -364,32 +364,32 @@ class PostTest < ActiveSupport::TestCase @post.update_attribute(:tag_string, "copy:abc") @post.reload end - + teardown do Delayed::Worker.delay_jobs = true end - + should "update the category of the tag" do assert_equal(Tag.categories.copyright, Tag.find_by_name("abc").category) end - + should "update the category cache of the tag" do assert_equal(Tag.categories.copyright, Cache.get("tc:abc")) end - + should "update the tag counts of the posts" do assert_equal(0, @post.tag_count_artist) assert_equal(1, @post.tag_count_copyright) assert_equal(0, @post.tag_count_general) end end - + context "tagged with a metatag" do context "for a parent" do setup do @parent = FactoryGirl.create(:post) end - + should "update the parent relationships for both posts" do @post.update_attributes(:tag_string => "aaa parent:#{@parent.id}") @post.reload @@ -398,14 +398,14 @@ class PostTest < ActiveSupport::TestCase assert(@parent.has_children?) end end - + context "for a pool" do context "on creation" do setup do @pool = FactoryGirl.create(:pool) @post = FactoryGirl.create(:post, :tag_string => "aaa pool:#{@pool.id}") end - + should "add the post to the pool" do @post.reload @pool.reload @@ -413,13 +413,13 @@ class PostTest < ActiveSupport::TestCase assert_equal("pool:#{@pool.id}", @post.pool_string) end end - + context "id" do setup do @pool = FactoryGirl.create(:pool) @post.update_attributes(:tag_string => "aaa pool:#{@pool.id}") end - + should "add the post to the pool" do @post.reload @pool.reload @@ -427,7 +427,7 @@ class PostTest < ActiveSupport::TestCase assert_equal("pool:#{@pool.id}", @post.pool_string) end end - + context "name" do context "that exists" do setup do @@ -442,7 +442,7 @@ class PostTest < ActiveSupport::TestCase assert_equal("pool:#{@pool.id}", @post.pool_string) end end - + context "that doesn't exist" do should "create a new pool and add the post to that pool" do @post.update_attributes(:tag_string => "aaa pool:abc") @@ -455,7 +455,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "for a rating" do context "that is valid" do should "update the rating" do @@ -464,7 +464,7 @@ class PostTest < ActiveSupport::TestCase assert_equal("e", @post.rating) end end - + context "that is invalid" do should "not update the rating" do @post.update_attributes(:tag_string => "aaa rating:z") @@ -473,7 +473,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "for a fav" do should "add the current user to the post's favorite listing" do @post.update_attributes(:tag_string => "aaa fav:self") @@ -482,24 +482,24 @@ class PostTest < ActiveSupport::TestCase end end end - + should "have an array representation of its tags" do post = FactoryGirl.create(:post) post.set_tag_string("aaa bbb") assert_equal(%w(aaa bbb), post.tag_array) assert_equal(%w(tag1 tag2), post.tag_array_was) end - + context "that has been updated" do should "increment the updater's post_update_count" do post = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") - + assert_difference("CurrentUser.post_update_count", 1) do post.update_attributes(:tag_string => "zzz") CurrentUser.reload end end - + should "reset its tag array cache" do post = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") user = FactoryGirl.create(:user) @@ -516,7 +516,7 @@ class PostTest < ActiveSupport::TestCase post = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") end end - + should "update the post counts of relevant tag records" do post1 = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") post2 = FactoryGirl.create(:post, :tag_string => "bbb ccc ddd") @@ -528,12 +528,12 @@ class PostTest < ActiveSupport::TestCase post3.save assert_equal(1, Tag.find_by_name("aaa").post_count) assert_equal(2, Tag.find_by_name("bbb").post_count) - assert_equal(2, Tag.find_by_name("ccc").post_count) - assert_equal(1, Tag.find_by_name("ddd").post_count) + assert_equal(2, Tag.find_by_name("ccc").post_count) + assert_equal(1, Tag.find_by_name("ddd").post_count) assert_equal(0, Tag.find_by_name("eee").post_count) assert_equal(1, Tag.find_by_name("xxx").post_count) end - + should "update its tag counts" do artist_tag = FactoryGirl.create(:artist_tag) copyright_tag = FactoryGirl.create(:copyright_tag) @@ -553,7 +553,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(0, new_post.tag_count_character) assert_equal(1, new_post.tag_count) end - + should "merge any changes that were made after loading the initial set of tags part 1" do post = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") @@ -570,10 +570,10 @@ class PostTest < ActiveSupport::TestCase post_edited_by_user_b.save # final should be, , , - final_post = Post.find(post.id) + final_post = Post.find(post.id) assert_equal(%w(aaa bbb ddd eee), Tag.scan_tags(final_post.tag_string).sort) end - + should "merge any changes that were made after loading the initial set of tags part 2" do # This is the same as part 1, only the order of operations is reversed. # The results should be the same. @@ -593,7 +593,7 @@ class PostTest < ActiveSupport::TestCase post_edited_by_user_b.save # final should be , , , - final_post = Post.find(post.id) + final_post = Post.find(post.id) assert_equal(%w(aaa bbb ddd eee), Tag.scan_tags(final_post.tag_string).sort) end end @@ -608,7 +608,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "Favorites:" do context "Removing a post from a user's favorites" do setup do @@ -618,19 +618,19 @@ class PostTest < ActiveSupport::TestCase @post = FactoryGirl.create(:post) @post.add_favorite!(@user) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "decrement the user's favorite_count" do assert_difference("CurrentUser.favorite_count", -1) do @post.remove_favorite!(@user) CurrentUser.reload end end - + should "decrement the post's score for privileged users" do @post.remove_favorite!(@user) @post.reload @@ -645,7 +645,7 @@ class PostTest < ActiveSupport::TestCase @post.reload assert_equal(1, @post.score) end - + should "not decrement the user's favorite_count if the user did not favorite the post" do @post2 = FactoryGirl.create(:post) assert_difference("CurrentUser.favorite_count", 0) do @@ -654,7 +654,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "Adding a post to a user's favorites" do setup do @user = FactoryGirl.create(:contributor_user) @@ -662,25 +662,25 @@ class PostTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" @post = FactoryGirl.create(:post) end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "increment the user's favorite_count" do assert_difference("CurrentUser.favorite_count", 1) do @post.add_favorite!(@user) CurrentUser.reload end end - + should "increment the post's score for privileged users" do @post.add_favorite!(@user) @post.reload assert_equal(1, @post.score) end - + should "not increment the post's score for basic users" do @member = FactoryGirl.create(:user) CurrentUser.scoped(@member, "127.0.0.1") do @@ -689,7 +689,7 @@ class PostTest < ActiveSupport::TestCase @post.reload assert_equal(0, @post.score) end - + should "update the fav strings ont he post" do @post.add_favorite!(@user) @post.reload @@ -705,7 +705,7 @@ class PostTest < ActiveSupport::TestCase @post.reload assert_equal("", @post.fav_string) assert(!Favorite.exists?(:user_id => @user.id, :post_id => @post.id)) - + @post.remove_favorite!(@user) @post.reload assert_equal("", @post.fav_string) @@ -713,7 +713,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "Pools:" do context "Removing a post from a pool" do should "update the post's pool string" do @@ -728,7 +728,7 @@ class PostTest < ActiveSupport::TestCase assert_equal("", post.pool_string) end end - + context "Adding a post to a pool" do should "update the post's pool string" do post = FactoryGirl.create(:post) @@ -745,7 +745,7 @@ class PostTest < ActiveSupport::TestCase end end end - + context "Uploading:" do context "Uploading a post" do should "capture who uploaded the post" do @@ -772,28 +772,28 @@ class PostTest < ActiveSupport::TestCase count = Post.tag_match("'").count assert_equal(1, count) end - + should "return posts for the \\ tag" do post1 = FactoryGirl.create(:post, :tag_string => "\\") post2 = FactoryGirl.create(:post, :tag_string => "aaa bbb") count = Post.tag_match("\\").count assert_equal(1, count) end - + should "return posts for the ( tag" do post1 = FactoryGirl.create(:post, :tag_string => "(") post2 = FactoryGirl.create(:post, :tag_string => "aaa bbb") count = Post.tag_match("(").count assert_equal(1, count) end - + should "return posts for the ? tag" do post1 = FactoryGirl.create(:post, :tag_string => "?") post2 = FactoryGirl.create(:post, :tag_string => "aaa bbb") count = Post.tag_match("?").count assert_equal(1, count) end - + should "return posts for 1 tag" do post1 = FactoryGirl.create(:post, :tag_string => "aaa") post2 = FactoryGirl.create(:post, :tag_string => "aaa bbb") @@ -812,7 +812,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post2.id, relation.first.id) end - + should "return posts for 1 tag with exclusion" do post1 = FactoryGirl.create(:post, :tag_string => "aaa") post2 = FactoryGirl.create(:post, :tag_string => "aaa bbb") @@ -821,7 +821,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post1.id, relation.first.id) end - + should "return posts for 1 tag with a pattern" do post1 = FactoryGirl.create(:post, :tag_string => "aaa") post2 = FactoryGirl.create(:post, :tag_string => "aaab bbb") @@ -829,9 +829,9 @@ class PostTest < ActiveSupport::TestCase relation = Post.tag_match("a*") assert_equal(2, relation.count) assert_equal(post2.id, relation.all[0].id) - assert_equal(post1.id, relation.all[1].id) + assert_equal(post1.id, relation.all[1].id) end - + should "return posts for 2 tags, one with a pattern" do post1 = FactoryGirl.create(:post, :tag_string => "aaa") post2 = FactoryGirl.create(:post, :tag_string => "aaab bbb") @@ -840,7 +840,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post2.id, relation.first.id) end - + should "return posts for the metatag" do post1 = FactoryGirl.create(:post) post2 = FactoryGirl.create(:post) @@ -855,7 +855,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post1.id, relation.first.id) end - + should "return posts for the metatag" do post1 = FactoryGirl.create(:post) post2 = FactoryGirl.create(:post) @@ -866,7 +866,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post1.id, relation.first.id) end - + should "return posts for the metatag" do post1 = FactoryGirl.create(:post) post2 = FactoryGirl.create(:post) @@ -877,13 +877,13 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post1.id, relation.first.id) end - + should "return posts for the metatag" do second_user = FactoryGirl.create(:user) post1 = FactoryGirl.create(:post, :uploader => CurrentUser.user) - + assert_equal(CurrentUser.id, post1.uploader_id) - + CurrentUser.scoped(second_user, "127.0.0.2") do post2 = FactoryGirl.create(:post) post3 = FactoryGirl.create(:post) @@ -893,13 +893,13 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post1.id, relation.first.id) end - + should "return posts for the metatag" do post = FactoryGirl.create(:post, :source => "http://i1.pixiv.net/img123/img/artist-name/789.png") assert_equal(1, Post.tag_match("pixiv:789").count) assert_equal(0, Post.tag_match("pixiv:790").count) end - + should "return posts for a list of md5 hashes" do post1 = FactoryGirl.create(:post, :md5 => "abcd") post2 = FactoryGirl.create(:post) @@ -908,7 +908,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post1.id, relation.first.id) end - + should "return posts for a source search" do post1 = FactoryGirl.create(:post, :source => "abcd") post2 = FactoryGirl.create(:post, :source => "abcdefg") @@ -917,14 +917,14 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post2.id, relation.first.id) end - + should "return posts for a case sensitive source search" do post1 = FactoryGirl.create(:post, :source => "ABCD") post2 = FactoryGirl.create(:post, :source => "1234") relation = Post.tag_match("source:ABCD") assert_equal(1, relation.count) end - + should "return posts for a pixiv source search" do post = FactoryGirl.create(:post, :source => "http://i1.pixiv.net/img123/img/artist-name/789.png") assert_equal(1, Post.tag_match("source:pixiv/artist-name/*").count) @@ -932,7 +932,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, Post.tag_match("source:*.pixiv.net/img*/artist-name/*").count) assert_equal(0, Post.tag_match("source:*.pixiv.net/img*/artist-fake/*").count) end - + should "return posts for a tag subscription search" do post1 = FactoryGirl.create(:post, :tag_string => "aaa") sub = FactoryGirl.create(:tag_subscription, :tag_query => "aaa", :name => "zzz") @@ -940,7 +940,7 @@ class PostTest < ActiveSupport::TestCase relation = Post.tag_match("sub:#{CurrentUser.name}") assert_equal(1, relation.count) end - + should "return posts for a particular rating" do post1 = FactoryGirl.create(:post, :rating => "s") post2 = FactoryGirl.create(:post, :rating => "q") @@ -949,7 +949,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post3.id, relation.first.id) end - + should "return posts for a particular negated rating" do post1 = FactoryGirl.create(:post, :rating => "s") post2 = FactoryGirl.create(:post, :rating => "s") @@ -958,7 +958,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, relation.count) assert_equal(post3.id, relation.first.id) end - + should "return posts ordered by a particular attribute" do post1 = FactoryGirl.create(:post, :rating => "s") post2 = FactoryGirl.create(:post, :rating => "s") @@ -968,9 +968,9 @@ class PostTest < ActiveSupport::TestCase relation = Post.tag_match("order:mpixels") assert_equal(post3.id, relation.first.id) relation = Post.tag_match("order:landscape") - assert_equal(post3.id, relation.first.id) + assert_equal(post3.id, relation.first.id) end - + should "fail for more than 6 tags" do post1 = FactoryGirl.create(:post, :rating => "s") @@ -978,14 +978,14 @@ class PostTest < ActiveSupport::TestCase Post.tag_match("a b c rating:s width:10 height:10 user:bob") end end - + should "succeed for exclusive tag searches with no other tag" do post1 = FactoryGirl.create(:post, :rating => "s", :tag_string => "aaa") assert_nothing_raised do relation = Post.tag_match("-aaa") end end - + should "succeed for exclusive tag searches combined with a metatag" do post1 = FactoryGirl.create(:post, :rating => "s", :tag_string => "aaa") assert_nothing_raised do @@ -1023,7 +1023,7 @@ class PostTest < ActiveSupport::TestCase FactoryGirl.create(:tag_alias, :antecedent_name => "alias", :consequent_name => "aaa") FactoryGirl.create(:post, :tag_string => "aaa") end - + should "be counted correctly in fast_count" do assert_equal(1, Post.count) assert_equal(Danbooru.config.blank_tag_search_fast_count, Post.fast_count("")) @@ -1032,7 +1032,7 @@ class PostTest < ActiveSupport::TestCase assert_equal(0, Post.fast_count("bbb")) end end - + should "increment the post count" do assert_equal(0, Post.fast_count("")) post = FactoryGirl.create(:post, :tag_string => "aaa bbb") @@ -1040,10 +1040,10 @@ class PostTest < ActiveSupport::TestCase assert_equal(1, Post.fast_count("aaa")) assert_equal(1, Post.fast_count("bbb")) assert_equal(0, Post.fast_count("ccc")) - + post.tag_string = "ccc" post.save - + assert_equal(1, Post.fast_count("")) assert_equal(0, Post.fast_count("aaa")) assert_equal(0, Post.fast_count("bbb")) @@ -1060,24 +1060,24 @@ class PostTest < ActiveSupport::TestCase @post.update_attributes(:tag_string => "bbb xxx yyy", :source => "xyz") @post.update_attributes(:tag_string => "bbb mmm yyy", :source => "abc") end - + context "and then reverted to an early version" do setup do @post.revert_to(@post.versions[1]) end - + should "correctly revert all fields" do assert_equal("aaa bbb ccc ddd", @post.tag_string) assert_equal(nil, @post.source) assert_equal("q", @post.rating) end end - + context "and then reverted to a later version" do setup do @post.revert_to(@post.versions[-2]) end - + should "correctly revert all fields" do assert_equal("bbb xxx yyy", @post.tag_string) assert_equal("xyz", @post.source) diff --git a/test/unit/post_version_test.rb b/test/unit/post_version_test.rb index a1b867237..36efbfc61 100644 --- a/test/unit/post_version_test.rb +++ b/test/unit/post_version_test.rb @@ -8,29 +8,29 @@ class PostVersionTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "that has multiple versions: " do setup do @post = FactoryGirl.create(:post, :tag_string => "1") @post.update_attributes(:tag_string => "1 2") @post.update_attributes(:tag_string => "2 3") end - + context "a version record" do setup do @version = PostVersion.last end - + should "know its previous version" do assert_not_nil(@version.previous) assert_equal("1 2", @version.previous.tags) end - + should "know the seuqence of all versions for the post" do assert_equal(2, @version.sequence_for_post.size) assert_equal(%w(3), @version.sequence_for_post[0][:added_tags]) @@ -38,13 +38,13 @@ class PostVersionTest < ActiveSupport::TestCase end end end - + context "that has been created" do setup do @parent = FactoryGirl.create(:post) @post = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc", :rating => "e", :parent => @parent, :source => "xyz") end - + should "also create a version" do assert_equal(1, @post.versions.size) @version = @post.versions.last @@ -54,14 +54,14 @@ class PostVersionTest < ActiveSupport::TestCase assert_equal(@post.source, @version.source) end end - + context "that has been updated" do setup do @parent = FactoryGirl.create(:post) @post = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc", :rating => "q", :source => "xyz") @post.update_attributes(:tag_string => "bbb ccc xxx", :source => "") end - + should "also create a version" do assert_equal(2, @post.versions.size) @version = @post.versions.last diff --git a/test/unit/post_vote_test.rb b/test/unit/post_vote_test.rb index a2989ac1d..33e874fbf 100644 --- a/test/unit/post_vote_test.rb +++ b/test/unit/post_vote_test.rb @@ -6,21 +6,21 @@ class PostVoteTest < ActiveSupport::TestCase CurrentUser.user = user CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all - + @post = FactoryGirl.create(:post) end - + context "Voting for a post" do should "interpret up as +1 score" do vote = PostVote.create(:post_id => @post.id, :score => "up") assert_equal(1, vote.score) end - + should "interpret down as -1 score" do vote = PostVote.create(:post_id => @post.id, :score => "down") assert_equal(-1, vote.score) end - + should "not accept any other scores" do vote = PostVote.create(:post_id => @post.id, :score => "xxx") assert(vote.errors.any?) diff --git a/test/unit/related_tag_calculator_test.rb b/test/unit/related_tag_calculator_test.rb index 9d80f06be..8d1ba32d7 100644 --- a/test/unit/related_tag_calculator_test.rb +++ b/test/unit/related_tag_calculator_test.rb @@ -7,28 +7,28 @@ class RelatedTagCalculatorTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "A related tag calculator" do should "calculate related tags for a tag" do posts = [] posts << FactoryGirl.create(:post, :tag_string => "aaa bbb ccc ddd") posts << FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") posts << FactoryGirl.create(:post, :tag_string => "aaa bbb") - + assert_equal({"aaa" => 3, "bbb" => 3, "ccc" => 2, "ddd" => 1}, RelatedTagCalculator.calculate_from_sample("aaa", 10)) end - + should "calculate related tags for multiple tag" do posts = [] posts << FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") posts << FactoryGirl.create(:post, :tag_string => "aaa bbb ccc ddd") posts << FactoryGirl.create(:post, :tag_string => "aaa eee fff") - + assert_equal({"aaa"=>2, "bbb"=>2, "ddd"=>1, "ccc"=>2}, RelatedTagCalculator.calculate_from_sample("aaa bbb", 10)) end @@ -37,17 +37,17 @@ class RelatedTagCalculatorTest < ActiveSupport::TestCase posts << FactoryGirl.create(:post, :tag_string => "aaa bbb art:ccc copy:ddd") posts << FactoryGirl.create(:post, :tag_string => "aaa bbb art:ccc") posts << FactoryGirl.create(:post, :tag_string => "aaa bbb") - + assert_equal({"ccc" => 2}, RelatedTagCalculator.calculate_from_sample("aaa", 10, Tag.categories.artist)) assert_equal({"ddd" => 1}, RelatedTagCalculator.calculate_from_sample("aaa", 10, Tag.categories.copyright)) end - + should "convert a hash into string format" do posts = [] posts << FactoryGirl.create(:post, :tag_string => "aaa bbb ccc ddd") posts << FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") posts << FactoryGirl.create(:post, :tag_string => "aaa bbb") - + tag = Tag.find_by_name("aaa") counts = RelatedTagCalculator.calculate_from_sample("aaa", 10) assert_equal("aaa 3 bbb 3 ccc 2 ddd 1", RelatedTagCalculator.convert_hash_to_string(counts)) diff --git a/test/unit/related_tag_query_test.rb b/test/unit/related_tag_query_test.rb index d286112b7..d8c57b0d3 100644 --- a/test/unit/related_tag_query_test.rb +++ b/test/unit/related_tag_query_test.rb @@ -8,7 +8,7 @@ class RelatedTagQueryTest < ActiveSupport::TestCase MEMCACHE.flush_all Delayed::Worker.delay_jobs = false end - + context "a related tag query without a category constraint" do setup do @post_1 = FactoryGirl.create(:post, :tag_string => "aaa bbb") @@ -20,48 +20,48 @@ class RelatedTagQueryTest < ActiveSupport::TestCase Tag.named("aaa").first.update_related @query = RelatedTagQuery.new("aaa", "") end - + should "work" do assert_equal(["aaa", "bbb", "ccc"], @query.tags) end - + should "render the json" do assert_equal("{\"query\":\"aaa\",\"category\":\"\",\"tags\":[[\"aaa\",0],[\"bbb\",0],[\"ccc\",0]],\"wiki_page_tags\":[]}", @query.to_json) end end - + context "for a tag that doesn't exist" do setup do @query = RelatedTagQuery.new("zzz", "") end - + should "work" do assert_equal([], @query.tags) end end - + context "for a pattern search" do setup do @query = RelatedTagQuery.new("a*", "") end - + should "work" do assert_equal(["aaa"], @query.tags) end end - + context "for a tag with a wiki page" do setup do @wiki_page = FactoryGirl.create(:wiki_page, :title => "aaa", :body => "[[bbb]] [[ccc]]") @query = RelatedTagQuery.new("aaa", "") end - + should "find any tags embedded in the wiki page" do assert_equal(["bbb", "ccc"], @query.wiki_page_tags) end end end - + context "a related tag query with a category constraint" do setup do @post_1 = FactoryGirl.create(:post, :tag_string => "aaa bbb") @@ -69,7 +69,7 @@ class RelatedTagQueryTest < ActiveSupport::TestCase @post_3 = FactoryGirl.create(:post, :tag_string => "aaa copy:ddd") @query = RelatedTagQuery.new("aaa", "artist") end - + should "find the related tags" do assert_equal(%w(ccc), @query.tags) end diff --git a/test/unit/sources/nico_seiga_test.rb b/test/unit/sources/nico_seiga_test.rb index 2d83f1ce4..e8cc077ed 100644 --- a/test/unit/sources/nico_seiga_test.rb +++ b/test/unit/sources/nico_seiga_test.rb @@ -10,19 +10,19 @@ module Sources @site = Sources::Site.new("http://seiga.nicovideo.jp/seiga/im1464351?track=ranking") @site.get end - + should "get the profile" do assert_equal("http://seiga.nicovideo.jp/user/illust/20446930?target=seiga", @site.profile_url) end - + should "get the artist name" do assert_equal("rariemonn", @site.artist_name) end - + should "get the image url" do assert_equal("http://seiga.nicovideo.jp/image/source?id=1464351", @site.image_url) end - + should "get the tags" do assert(@site.tags.size > 0) first_tag = @site.tags.first diff --git a/test/unit/sources/pixa_test.rb b/test/unit/sources/pixa_test.rb index e9daa280a..25bc97e86 100644 --- a/test/unit/sources/pixa_test.rb +++ b/test/unit/sources/pixa_test.rb @@ -1,7 +1,7 @@ # # encoding: UTF-8 -# +# # require 'test_helper' -# +# # module Sources # class PixaTest < ActiveSupport::TestCase # context "The source site for pixa" do @@ -9,26 +9,26 @@ # @site = Sources::Site.new("http://www.pixa.cc/illustrations/show/75575") # @site.get # end -# +# # should "get the profile" do # assert_equal("http://www.pixa.cc/profiles/show/9191", @site.profile_url) # end -# +# # should "get the artist name" do # assert_equal("air", @site.artist_name) # end -# +# # should "get the image url" do # assert_equal("http://file0.pixa.cc/illustrations/34/cb/df/70/49/b4/52/2d/42/c6/middle/110910魔法少女のコピー.jpg?1315664621", @site.image_url) # end -# +# # should "get the tags" do # assert(@site.tags.size > 0) # first_tag = @site.tags.first # assert_equal(2, first_tag.size) # assert(first_tag[0] =~ /./) # end -# +# # should "convert a page into a json representation" do # assert_nothing_raised do # @site.to_json diff --git a/test/unit/sources/pixiv_test.rb b/test/unit/sources/pixiv_test.rb index 7a67886e2..35c8a2599 100644 --- a/test/unit/sources/pixiv_test.rb +++ b/test/unit/sources/pixiv_test.rb @@ -9,19 +9,19 @@ module Sources @site = Sources::Site.new("http://www.pixiv.net/member_illust.php?mode=big&illust_id=9646484") @site.get end - + should "get the profile" do assert_equal("http://www.pixiv.net/member.php?id=4015", @site.profile_url) end - + should "get the artist name" do assert_equal("シビレ罠", @site.artist_name) end - + should "get the image url" do assert_equal("http://i1.pixiv.net/img01/img/nisieda/9646484.jpg", @site.image_url) end - + should "get the tags" do assert(@site.tags.size > 0) first_tag = @site.tags.first @@ -29,7 +29,7 @@ module Sources assert(first_tag[0] =~ /./) assert(first_tag[1] =~ /search\.php/) end - + should "convert a page into a json representation" do assert_nothing_raised do @site.to_json diff --git a/test/unit/sources/tinami_test.rb b/test/unit/sources/tinami_test.rb index 62234c832..6b422d926 100644 --- a/test/unit/sources/tinami_test.rb +++ b/test/unit/sources/tinami_test.rb @@ -1,7 +1,7 @@ # # encoding: UTF-8 -# +# # require 'test_helper' -# +# # module Sources # class TinamiTest < ActiveSupport::TestCase # context "The source site for tinami" do @@ -10,23 +10,23 @@ # @site = Sources::Site.new("http://www.tinami.com/view/308311") # @site.get # end -# +# # should "get the profile" do # assert_equal("http://www.tinami.com/creator/profile/29399", @site.profile_url) # end -# +# # should "get the artist name" do # assert_match(/ROM/, @site.artist_name) # end -# +# # should "get the image url" do # assert_equal("http://img.tinami.com/illust2/img/336/4e80b9773c084.png", @site.image_url) # end -# +# # should "get the tags" do # assert(@site.tags.size > 0) # end -# +# # should "convert a page into a json representation" do # assert_nothing_raised do # @site.to_json diff --git a/test/unit/tag_alias_correction_test.rb b/test/unit/tag_alias_correction_test.rb index d2dbc206d..6897b7b4b 100644 --- a/test/unit/tag_alias_correction_test.rb +++ b/test/unit/tag_alias_correction_test.rb @@ -17,41 +17,41 @@ class TagAliasCorrectionTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "with a bad cache and post counts" do setup do Cache.put("ta:aaa", "zzz") Tag.update_all("post_count = -3", "name = 'aaa'") @correction = TagAliasCorrection.new(@tag_alias.id) end - + should "have the correct statistics hash" do assert_equal("zzz", @correction.statistics_hash["antecedent_cache"]) assert_equal("bbb", @correction.statistics_hash["consequent_cache"]) assert_equal(-3, @correction.statistics_hash["antecedent_count"]) assert_equal(1, @correction.statistics_hash["consequent_count"]) end - + should "render to json" do assert_nothing_raised do @correction.to_json end - + assert_nothing_raised do JSON.parse(@correction.to_json) end end - + context "that is fixed" do setup do @correction.fix! TagAlias.to_aliased(["aaa"]) end - + should "now have the correct cache" do assert_equal("bbb", Cache.get("ta:aaa")) end - + should "now have the correct count" do assert_equal(0, Tag.find_by_name("aaa").post_count) end diff --git a/test/unit/tag_alias_request_test.rb b/test/unit/tag_alias_request_test.rb index 452ddb8b0..41171312e 100644 --- a/test/unit/tag_alias_request_test.rb +++ b/test/unit/tag_alias_request_test.rb @@ -15,13 +15,13 @@ class TagAliasRequestTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "raise an exception if invalid" do assert_raises(TagAliasRequest::ValidationError) do TagAliasRequest.new("", "", "reason").create end end - + should "create a tag alias" do assert_difference("TagAlias.count", 1) do TagAliasRequest.new("aaa", "bbb", "reason").create diff --git a/test/unit/tag_alias_test.rb b/test/unit/tag_alias_test.rb index e4479d940..aab84adad 100644 --- a/test/unit/tag_alias_test.rb +++ b/test/unit/tag_alias_test.rb @@ -14,12 +14,12 @@ class TagAliasTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "populate the creator information" do ta = FactoryGirl.create(:tag_alias, :antecedent_name => "aaa", :consequent_name => "bbb") assert_equal(CurrentUser.user.id, ta.creator_id) end - + should "convert a tag to its normalized version" do tag1 = FactoryGirl.create(:tag, :name => "aaa") tag2 = FactoryGirl.create(:tag, :name => "bbb") @@ -27,7 +27,7 @@ class TagAliasTest < ActiveSupport::TestCase normalized_tags = TagAlias.to_aliased(["aaa", "ccc"]) assert_equal(["bbb", "ccc"], normalized_tags.sort) end - + should "update the cache" do tag1 = FactoryGirl.create(:tag, :name => "aaa") tag2 = FactoryGirl.create(:tag, :name => "bbb") @@ -38,7 +38,7 @@ class TagAliasTest < ActiveSupport::TestCase ta.destroy assert_nil(Cache.get("ta:aaa")) end - + should "update any affected posts when saved" do assert_equal(0, TagAlias.count) post1 = FactoryGirl.create(:post, :tag_string => "aaa bbb") @@ -51,7 +51,7 @@ class TagAliasTest < ActiveSupport::TestCase assert_equal("bbb ccc", post1.tag_string) assert_equal("ccc ddd", post2.tag_string) end - + should "not validate for transitive relations" do ta1 = FactoryGirl.create(:tag_alias, :antecedent_name => "aaa", :consequent_name => "bbb") assert_difference("TagAlias.count", 0) do @@ -61,7 +61,7 @@ class TagAliasTest < ActiveSupport::TestCase assert_equal("Tag alias can not create a transitive relation with another tag alias", ta3.errors.full_messages.join) end end - + should "record the alias's creator in the tag history" do uploader = FactoryGirl.create(:user) post = nil @@ -73,7 +73,7 @@ class TagAliasTest < ActiveSupport::TestCase assert_not_equal(tag_alias.creator_id, post.uploader_id) assert_equal(tag_alias.creator_id, post.versions.last.updater_id) end - + should "push the antecedent's category to the consequent" do tag1 = FactoryGirl.create(:tag, :name => "aaa", :category => 1) tag2 = FactoryGirl.create(:tag, :name => "bbb") diff --git a/test/unit/tag_implication_request_test.rb b/test/unit/tag_implication_request_test.rb index f53f50633..37eb8e3eb 100644 --- a/test/unit/tag_implication_request_test.rb +++ b/test/unit/tag_implication_request_test.rb @@ -15,13 +15,13 @@ class TagImplicationRequestTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "raise an exception if invalid" do assert_raises(TagImplicationRequest::ValidationError) do TagImplicationRequest.new("", "", "reason").create end end - + should "create a tag implication" do assert_difference("TagImplication.count", 1) do TagImplicationRequest.new("aaa", "bbb", "reason").create diff --git a/test/unit/tag_implication_test.rb b/test/unit/tag_implication_test.rb index b6d2b81b9..a21929b9b 100644 --- a/test/unit/tag_implication_test.rb +++ b/test/unit/tag_implication_test.rb @@ -14,12 +14,12 @@ class TagImplicationTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "populate the creator information" do ti = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb") assert_equal(CurrentUser.user.id, ti.creator_id) end - + should "not validate when a circular relation is created" do ti1 = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb") ti2 = FactoryGirl.build(:tag_implication, :antecedent_name => "bbb", :consequent_name => "aaa") @@ -27,7 +27,7 @@ class TagImplicationTest < ActiveSupport::TestCase assert(ti2.errors.any?, "Tag implication should not have validated.") assert_equal("Tag implication can not create a circular relation with another tag implication", ti2.errors.full_messages.join("")) end - + should "not allow for duplicates" do ti1 = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb") ti2 = FactoryGirl.build(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb") @@ -35,11 +35,11 @@ class TagImplicationTest < ActiveSupport::TestCase assert(ti2.errors.any?, "Tag implication should not have validated.") assert_equal("Antecedent name has already been taken", ti2.errors.full_messages.join("")) end - + should "calculate all its descendants" do ti1 = FactoryGirl.create(:tag_implication, :antecedent_name => "bbb", :consequent_name => "ccc") assert_equal("ccc", ti1.descendant_names) - assert_equal(["ccc"], ti1.descendant_names_array) + assert_equal(["ccc"], ti1.descendant_names_array) ti2 = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb") assert_equal("bbb ccc", ti2.descendant_names) assert_equal(["bbb", "ccc"], ti2.descendant_names_array) @@ -47,7 +47,7 @@ class TagImplicationTest < ActiveSupport::TestCase assert_equal("ccc", ti1.descendant_names) assert_equal(["ccc"], ti1.descendant_names_array) end - + should "update its descendants on save" do ti1 = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb") ti2 = FactoryGirl.create(:tag_implication, :antecedent_name => "ccc", :consequent_name => "ddd") @@ -59,7 +59,7 @@ class TagImplicationTest < ActiveSupport::TestCase assert_equal("bbb ddd", ti1.descendant_names) assert_equal("ddd", ti2.descendant_names) end - + should "update the decendants for its parent on create" do ti1 = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "bbb") ti1.reload @@ -92,7 +92,7 @@ class TagImplicationTest < ActiveSupport::TestCase assert_equal("eee", ti4.descendant_names) end - + should "update any affected post upon save" do p1 = FactoryGirl.create(:post, :tag_string => "aaa bbb ccc") ti1 = FactoryGirl.create(:tag_implication, :antecedent_name => "aaa", :consequent_name => "xxx") @@ -100,7 +100,7 @@ class TagImplicationTest < ActiveSupport::TestCase p1.reload assert_equal("aaa bbb ccc xxx yyy", p1.tag_string) end - + should "record the implication's creator in the tag history" do user = FactoryGirl.create(:user) p1 = nil diff --git a/test/unit/tag_subscription_test.rb b/test/unit/tag_subscription_test.rb index 0c7131020..9c8b6a0de 100644 --- a/test/unit/tag_subscription_test.rb +++ b/test/unit/tag_subscription_test.rb @@ -7,26 +7,26 @@ class TagSubscriptionTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "A tag subscription" do context "for a user with too many subscriptions" do setup do Danbooru.config.stubs(:max_tag_subscriptions).returns(0) @user = FactoryGirl.create(:user) end - + should "fail" do sub = FactoryGirl.build(:tag_subscription, :tag_query => "aaa bbb", :creator => @user, :name => "zzz") sub.save assert_equal(["You can create up to 0 tag subscriptions"], sub.errors.full_messages) end end - + should "find the union of all posts for each tag in its tag query" do posts = [] user = FactoryGirl.create(:user) @@ -41,7 +41,7 @@ class TagSubscriptionTest < ActiveSupport::TestCase assert_equal([posts[2].id, posts[1].id, posts[0].id], TagSubscription.find_posts(user.id).map(&:id)) end end - + should "cache its tag query results" do posts = [] user = FactoryGirl.create(:user) @@ -53,7 +53,7 @@ class TagSubscriptionTest < ActiveSupport::TestCase assert_equal("#{posts[1].id},#{posts[0].id}", sub.post_ids) end end - + should "find posts based on its cached post ids" do user = FactoryGirl.create(:user) CurrentUser.scoped(user, "127.0.0.1") do diff --git a/test/unit/tag_test.rb b/test/unit/tag_test.rb index 6cdd21a5c..845457225 100644 --- a/test/unit/tag_test.rb +++ b/test/unit/tag_test.rb @@ -8,17 +8,17 @@ class TagTest < ActiveSupport::TestCase MEMCACHE.flush_all Delayed::Worker.delay_jobs = false end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "A tag category fetcher" do setup do MEMCACHE.flush_all end - + should "fetch for a single tag" do FactoryGirl.create(:artist_tag, :name => "test") assert_equal(Tag.categories.artist, Tag.category_for("test")) @@ -28,7 +28,7 @@ class TagTest < ActiveSupport::TestCase FactoryGirl.create(:artist_tag, :name => "!@$%") assert_equal(Tag.categories.artist, Tag.category_for("!@$%")) end - + should "fetch for multiple tags" do FactoryGirl.create(:artist_tag, :name => "aaa") FactoryGirl.create(:copyright_tag, :name => "bbb") @@ -38,26 +38,26 @@ class TagTest < ActiveSupport::TestCase assert_equal(0, categories["ccc"]) end end - + context "A tag category mapping" do setup do MEMCACHE.flush_all end - + should "exist" do assert_nothing_raised {Tag.categories} end - + should "have convenience methods for the four main categories" do assert_equal(0, Tag.categories.general) assert_equal(1, Tag.categories.artist) assert_equal(3, Tag.categories.copyright) assert_equal(4, Tag.categories.character) end - + should "have a regular expression for matching category names and shortcuts" do regexp = Tag.categories.regexp - + assert_match(regexp, "artist") assert_match(regexp, "art") assert_match(regexp, "copyright") @@ -69,16 +69,16 @@ class TagTest < ActiveSupport::TestCase assert_no_match(regexp, "c") assert_no_match(regexp, "woodle") end - + should "map a category name to its value" do assert_equal(0, Tag.categories.value_for("general")) assert_equal(0, Tag.categories.value_for("gen")) assert_equal(1, Tag.categories.value_for("artist")) assert_equal(1, Tag.categories.value_for("art")) - assert_equal(0, Tag.categories.value_for("unknown")) + assert_equal(0, Tag.categories.value_for("unknown")) end end - + context "A tag" do setup do MEMCACHE.flush_all @@ -88,29 +88,29 @@ class TagTest < ActiveSupport::TestCase @tag = FactoryGirl.create(:artist_tag) assert_equal("Artist", @tag.category_name) end - + should "reset its category after updating" do tag = FactoryGirl.create(:artist_tag) tag.update_category_cache_for_all assert_equal(Tag.categories.artist, MEMCACHE.get("tc:#{tag.name}")) - + tag.update_attribute(:category, Tag.categories.copyright) tag.update_category_cache_for_all assert_equal(Tag.categories.copyright, MEMCACHE.get("tc:#{tag.name}")) end end - + context "A tag parser" do should "scan a query" do assert_equal(%w(aaa bbb), Tag.scan_query("aaa bbb")) assert_equal(%w(~AAa -BBB* -bbb*), Tag.scan_query("~AAa -BBB* -bbb*")) end - + should "strip out invalid characters when scanning" do assert_equal(%w(aaa bbb), Tag.scan_tags("aaa bbb")) assert_equal(%w(-BB;B* -b_b_b_), Tag.scan_tags("-B,B;B* -b_b_b_")) end - + should "cast values" do assert_equal(2048, Tag.parse_cast("2kb", :filesize)) assert_equal(2097152, Tag.parse_cast("2m", :filesize)) @@ -118,7 +118,7 @@ class TagTest < ActiveSupport::TestCase assert_nothing_raised {Tag.parse_cast("1234", :integer)} assert_nothing_raised {Tag.parse_cast("1234.56", :float)} end - + should "parse a query" do tag1 = FactoryGirl.create(:tag, :name => "abc") tag2 = FactoryGirl.create(:tag, :name => "acb") @@ -134,7 +134,7 @@ class TagTest < ActiveSupport::TestCase assert_equal(["acb"], Tag.parse_query("a*b")[:tags][:include]) end end - + context "A tag" do should "be found when one exists" do tag = FactoryGirl.create(:tag) @@ -142,7 +142,7 @@ class TagTest < ActiveSupport::TestCase Tag.find_or_create_by_name(tag.name) end end - + should "change the type for an existing tag" do tag = FactoryGirl.create(:tag) assert_difference("Tag.count", 0) do @@ -152,7 +152,7 @@ class TagTest < ActiveSupport::TestCase assert_equal(Tag.categories.artist, tag.category) end end - + should "be created when one doesn't exist" do assert_difference("Tag.count", 1) do tag = Tag.find_or_create_by_name("hoge") @@ -160,7 +160,7 @@ class TagTest < ActiveSupport::TestCase assert_equal(Tag.categories.general, tag.category) end end - + should "be created with the type when one doesn't exist" do assert_difference("Tag.count", 1) do tag = Tag.find_or_create_by_name("artist:hoge") diff --git a/test/unit/upload_test.rb b/test/unit/upload_test.rb index d5e3079c9..f08c45ab5 100644 --- a/test/unit/upload_test.rb +++ b/test/unit/upload_test.rb @@ -18,11 +18,11 @@ class UploadTest < ActiveSupport::TestCase @upload.delete_temp_file if @upload end - context "An upload" do + context "An upload" do teardown do FileUtils.rm_f(Dir.glob("#{Rails.root}/tmp/test.*")) end - + context "that has incredibly absurd res dimensions" do setup do @upload = FactoryGirl.build(:jpg_upload, :tag_string => "") @@ -30,19 +30,19 @@ class UploadTest < ActiveSupport::TestCase @upload.image_height = 10 @upload.add_dimension_tags! end - + should "have the incredibly_absurdres tag" do assert_match(/incredibly_absurdres/, @upload.tag_string) end end - + context "that has a large flie size" do setup do @upload = FactoryGirl.build(:jpg_upload, :tag_string => "") @upload.file_size = 11.megabytes @upload.add_file_size_tags!(@upload.file_path) end - + should "have the huge_filesize tag" do assert_match(/huge_filesize/, @upload.tag_string) end @@ -131,7 +131,7 @@ class UploadTest < ActiveSupport::TestCase assert_equal(28086, File.size(@upload.file_path)) assert_equal("jpg", @upload.file_ext) end - + should "process a transparent png" do FileUtils.cp("#{Rails.root}/test/files/alpha.png", "#{Rails.root}/tmp") @upload = Upload.new(:file => upload_file("#{Rails.root}/tmp/alpha.png", "image/png", "alpha.png")) @@ -169,7 +169,7 @@ class UploadTest < ActiveSupport::TestCase assert_equal(108224, File.size(@upload.resized_file_path_for(Danbooru.config.large_image_width))) end end - + should "increment the uploaders post_upload_count" do @upload = FactoryGirl.create(:source_upload) assert_difference("CurrentUser.post_upload_count", 1) do @@ -225,7 +225,7 @@ class UploadTest < ActiveSupport::TestCase assert(File.exists?(post.file_path)) assert_equal(28086, File.size(post.file_path)) assert_equal(post.id, @upload.post_id) - assert_equal("completed", @upload.status) + assert_equal("completed", @upload.status) end should "delete the temporary file upon completion" do diff --git a/test/unit/user_feedback_test.rb b/test/unit/user_feedback_test.rb index 087895374..72621a492 100644 --- a/test/unit/user_feedback_test.rb +++ b/test/unit/user_feedback_test.rb @@ -11,27 +11,27 @@ class UserFeedbackTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + should "create a dmail" do user = FactoryGirl.create(:user) privileged = FactoryGirl.create(:privileged_user) member = FactoryGirl.create(:user) - + CurrentUser.user = privileged assert_difference("Dmail.count", 2) do FactoryGirl.create(:user_feedback, :user => user) end end - + should "should not validate if the creator is not privileged" do user = FactoryGirl.create(:user) privileged = FactoryGirl.create(:privileged_user) member = FactoryGirl.create(:user) - + CurrentUser.user = privileged feedback = FactoryGirl.create(:user_feedback, :user => user) assert(feedback.errors.empty?) - + CurrentUser.user = member feedback = FactoryGirl.build(:user_feedback, :user => user) feedback.save diff --git a/test/unit/user_password_reset_nonce_test.rb b/test/unit/user_password_reset_nonce_test.rb index 45372a8e4..2c49751e6 100644 --- a/test/unit/user_password_reset_nonce_test.rb +++ b/test/unit/user_password_reset_nonce_test.rb @@ -7,11 +7,11 @@ class UserPasswordResetNonceTest < ActiveSupport::TestCase @user = FactoryGirl.create(:user, :email => "aaa@b.net") @nonce = FactoryGirl.create(:user_password_reset_nonce, :email => @user.email) end - + should "validate" do assert_equal([], @nonce.errors.full_messages) end - + should "populate the key with a random string" do assert_equal(32, @nonce.key.size) end @@ -21,24 +21,24 @@ class UserPasswordResetNonceTest < ActiveSupport::TestCase @nonce.reset_user! end end - + context "with a blank email" do setup do @user = FactoryGirl.create(:user, :email => "") @nonce = UserPasswordResetNonce.new(:email => "") end - + should "not validate" do @nonce.save assert_equal(["Email can't be blank", "Email is invalid"], @nonce.errors.full_messages.sort) end end - + context "with an invalid email" do setup do @nonce = UserPasswordResetNonce.new(:email => "z@z.net") end - + should "not validate" do @nonce.save assert_equal(["Email is invalid"], @nonce.errors.full_messages) diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 2d88c6d65..886a738d1 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -13,24 +13,24 @@ class UserTest < ActiveSupport::TestCase CurrentUser.user = nil CurrentUser.ip_addr = nil end - + context "that has been invited by a mod" do setup do @mod = FactoryGirl.create(:moderator_user) end - + should "work" do @user.invite!(User::Levels::CONTRIBUTOR) @user.reload assert_equal(User::Levels::CONTRIBUTOR, @user.level) end - + should "not allow invites up to janitor level or beyond" do @user.invite!(User::Levels::JANITOR) @user.reload assert_equal(User::Levels::MEMBER, @user.level) end - + should "create a mod action" do assert_difference("ModAction.count") do @user.invite!(User::Levels::CONTRIBUTOR) @@ -38,16 +38,16 @@ class UserTest < ActiveSupport::TestCase assert_equal("#{@user.name} level changed Member -> Contributor by #{CurrentUser.name}", ModAction.last.description) end end - + context "who has negeative feedback and is trying to change their name" do setup do @mod = FactoryGirl.create(:moderator_user) - + CurrentUser.scoped(@mod, "127.0.0.1") do FactoryGirl.create(:user_feedback, :user => @user, :category => "negative") end end - + should "not validate" do @user.reload @user.update_attributes(:name => "fanfarlo") @@ -62,20 +62,20 @@ class UserTest < ActiveSupport::TestCase assert(user.errors.any?) assert_equal("IP address is banned", user.errors.full_messages.join) end - + should "limit post uploads" do assert(!@user.can_upload?) @user.update_column(:level, User::Levels::CONTRIBUTOR) assert(@user.can_upload?) @user.update_column(:level, User::Levels::MEMBER) - + 40.times do FactoryGirl.create(:post, :uploader => @user, :is_deleted => true) end - + assert(!@user.can_upload?) end - + should "limit comment votes" do Danbooru.config.stubs(:member_comment_time_threshold).returns(1.week.from_now) Danbooru.config.stubs(:member_comment_limit).returns(10) @@ -84,12 +84,12 @@ class UserTest < ActiveSupport::TestCase comment = FactoryGirl.create(:comment) FactoryGirl.create(:comment_vote, :comment_id => comment.id) end - + assert(!@user.can_comment_vote?) CommentVote.update_all("created_at = '1990-01-01'") assert(@user.can_comment_vote?) end - + should "limit comments" do assert(!@user.can_comment?) @user.update_column(:level, User::Levels::PRIVILEGED) @@ -102,7 +102,7 @@ class UserTest < ActiveSupport::TestCase end assert(!@user.can_comment?) end - + should "verify" do assert(@user.is_verified?) @user = FactoryGirl.create(:user) @@ -113,92 +113,92 @@ class UserTest < ActiveSupport::TestCase assert_nothing_raised {@user.verify!(@user.email_verification_key)} assert(@user.is_verified?) end - + should "authenticate" do assert(User.authenticate(@user.name, "password"), "Authentication should have succeeded") assert(!User.authenticate(@user.name, "password2"), "Authentication should not have succeeded") assert(User.authenticate_hash(@user.name, User.sha1("password")), "Authentication should have succeeded") assert(!User.authenticate_hash(@user.name, User.sha1("xxx")), "Authentication should not have succeeded") end - + should "normalize its level" do user = FactoryGirl.create(:user, :level => User::Levels::ADMIN) assert(user.is_moderator?) assert(user.is_janitor?) assert(user.is_contributor?) assert(user.is_privileged?) - + user = FactoryGirl.create(:user, :level => User::Levels::MODERATOR) assert(!user.is_admin?) assert(user.is_moderator?) assert(user.is_janitor?) assert(user.is_contributor?) assert(user.is_privileged?) - + user = FactoryGirl.create(:user, :level => User::Levels::JANITOR) assert(!user.is_admin?) assert(!user.is_moderator?) assert(user.is_janitor?) assert(user.is_contributor?) assert(user.is_privileged?) - + user = FactoryGirl.create(:user, :level => User::Levels::CONTRIBUTOR) assert(!user.is_admin?) assert(!user.is_moderator?) assert(!user.is_janitor?) assert(user.is_contributor?) assert(user.is_privileged?) - + user = FactoryGirl.create(:user, :level => User::Levels::PRIVILEGED) assert(!user.is_admin?) assert(!user.is_moderator?) assert(!user.is_janitor?) assert(!user.is_contributor?) assert(user.is_privileged?) - - user = FactoryGirl.create(:user) + + user = FactoryGirl.create(:user) assert(!user.is_admin?) assert(!user.is_moderator?) assert(!user.is_janitor?) assert(!user.is_contributor?) assert(!user.is_privileged?) end - + context "name" do should "be #{Danbooru.config.default_guest_name} given an invalid user id" do assert_equal(Danbooru.config.default_guest_name, User.id_to_name(-1)) end - + should "be fetched given a user id" do @user = FactoryGirl.create(:user) assert_equal(@user.name, User.id_to_name(@user.id)) end - + should "be updated" do @user = FactoryGirl.create(:user) @user.update_attribute(:name, "danzig") assert_equal(@user.name, User.id_to_name(@user.id)) end end - + context "ip address" do setup do @user = FactoryGirl.create(:user) end - + context "in the json representation" do should "not appear" do assert(@user.to_json !~ /addr/) end end - + context "in the xml representation" do should "not appear" do assert(@user.to_xml !~ /addr/) end end end - + context "password" do should "match the cookie hash" do @user = FactoryGirl.create(:user) @@ -208,7 +208,7 @@ class UserTest < ActiveSupport::TestCase @user.reload assert(User.authenticate_cookie_hash(@user.name, @user.bcrypt_cookie_password_hash)) end - + should "match the confirmation" do @user = FactoryGirl.create(:user) @user.password = "zugzug5" @@ -217,7 +217,7 @@ class UserTest < ActiveSupport::TestCase @user.reload assert(User.authenticate(@user.name, "zugzug5"), "Authentication should have succeeded") end - + should "match the confirmation" do @user = FactoryGirl.create(:user) @user.password = "zugzug6" @@ -225,7 +225,7 @@ class UserTest < ActiveSupport::TestCase @user.save assert_equal(["Password doesn't match confirmation"], @user.errors.full_messages) end - + should "not be too short" do @user = FactoryGirl.create(:user) @user.password = "x5" @@ -233,52 +233,52 @@ class UserTest < ActiveSupport::TestCase @user.save assert_equal(["Password is too short (minimum is 5 characters)"], @user.errors.full_messages) end - + should "should be reset" do @user = FactoryGirl.create(:user) new_pass = @user.reset_password assert(User.authenticate(@user.name, new_pass), "Authentication should have succeeded") end - + should "not change the password if the password and old password are blank" do @user = FactoryGirl.create(:user, :password => "67890") @user.update_attributes(:password => "", :old_password => "") assert(@user.bcrypt_password == User.sha1("67890")) end - + should "not change the password if the old password is incorrect" do @user = FactoryGirl.create(:user, :password => "67890") @user.update_attributes(:password => "12345", :old_password => "abcdefg") assert(@user.bcrypt_password == User.sha1("67890")) end - + should "not change the password if the old password is blank" do @user = FactoryGirl.create(:user, :password => "67890") @user.update_attributes(:password => "12345", :old_password => "") assert(@user.bcrypt_password == User.sha1("67890")) end - + should "change the password if the old password is correct" do @user = FactoryGirl.create(:user, :password => "67890") @user.update_attributes(:password => "12345", :old_password => "67890") assert(@user.bcrypt_password == User.sha1("12345")) end - + context "in the json representation" do setup do @user = FactoryGirl.create(:user) end - + should "not appear" do assert(@user.to_json !~ /password/) end end - + context "in the xml representation" do setup do @user = FactoryGirl.create(:user) end - + should "not appear" do assert(@user.to_xml !~ /password/) end diff --git a/test/unit/wiki_page_test.rb b/test/unit/wiki_page_test.rb index 577f6c27c..f50a93caa 100644 --- a/test/unit/wiki_page_test.rb +++ b/test/unit/wiki_page_test.rb @@ -4,7 +4,7 @@ class WikiPageTest < ActiveSupport::TestCase setup do MEMCACHE.flush_all end - + teardown do CurrentUser.user = nil CurrentUser.ip_addr = nil @@ -18,14 +18,14 @@ class WikiPageTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" @wiki_page = FactoryGirl.create(:wiki_page) end - + should "allow the is_locked attribute to be updated" do @wiki_page.update_attributes(:is_locked => true) @wiki_page.reload assert_equal(true, @wiki_page.is_locked?) end end - + context "updated by a regular user" do setup do @user = FactoryGirl.create(:user) @@ -33,14 +33,14 @@ class WikiPageTest < ActiveSupport::TestCase CurrentUser.ip_addr = "127.0.0.1" @wiki_page = FactoryGirl.create(:wiki_page, :title => "HOT POTATO") end - + should "not allow the is_locked attribute to be updated" do @wiki_page.update_attributes(:is_locked => true) assert_equal(["Is locked can be modified by janitors only"], @wiki_page.errors.full_messages) @wiki_page.reload assert_equal(false, @wiki_page.is_locked?) end - + should "normalize its title" do assert_equal("hot_potato", @wiki_page.title) end @@ -78,7 +78,7 @@ class WikiPageTest < ActiveSupport::TestCase @wiki_page.save end version = WikiPageVersion.first - assert_not_equal(@wiki_page.creator_id, version.updater_id) + assert_not_equal(@wiki_page.creator_id, version.updater_id) end end end