-
Notifications
You must be signed in to change notification settings - Fork 410
/
post.rb
1850 lines (1544 loc) · 59.7 KB
/
post.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
class Post < ApplicationRecord
class RevertError < StandardError; end
class DeletionError < StandardError; end
# Tags to copy when copying notes.
NOTE_COPY_TAGS = %w[translated partially_translated check_translation translation_request reverse_translation
annotated partially_annotated check_annotation annotation_request]
RESTRICTED_TAGS_REGEX = /(?:^| )(?:#{Danbooru.config.restricted_tags.join("|")})(?:$| )/o
RATINGS = {
g: "General",
s: "Sensitive",
q: "Questionable",
e: "Explicit",
}.with_indifferent_access
RATING_ALIASES = {
safe: ["s"],
nsfw: ["q", "e"],
sfw: ["g", "s"],
}.with_indifferent_access
deletable
has_bit_flags %w[has_embedded_notes _unused_has_cropped is_taken_down]
normalize :source, :normalize_source
before_validation :merge_old_changes
before_validation :apply_pre_metatags
before_validation :normalize_tags
before_validation :blank_out_nonexistent_parents
before_validation :remove_parent_loops
validates :md5, uniqueness: { message: ->(post, _data) { "Duplicate of post ##{Post.find_by_md5(post.md5).id}" }}, on: :create
validates :rating, presence: { message: "not selected" }
validates :rating, inclusion: { in: RATINGS.keys, message: "must be #{RATINGS.keys.map(&:upcase).to_sentence(last_word_connector: ", or ")}" }, if: -> { rating.present? }
validates :source, length: { maximum: 1200 }
validate :post_is_not_its_own_parent
validate :uploader_is_not_limited, on: :create
before_save :parse_pixiv_id
before_save :added_tags_are_valid
before_save :removed_tags_are_valid
before_save :has_artist_tag
before_save :has_copyright_tag
before_save :has_enough_tags
before_save :update_tag_post_counts
before_save :update_tag_category_counts
before_create :autoban
after_save :create_version
after_save :update_parent_on_save
after_save :apply_post_metatags
after_create_commit :update_iqdb
belongs_to :approver, class_name: "User", optional: true
belongs_to :uploader, :class_name => "User", :counter_cache => "post_upload_count"
belongs_to :parent, class_name: "Post", optional: true
has_one :media_asset, -> { active }, foreign_key: :md5, primary_key: :md5
has_one :media_metadata, through: :media_asset
has_one :artist_commentary, :dependent => :destroy
has_one :vote_by_current_user, -> { active.where(user_id: CurrentUser.id) }, class_name: "PostVote" # XXX using current user here is wrong
has_many :flags, :class_name => "PostFlag", :dependent => :destroy
has_many :appeals, :class_name => "PostAppeal", :dependent => :destroy
has_many :votes, :class_name => "PostVote", :dependent => :destroy
has_many :notes, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :children, -> {order("posts.id")}, :class_name => "Post", :foreign_key => "parent_id"
has_many :approvals, :class_name => "PostApproval", :dependent => :destroy
has_many :disapprovals, :class_name => "PostDisapproval", :dependent => :destroy
has_many :favorites, dependent: :destroy
has_many :replacements, class_name: "PostReplacement", :dependent => :destroy
has_many :ai_tags, through: :media_asset
has_many :events, class_name: "PostEvent"
has_many :mod_actions, as: :subject, dependent: :destroy
attr_accessor :old_tag_string, :old_parent_id, :old_source, :old_rating, :has_constraints, :disable_versioning, :post_edit
scope :pending, -> { where(is_pending: true) }
scope :flagged, -> { where(is_flagged: true) }
scope :banned, -> { where(is_banned: true) }
# XXX conflict with deletable
scope :active, -> { where(is_pending: false, is_deleted: false, is_flagged: false).where.not(id: PostAppeal.pending) }
scope :appealed, -> { where(id: PostAppeal.pending.select(:post_id)) }
scope :in_modqueue, -> { where_union(pending, flagged, appealed) }
scope :expired, -> { pending.where("posts.created_at < ?", Danbooru.config.moderation_period.ago) }
scope :unflagged, -> { where(is_flagged: false) }
scope :has_notes, -> { where.not(last_noted_at: nil) }
scope :for_user, ->(user_id) { where(uploader_id: user_id) }
if PostVersion.enabled?
has_many :versions, -> { Rails.env.test? ? order("post_versions.updated_at ASC, post_versions.id ASC") : order("post_versions.updated_at ASC") }, class_name: "PostVersion", dependent: :destroy
end
def self.new_from_upload(upload_media_asset, tag_string: nil, rating: nil, parent_id: nil, source: nil, artist_commentary_title: nil, artist_commentary_desc: nil, translated_commentary_title: nil, translated_commentary_desc: nil, is_pending: nil, add_artist_tag: false)
upload = upload_media_asset.upload
media_asset = upload_media_asset.media_asset
# XXX depends on CurrentUser
commentary = ArtistCommentary.new(
original_title: artist_commentary_title,
original_description: artist_commentary_desc,
translated_title: translated_commentary_title,
translated_description: translated_commentary_desc,
)
if add_artist_tag
tag_string = "#{tag_string} #{upload_media_asset.source_extractor&.artists.to_a.map(&:tag).map(&:name).join(" ")}".strip
tag_string += " " if tag_string.present?
end
post = Post.new(
uploader: upload.uploader,
md5: media_asset&.md5,
file_ext: media_asset&.file_ext,
file_size: media_asset&.file_size,
image_width: media_asset&.image_width,
image_height: media_asset&.image_height,
source: source.to_s,
tag_string: tag_string,
rating: rating,
parent_id: parent_id,
is_pending: !upload.uploader.is_contributor? || is_pending.to_s.truthy?,
artist_commentary: (commentary if commentary.any_field_present?),
)
end
concerning :FileMethods do
def seo_tags
presenter.humanized_essential_tag_string.gsub(/[^a-z0-9]+/, "_").gsub(/(?:^_+)|(?:_+$)/, "").gsub(/_{2,}/, "_")
end
def file(type = :original)
media_asset.variant(type).open_file!
end
def tagged_file_url(tagged_filenames: !CurrentUser.user.disable_tagged_filenames?)
slug = seo_tags if tagged_filenames
media_asset.variant(:original).file_url(slug)
end
def tagged_large_file_url(tagged_filenames: !CurrentUser.user.disable_tagged_filenames?)
slug = seo_tags if tagged_filenames
if media_asset.has_variant?(:sample)
media_asset.variant(:sample).file_url(slug)
else
media_asset.variant(:original).file_url(slug)
end
end
def file_url
media_asset.variant(:original).file_url
end
def large_file_url
if media_asset.has_variant?(:sample)
media_asset.variant(:sample).file_url
else
media_asset.variant(:original).file_url
end
end
def preview_file_url
# XXX hack to return placeholder thumbnail for Flash files the /posts.json API.
return Danbooru.config.storage_manager.file_url("/images/flash-preview.png") if media_asset.is_flash?
media_asset.variant(:preview).file_url
end
def file_url_for(user)
if user.default_image_size == "large" && image_width > Danbooru.config.large_image_width
tagged_large_file_url
else
tagged_file_url
end
end
def is_image?
file_ext.in?(%w[jpg gif png webp avif])
end
def is_flash?
file_ext =~ /swf/i
end
def is_video?
file_ext.in?(%w[webm mp4])
end
def is_ugoira?
file_ext =~ /zip/i
end
def has_preview?
is_image? || is_video? || is_ugoira?
end
end
concerning :ImageMethods do
def has_large?
return false if has_tag?("animated_gif") || has_tag?("animated_png")
return true if is_ugoira?
is_image? && image_width.present? && image_width > Danbooru.config.large_image_width
end
alias has_large has_large?
def large_image_width
if has_large?
[Danbooru.config.large_image_width, image_width.to_i].min
else
image_width.to_i
end
end
def large_image_height
ratio = Danbooru.config.large_image_width.to_f / image_width.to_f
if has_large? && ratio < 1
(image_height * ratio).to_i
else
image_height
end
end
def image_width_for(user)
if user.default_image_size == "large"
large_image_width
else
image_width
end
end
def image_height_for(user)
if user.default_image_size == "large"
large_image_height
else
image_height
end
end
def resize_percentage
return 100 if image_width.to_i == 0
100 * large_image_width.to_f / image_width.to_f
end
# XXX
def current_image_size
has_large? && CurrentUser.default_image_size == "large" ? "large" : "original"
end
end
concerning :ApprovalMethods do
def in_modqueue?
is_pending? || is_flagged? || is_appealed?
end
def is_active?
!is_deleted? && !in_modqueue?
end
def is_appealed?
is_deleted? && appeals.any?(&:pending?)
end
def is_appealable?
is_deleted? && !is_appealed?
end
def is_approvable?(user = CurrentUser.user)
!is_active? && uploader != user
end
def autoban
if has_tag?("banned_artist") || has_tag?("paid_reward")
self.is_banned = true
end
end
end
concerning :PresenterMethods do
def presenter
@presenter ||= PostPresenter.new(self)
end
def status_flags
flags = []
flags << "pending" if is_pending?
flags << "flagged" if is_flagged?
flags << "deleted" if is_deleted?
flags << "banned" if is_banned?
flags.join(" ")
end
# g => 0, s => 1, q => 2, e => 3
def rating_id
RATINGS.keys.index(rating)
end
def pretty_rating
RATINGS.fetch(rating)
end
def parsed_source
Source::URL.parse(source) if web_source?
end
def normalized_source
parsed_source&.page_url || source
end
def source_domain
parsed_source&.domain.to_s
end
end
concerning :TagMethods do
def tag_array
tag_string.split
end
def tag_array_was
tag_string_was.split
end
def tags
Tag.where(name: tag_array)
end
def tags_was
Tag.where(name: tag_array_was)
end
def added_tags
tags - tags_was
end
def decrement_tag_post_counts
Tag.where(:name => tag_array).update_all("post_count = post_count - 1") if tag_array.any?
end
def update_tag_post_counts
decrement_tags = tag_array_was - tag_array
increment_tags = tag_array - tag_array_was
if increment_tags.any?
Tag.increment_post_counts(increment_tags)
end
if decrement_tags.any?
Tag.decrement_post_counts(decrement_tags)
end
end
# Update tag_count_general, tag_count_copyright, etc.
def update_tag_category_counts
TagCategory.categories.each do |category_name|
tag_count = tags.select { |t| t.category_name.downcase == category_name }.size
send("tag_count_#{category_name}=", tag_count)
end
self.tag_count = tag_array.size
end
def merge_old_changes
if old_parent_id == ""
old_parent_id = nil
else
old_parent_id = old_parent_id.to_i
end
if old_parent_id == parent_id
self.parent_id = parent_id_before_last_save || parent_id_was
end
if old_source == source.to_s
self.source = source_before_last_save || source_was
end
if old_rating == rating
self.rating = rating_before_last_save || rating_was
end
@post_edit = PostEdit.new(self, tag_string_was, old_tag_string || tag_string_was, tag_string)
end
def normalize_tags
self.tag_string = Tag.create_for_list(post_edit.tag_names).uniq.sort.join(" ")
end
def add_automatic_tags(tags)
tags -= %w[incredibly_absurdres absurdres highres lowres flash video ugoira animated_gif animated_png exif_rotation non-repeating_animation non-web_source wide_image tall_image]
if tags.size >= 30
tags -= ["tagme"]
elsif tags.empty?
tags << "tagme"
end
if image_width >= 10_000 || image_height >= 10_000
tags << "incredibly_absurdres"
end
if image_width >= 3200 || image_height >= 2400
tags << "absurdres"
end
if image_width >= 1600 || image_height >= 1200
tags << "highres"
end
if image_width <= 500 && image_height <= 500
tags << "lowres"
end
if image_width >= 1024 && image_width.to_f / image_height >= 4
tags << "wide_image"
elsif image_height >= 1024 && image_height.to_f / image_width >= 4
tags << "tall_image"
end
if is_flash?
tags << "flash"
end
if is_video?
tags << "video"
end
if is_ugoira?
tags << "ugoira"
end
if source.present? && !web_source?
tags << "non-web_source"
end
source_url = parsed_source
if source_url.present? && source_url.recognized?
# A bad_link is an image URL from a recognized site that can't be converted to a page URL.
if source_url.image_url? && source_url.page_url.nil?
tags << "bad_link"
else
tags -= ["bad_link"]
end
# A bad_source is a source from a recognized site that isn't an image url or a page url.
if !source_url.image_url? && !source_url.page_url?
tags << "bad_source"
else
tags -= ["bad_source"]
end
end
# Allow only Flash files to be manually tagged as `animated`; GIFs, PNGs, videos, and ugoiras are automatically tagged.
tags -= ["animated"] unless is_flash?
tags << "animated" if media_asset.is_animated?
tags << "animated_gif" if media_asset.is_animated_gif?
tags << "animated_png" if media_asset.is_animated_png?
tags << "greyscale" if media_asset.is_greyscale?
tags << "exif_rotation" if media_asset.is_rotated?
tags << "non-repeating_animation" if media_asset.is_non_repeating_animation?
tags << "ai-generated" if media_asset.is_ai_generated?
# Allow Flash files to be manually tagged as `sound`; other files are automatically tagged.
tags -= ["sound"] unless is_flash?
tags << "sound" if media_asset.has_sound?
tags
end
def apply_post_metatags
post_edit.post_metatag_terms.each do |metatag|
case [metatag.name, metatag.value]
in "-pool", /^\d+$/ => pool_id
pool = Pool.find_by_id(pool_id)
pool&.remove!(self)
in "-pool", name
pool = Pool.find_by_name(name)
pool&.remove!(self)
in "pool", /^\d+$/ => pool_id
pool = Pool.find_by_id(pool_id)
pool&.add!(self)
in "pool", name
pool = Pool.find_by_name(name)
pool&.add!(self)
in "newpool", name
pool = Pool.find_by_name(name)
# XXX race condition
if pool.nil?
Pool.create!(name: name, description: "This pool was automatically generated", post_ids: [id])
else
pool.add!(self)
end
in "fav", name
raise User::PrivilegeError unless Pundit.policy!(CurrentUser.user, Favorite).create?
Favorite.create(post: self, user: CurrentUser.user)
in "-fav", name
raise User::PrivilegeError unless Pundit.policy!(CurrentUser.user, Favorite).create?
Favorite.destroy_by(post: self, user: CurrentUser.user)
in "upvote", name
vote!(1, CurrentUser.user)
in "downvote", name
vote!(-1, CurrentUser.user)
in "status", "active"
raise User::PrivilegeError unless CurrentUser.is_approver?
approvals.create!(user: CurrentUser.user)
in "status", "banned"
raise User::PrivilegeError unless CurrentUser.is_approver?
ban!(CurrentUser.user)
in "-status", "banned"
raise User::PrivilegeError unless CurrentUser.is_approver?
unban!(CurrentUser.user)
in "disapproved", reason
raise User::PrivilegeError unless CurrentUser.is_approver?
disapprovals.create!(user: CurrentUser.user, reason: reason.downcase)
in "child", "none"
children.each do |post|
post.update!(parent_id: nil)
end
in "-child", ids
next if ids.blank?
children.where_numeric_matches(:id, ids).each do |post|
post.update!(parent_id: nil)
end
in "child", ids
next if ids.blank?
Post.where_numeric_matches(:id, ids).where.not(id: id).limit(10).each do |post|
post.update!(parent_id: id)
end
in "-favgroup", name
favgroup = FavoriteGroup.find_by_name_or_id!(name, CurrentUser.user)
raise User::PrivilegeError unless Pundit.policy!(CurrentUser.user, favgroup).update?
favgroup&.remove(self)
in "favgroup", name
favgroup = FavoriteGroup.find_by_name_or_id!(name, CurrentUser.user)
raise User::PrivilegeError unless Pundit.policy!(CurrentUser.user, favgroup).update?
favgroup&.add(self)
end
end
rescue
# XXX Silently ignore errors so that the edit doesn't fail. We can't let
# the edit fail because then it will create a new post version even if
# the edit didn't go through.
nil
end
def apply_pre_metatags
post_edit.pre_metatag_terms.each do |metatag|
case [metatag.name, metatag.value]
in "parent", ("none" | "0")
self.parent_id = nil
in "-parent", /^\d+$/ => new_parent_id
if parent_id == new_parent_id.to_i
self.parent_id = nil
end
in "parent", /^\d+$/ => new_parent_id
if new_parent_id.to_i != id && Post.exists?(new_parent_id)
self.parent_id = new_parent_id.to_i
remove_parent_loops
end
in "rating", /\A([#{RATINGS.keys.join}])/i
self.rating = $1.downcase
in "source", "none"
self.source = ""
in "source", value
self.source = value
in category, name if category.in?(PostEdit::CATEGORIZATION_METATAGS)
Tag.find_or_create_by_name(name, category: category, current_user: CurrentUser.user)
else
nil
end
end
end
def web_source?
source.match?(%r{\Ahttps?://}i)
end
def has_tag?(tag)
tag_array.include?(tag)
end
def add_tag(tag)
self.tag_string = "#{tag_string} #{tag}"
end
def remove_tag(tag)
self.tag_string = (tag_array - Array(tag)).join(" ")
end
def tag_categories
@tag_categories ||= Tag.categories_for(tag_array)
end
def typed_tags(name)
@typed_tags ||= {}
@typed_tags[name] ||= begin
tag_array.select do |tag|
tag_categories[tag] == TagCategory.mapping[name]
end
end
end
TagCategory.categories.each do |category|
define_method("tag_string_#{category}") do
typed_tags(category).join(" ")
end
end
end
concerning :FavoriteMethods do
def favorited_by?(user)
return false if user.is_anonymous?
Favorite.exists?(post: self, user: user)
end
def favorite_groups
FavoriteGroup.for_post(id)
end
def remove_from_fav_groups
FavoriteGroup.for_post(id).find_each do |favgroup|
favgroup.remove(self)
end
end
end
concerning :PoolMethods do
def pools
Pool.where("pools.post_ids && array[?]", id)
end
def has_active_pools?
pools.undeleted.present?
end
def remove_from_all_pools
pools.find_each do |pool|
pool.remove!(self)
end
end
end
concerning :VoteMethods do
def vote!(score, voter)
# Ignore vote if user doesn't have permission to vote.
return unless Pundit.policy!(voter, PostVote).create?
with_lock do
votes.create!(user: voter, score: score) unless votes.active.exists?(user: voter, score: score)
reload # PostVote.create modifies our score. Reload to get the new score.
end
end
end
concerning :ParentMethods do
# A parent has many children. A child belongs to a parent.
# A parent cannot have a parent.
#
# After expunging a child:
# - Move favorites to parent.
# - Does the parent have any children?
# - Yes: Done.
# - No: Update parent's has_children flag to false.
#
# After expunging a parent:
# - Move favorites to the first child.
# - Reparent all children to the first child.
def update_has_children_flag
update(has_children: children.exists?, has_active_children: children.undeleted.exists?)
end
def blank_out_nonexistent_parents
if parent_id.present? && parent.nil?
self.parent_id = nil
end
end
def remove_parent_loops
if parent.present? && parent.parent_id.present? && parent.parent_id == id
parent.parent_id = nil
parent.save
end
end
def update_parent_on_destroy
parent&.update_has_children_flag
end
def update_children_on_destroy
children.update(parent: nil)
end
def update_parent_on_save
return unless saved_change_to_parent_id? || saved_change_to_is_deleted?
parent.update_has_children_flag if parent.present?
Post.find(parent_id_before_last_save).update_has_children_flag if parent_id_before_last_save.present?
rescue
# XXX Silently ignore errors so that the edit doesn't fail. We can't let
# the edit fail because then it will create a new post version even if
# the edit didn't go through.
nil
end
def give_favorites_to_parent(current_user = CurrentUser.user)
return if parent.nil?
transaction do
favorites.each do |fav|
fav.destroy!
Favorite.create(post: parent, user: fav.user)
end
end
ModAction.log("moved favorites from post ##{id} to post ##{parent.id}", :post_move_favorites, subject: self, user: current_user)
end
def has_visible_children?
return true if has_active_children?
return true if has_children? && CurrentUser.user.show_deleted_children?
return true if has_children? && is_deleted?
return false
end
def has_visible_children
has_visible_children?
end
end
concerning :DeletionMethods do
def expunge!(current_user = CurrentUser.user)
transaction do
Post.without_timeout do
ModAction.log("permanently deleted post ##{id} (md5=#{md5})", :post_permanent_delete, subject: nil, user: current_user)
update_children_on_destroy
decrement_tag_post_counts
remove_from_all_pools
remove_from_fav_groups
media_asset.trash!(current_user, log: false)
destroy
update_parent_on_destroy
end
end
remove_iqdb # this is non-transactional
end
def ban!(current_user)
return if is_banned?
update_column(:is_banned, true)
ModAction.log("banned post ##{id}", :post_ban, subject: self, user: current_user)
end
def unban!(current_user)
return unless is_banned?
update_column(:is_banned, false)
ModAction.log("unbanned post ##{id}", :post_unban, subject: self, user: current_user)
end
def delete!(reason, move_favorites: false, user: CurrentUser.user)
with_lock do
automated = (user == User.system)
flags.pending.update!(status: :succeeded)
appeals.pending.update!(status: :rejected)
flags.create!(reason: reason, is_deletion: true, creator: user, status: :succeeded)
update!(is_deleted: true, is_pending: false, is_flagged: false)
# XXX This must happen *after* the `is_deleted` flag is set to true (issue #3419).
give_favorites_to_parent if move_favorites
uploader.upload_limit.update_limit!(is_pending?, false)
unless automated
ModAction.log("deleted post ##{id}, reason: #{reason}", :post_delete, subject: self, user: user)
end
end
end
end
concerning :VersionMethods do
# XXX `create_version` must be called before `apply_post_metatags` because
# `apply_post_metatags` may update the post itself, which will clear all
# changes to the post and make saved_change_to_*? return false.
def create_version(force = false)
if new_record? || saved_change_to_watched_attributes? || force
create_new_version
end
end
def saved_change_to_watched_attributes?
saved_change_to_rating? || saved_change_to_source? || saved_change_to_parent_id? || saved_change_to_tag_string?
end
def merge_version?
prev = versions.last
prev && prev.updater_id == CurrentUser.user.id && prev.updated_at > 1.hour.ago
end
def create_new_version
User.where(id: CurrentUser.id).update_all("post_update_count = post_update_count + 1")
PostVersion.queue(self) if PostVersion.enabled?
end
def revert_to(target)
if id != target.post_id
raise RevertError, "You cannot revert to a previous version of another post."
end
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
concerning :NoteMethods do
def has_notes?
last_noted_at.present?
end
def copy_notes_to(other_post, copy_tags: NOTE_COPY_TAGS)
transaction do
if id == other_post.id
errors.add(:base, "Source and destination posts are the same")
return false
end
unless has_notes?
errors.add(:post, "has no notes")
return false
end
notes.active.each do |note|
note.copy_to(other_post)
end
dummy = Note.new
if notes.active.length == 1
dummy.body = "Copied 1 note from post ##{id}."
else
dummy.body = "Copied #{notes.active.length} notes from post ##{id}."
end
dummy.is_active = false
dummy.post_id = other_post.id
dummy.x = dummy.y = dummy.width = dummy.height = 0
dummy.save
copy_tags.each do |tag|
other_post.remove_tag(tag)
other_post.add_tag(tag) if has_tag?(tag)
end
other_post.has_embedded_notes = has_embedded_notes
other_post.save
end
end
end
concerning :ApiMethods do
def legacy_attributes
hash = {
"has_comments" => last_commented_at.present?,
"parent_id" => parent_id,
"status" => status,
"has_children" => has_children?,
"created_at" => created_at.to_formatted_s(:db),
"has_notes" => has_notes?,
"rating" => rating,
"author" => uploader.name,
"creator_id" => uploader_id,
"width" => image_width,
"source" => source,
"score" => score,
"tags" => tag_string,
"height" => image_height,
"file_size" => file_size,
"id" => id,
}
if visible?
hash["file_url"] = file_url
hash["preview_url"] = preview_file_url
hash["md5"] = md5
end
hash
end
def status
if is_pending?
"pending"
elsif is_deleted?
"deleted"
elsif is_flagged?
"flagged"
else
"active"
end
end
end
concerning :SearchMethods do
class_methods do
# Return a set of up to N random posts. May return less if there aren't
# enough posts.
#
# @param n [Integer] The maximum number of posts to return
# @return [ActiveRecord::Relation<Post>]
def random(n = 1)
posts = n.times.map do
key = SecureRandom.hex(16)
random_up(key) || random_down(key)
end.compact.uniq
reorder(nil).in_order_of(:id, posts.map(&:id))
end
def random_up(key)
where("posts.md5 < ?", key).reorder(md5: :desc).first
end
def random_down(key)
where("posts.md5 >= ?", key).reorder(md5: :asc).first
end
def sample(query, sample_size)
user_tag_match(query, safe_mode: false).reorder(:md5).limit(sample_size)
end
# unflattens the tag_string into one tag per row.
def with_unflattened_tags
joins("CROSS JOIN unnest(string_to_array(tag_string, ' ')) AS tag")
end
def with_comment_stats
relation = left_outer_joins(:comments).group(:id).select("posts.*")
relation = relation.select("COUNT(comments.id) AS comment_count")
relation = relation.select("COUNT(comments.id) FILTER (WHERE comments.is_deleted = TRUE) AS deleted_comment_count")
relation = relation.select("COUNT(comments.id) FILTER (WHERE comments.is_deleted = FALSE) AS active_comment_count")
relation
end
def with_note_stats
relation = left_outer_joins(:notes).group(:id).select("posts.*")
relation = relation.select("COUNT(notes.id) AS note_count")
relation = relation.select("COUNT(notes.id) FILTER (WHERE notes.is_active = TRUE) AS active_note_count")
relation = relation.select("COUNT(notes.id) FILTER (WHERE notes.is_active = FALSE) AS deleted_note_count")
relation
end
def with_flag_stats
relation = left_outer_joins(:flags).group(:id).select("posts.*")
relation.select("COUNT(post_flags.id) AS flag_count")
end
def with_appeal_stats
relation = left_outer_joins(:appeals).group(:id).select("posts.*")
relation = relation.select("COUNT(post_appeals.id) AS appeal_count")
relation
end
def with_approval_stats
relation = left_outer_joins(:approvals).group(:id).select("posts.*")
relation = relation.select("COUNT(post_approvals.id) AS approval_count")
relation
end