-
Notifications
You must be signed in to change notification settings - Fork 56
/
post.rb
1729 lines (1449 loc) · 49.9 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
class Post < ApplicationRecord
class RevertError < Exception ; end
class SearchError < Exception ; end
class DeletionError < Exception ; end
class TimeoutError < Exception ; end
# Tags to copy when copying notes.
NOTE_COPY_TAGS = %w[translated partially_translated translation_check translation_request]
before_validation :initialize_uploader, :on => :create
before_validation :merge_old_changes
before_validation :apply_source_diff
before_validation :apply_tag_diff, if: :should_process_tags?
before_validation :normalize_tags, if: :should_process_tags?
before_validation :tag_count_not_insane, if: :should_process_tags?
before_validation :strip_source
before_validation :fix_bg_color
before_validation :blank_out_nonexistent_parents
before_validation :remove_parent_loops
validates :md5, uniqueness: { :on => :create, message: ->(obj, data) {"duplicate: #{Post.find_by_md5(obj.md5).id}"} }
validates :rating, inclusion: { in: %w(s q e), message: "rating must be s, q, or e" }
validates :bg_color, format: { with: /\A[A-Fa-f0-9]{6}\z/ }, allow_nil: true
validates :description, length: { maximum: Danbooru.config.post_descr_max_size }, if: :description_changed?
validate :added_tags_are_valid, if: :should_process_tags?
validate :removed_tags_are_valid, if: :should_process_tags?
validate :has_artist_tag, if: :should_process_tags?
validate :has_enough_tags, if: :should_process_tags?
validate :post_is_not_its_own_parent
validate :updater_can_change_rating
before_save :update_tag_post_counts, if: :should_process_tags?
before_save :set_tag_counts, if: :should_process_tags?
after_save :create_lock_post_events
after_save :create_version
after_save :update_parent_on_save
after_save :apply_post_metatags
after_commit :delete_files, :on => :destroy
after_commit :remove_iqdb_async, :on => :destroy
after_commit :update_iqdb_async, :on => :create
after_commit :generate_video_samples, on: :create, if: :is_video?
belongs_to :updater, :class_name => "User", optional: true # this is handled in versions
belongs_to :approver, class_name: "User", optional: true
belongs_to :uploader, :class_name => "User"
user_status_counter :post_count, foreign_key: :uploader_id
belongs_to :parent, class_name: "Post", optional: true
has_one :upload, :dependent => :destroy
has_many :flags, :class_name => "PostFlag", :dependent => :destroy
has_many :votes, :class_name => "PostVote", :dependent => :destroy
has_many :notes, :dependent => :destroy
has_many :comments, -> {includes(:creator, :updater).order("comments.is_sticky DESC, comments.id")}, :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
has_many :replacements, class_name: "PostReplacement", :dependent => :destroy
attr_accessor :old_tag_string, :old_parent_id, :old_source, :old_rating,
:do_not_version_changes, :tag_string_diff, :source_diff, :edit_reason
has_many :versions, -> {order("post_versions.id ASC")}, :class_name => "PostVersion", :dependent => :destroy
IMAGE_TYPES = %i[original large preview crop]
module PostFileMethods
extend ActiveSupport::Concern
module ClassMethods
def delete_files(post_id, md5, file_ext, force: false)
if Post.where(md5: md5).exists? && !force
raise DeletionError.new("Files still in use; skipping deletion.")
end
Danbooru.config.storage_manager.delete_post_files(md5, file_ext)
end
end
def delete_files
Post.delete_files(id, md5, file_ext, force: true)
end
def move_files_on_delete
Danbooru.config.storage_manager.move_file_delete(self)
end
def move_files_on_undelete
Danbooru.config.storage_manager.move_file_undelete(self)
end
def storage_manager
Danbooru.config.storage_manager
end
def file(type = :original)
storage_manager.open_file(self, type)
end
def tagged_large_file_url
storage_manager.file_url(self, :large)
end
def file_url
storage_manager.file_url(self, :original)
end
def file_url_ext(ext)
storage_manager.file_url_ext(self, :original, ext)
end
def scaled_url_ext(scale, ext)
storage_manager.file_url_ext(self, :scaled, ext, scale: scale)
end
def large_file_url
return file_url if !has_large?
storage_manager.file_url(self, :large)
end
def preview_file_url
storage_manager.file_url(self, :preview)
end
def reverse_image_url
return large_file_url if has_large?
preview_file_url
end
def file_path
storage_manager.file_path(self, file_ext, :original, is_deleted?)
end
def large_file_path
storage_manager.file_path(self, file_ext, :large, is_deleted?)
end
def preview_file_path
storage_manager.file_path(self, file_ext, :preview, is_deleted?)
end
def crop_file_url
storage_manager.file_url(self, :crop)
end
def open_graph_video_url
if image_height > 720 && has_sample_size?('720p')
return scaled_url_ext('720p', 'mp4')
end
file_url_ext('mp4')
end
def open_graph_image_url
if is_image?
if has_large?
large_file_url
else
file_url
end
else
preview_file_url
end
end
def file_url_for(user)
if user.default_image_size == "large" && image_width > Danbooru.config.large_image_width
large_file_url
else
file_url
end
end
def file_url_ext_for(user, ext)
if user.default_image_size == "large" && is_video? && has_sample_size?('720p')
scaled_url_ext('720p', ext)
else
file_url_ext(ext)
end
end
def display_class_for(user)
if user.default_image_size == "original"
""
else
"fit-window"
end
end
def has_preview?
is_image? || is_video?
end
def has_dimensions?
image_width.present? && image_height.present?
end
def preview_dimensions(max_px = Danbooru.config.small_image_width)
return [max_px, max_px] unless has_dimensions?
height = width = max_px
dimension_ratio = image_width.to_f / image_height
if dimension_ratio > 1
height = (width / dimension_ratio).to_i
else
width = (height * dimension_ratio).to_i
end
[height, width]
end
def has_sample_size?(scale)
(generated_samples || []).include?(scale)
end
def scaled_sample_dimensions(box)
ratio = [box[0] / image_width.to_f, box[1] / image_height.to_f].min
width = [([image_width * ratio, 2].max.ceil), box[0]].min & ~1
height = [([image_height * ratio, 2].max.ceil), box[1]].min & ~1
[width, height]
end
def generate_video_samples(later: false)
if later
PostVideoConversionJob.set(wait: 1.minute).perform_later(id)
else
PostVideoConversionJob.perform_later(id)
end
end
def regenerate_video_samples!
# force code to assume no samples exist
update_column(:generated_samples, nil)
generate_video_samples(later: true)
end
def regenerate_image_samples!
file = self.file()
preview_file, crop_file, sample_file = ::PostThumbnailer.generate_resizes(file, image_height, image_width, is_video? ? :video : :image)
storage_manager.store_file(sample_file, self, :large) if sample_file.present?
storage_manager.store_file(preview_file, self, :preview) if preview_file.present?
storage_manager.store_file(crop_file, self, :crop) if crop_file.present?
update({has_cropped: crop_file.present?})
ensure
file.close
end
end
module ImageMethods
def twitter_card_supported?
image_width.to_i >= 280 && image_height.to_i >= 150
end
def has_large?
return true if is_video?
return false if is_gif?
return false if is_flash?
return false if has_tag?("animated_gif|animated_png")
is_image? && image_width.present? && image_width > Danbooru.config.large_image_width
end
def has_large
!!has_large?
end
def large_image_width
if has_large?
[Danbooru.config.large_image_width, image_width].min
else
image_width
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 resize_percentage
100 * large_image_width.to_f / image_width.to_f
end
end
module ApprovalMethods
def is_approvable?
!is_status_locked? && is_pending? && approver.nil?
end
def unflag!
flags.each(&:resolve!)
update(is_flagged: false)
PostEvent.add(id, CurrentUser.user, :flag_removed)
end
def approved_by?(user)
approver == user || approvals.where(user: user).exists?
end
def unapprove!
PostEvent.add(id, CurrentUser.user, :unapproved)
update(approver: nil, is_pending: true)
end
def is_unapprovable?(user)
# Allow unapproval only by the approver
return false if approver.present? && approver != user
# Prevent unapproving self approvals by someone else
return false if approver.nil? && uploader != user
# Allow unapproval when the post is not pending anymore and is not at risk of auto deletion
!is_pending? && !is_deleted? && created_at.after?(PostPruner::DELETION_WINDOW.days.ago)
end
def approve!(approver = CurrentUser.user, resolve_flags: false)
return if self.approver != nil
if resolve_flags && flags.unresolved.any?
unflag!
end
if uploader == approver
update(is_pending: false)
else
PostEvent.add(id, CurrentUser.user, :approved)
approvals.create(user: approver)
update(approver: approver, is_pending: false)
end
end
end
module SourceMethods
def source_array
return [] if source.blank?
source.split("\n")
end
def apply_source_diff
return unless source_diff.present?
diff = source_diff.gsub(/\r\n?/, "\n").gsub(/%0A/i, "\n").split(/(?:\r)?\n/)
to_remove, to_add = diff.partition {|x| x =~ /\A-/i}
to_remove = to_remove.map {|x| x[1..-1]}
current_sources = source_array
current_sources += to_add
current_sources -= to_remove
self.source = current_sources.join("\n")
end
def strip_source
self.source = "" if source.blank?
self.source.gsub!(/\r\n?/, "\n") # Normalize newlines
self.source.gsub!(/%0A/i, "\n") # Handle accidentally-encoded %0As from api calls (which would normally insert a literal %0A into the source)
sources = self.source.split(/(?:\r)?\n/)
gallery_sources = []
submission_sources = []
direct_sources = []
additional_sources = []
alternate_processors = []
sources.map! do |src|
src.unicode_normalize!(:nfc)
src = src.try(:strip)
alternate = Sources::Alternates.find(src)
alternate_processors << alternate
gallery_sources << alternate.gallery_url if alternate.gallery_url
submission_sources << alternate.submission_url if alternate.submission_url
direct_sources << alternate.submission_url if alternate.direct_url
additional_sources += alternate.additional_urls if alternate.additional_urls
alternate.original_url
end
sources = (sources + submission_sources + gallery_sources + direct_sources + additional_sources).compact.reject{ |e| e.strip.empty? }.uniq
alternate_processors.each do |alt_processor|
sources = alt_processor.remove_duplicates(sources)
end
self.source = sources.first(10).join("\n")
end
def copy_sources_to_parent
return unless parent_id.present?
parent.source += "\n#{self.source}"
end
end
module PresenterMethods
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.join(" ")
end
def pretty_rating
case rating
when "q"
"Questionable"
when "e"
"Explicit"
when "s"
"Safe"
end
end
end
module TagMethods
def should_process_tags?
tag_string_changed? || locked_tags_changed? || tag_string_diff.present?
end
def tag_array
@tag_array ||= Tag.scan_tags(tag_string)
end
def tag_array_was
@tag_array_was ||= Tag.scan_tags(tag_string_in_database.presence || tag_string_before_last_save || "")
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.decrement_post_counts(tag_array)
end
def increment_tag_post_counts
Tag.increment_post_counts(tag_array)
end
def update_tag_post_counts
return if is_deleted?
decrement_tags = tag_array_was - tag_array
increment_tags = tag_array - tag_array_was
Tag.increment_post_counts(increment_tags)
Tag.decrement_post_counts(decrement_tags)
end
def set_tag_count(category, tagcount)
self.send("tag_count_#{category}=", tagcount)
end
def inc_tag_count(category)
set_tag_count(category, self.send("tag_count_#{category}") + 1)
end
def set_tag_counts(disable_cache: true)
self.tag_count = 0
TagCategory.categories.each {|x| set_tag_count(x, 0)}
categories = Tag.categories_for(tag_array, disable_cache: disable_cache)
categories.each_value do |category|
self.tag_count += 1
inc_tag_count(TagCategory.reverse_mapping[category])
end
end
def merge_old_changes
@removed_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)
kept_tags = current_tags & new_tags
@removed_tags = old_tags - kept_tags
set_tag_string(((current_tags + new_tags) - old_tags + (current_tags & new_tags)).uniq.sort.join(" "))
end
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
end
def apply_tag_diff
@removed_tags = []
return unless tag_string_diff.present?
current_tags = tag_array
diff = Tag.scan_tags(tag_string_diff.downcase)
to_remove, to_add = diff.partition {|x| x =~ /\A-/i}
to_remove = to_remove.map {|x| x[1..-1]}
to_remove = TagAlias.to_aliased(to_remove)
to_add = TagAlias.to_aliased(to_add)
@removed_tags = to_remove
current_tags += to_add
current_tags -= to_remove
set_tag_string(current_tags.uniq.sort.join(" "))
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 tag_count_not_insane
max_count = Danbooru.config.max_tags_per_post
if Tag.scan_tags(tag_string).size > max_count
self.errors.add(:tag_string, "tag count exceeds maximum of #{max_count}")
throw :abort
end
true
end
def normalize_tags
if !locked_tags.nil? && locked_tags.strip.blank?
self.locked_tags = nil
elsif locked_tags.present?
locked = Tag.scan_tags(locked_tags.downcase)
to_remove, to_add = locked.partition {|x| x =~ /\A-/i}
to_remove = to_remove.map {|x| x[1..-1]}
to_remove = TagAlias.to_aliased(to_remove)
@locked_to_remove = to_remove + to_remove.map { |tag_name| TagImplication.cached_descendants(tag_name) }.flatten
@locked_to_add = TagAlias.to_aliased(to_add)
end
normalized_tags = Tag.scan_tags(tag_string)
# Sanity check input, this is checked again on output as well to prevent bad cases where implications push post
# over the limit and posts will fail to edit later on.
if normalized_tags.size > Danbooru.config.max_tags_per_post
self.errors.add(:tag_string, "tag count exceeds maximum of #{Danbooru.config.max_tags_per_post}")
throw :abort
end
normalized_tags = apply_casesensitive_metatags(normalized_tags)
normalized_tags = normalized_tags.map {|tag| tag.downcase}
normalized_tags = filter_metatags(normalized_tags)
normalized_tags = remove_negated_tags(normalized_tags)
normalized_tags = remove_dnp_tags(normalized_tags)
normalized_tags = TagAlias.to_aliased(normalized_tags)
normalized_tags = apply_locked_tags(normalized_tags, @locked_to_add, @locked_to_remove)
normalized_tags = %w[tagme] if normalized_tags.empty?
normalized_tags = add_automatic_tags(normalized_tags)
normalized_tags = TagImplication.with_descendants(normalized_tags)
add_dnp_tags_to_locked(normalized_tags)
normalized_tags -= @locked_to_remove if @locked_to_remove # Prevent adding locked tags through implications or aliases.
normalized_tags = normalized_tags.compact.uniq
normalized_tags = Tag.find_or_create_by_name_list(normalized_tags)
normalized_tags = remove_invalid_tags(normalized_tags)
set_tag_string(normalized_tags.map(&:name).uniq.sort.join(" "))
end
# Prevent adding these without an implication
def remove_dnp_tags(tags)
locked = locked_tags || ""
# Don't remove dnp tags here if they would be later added through locked tags
# to prevent the warning message from appearing when they didn't actually get removed
if locked.exclude?("avoid_posting")
tags -= ["avoid_posting"]
end
if locked.exclude?("conditional_dnp")
tags -= ["conditional_dnp"]
end
tags
end
def add_dnp_tags_to_locked(tags)
locked = Tag.scan_tags((locked_tags || '').downcase)
if tags.include? 'avoid_posting'
locked << 'avoid_posting'
end
if tags.include? 'conditional_dnp'
locked << 'conditional_dnp'
end
self.locked_tags = locked.uniq.join(' ') if locked.size > 0
end
def apply_locked_tags(tags, to_add, to_remove)
if to_remove
overlap = tags & to_remove
n = overlap.size
if n > 0
self.warnings.add(:base, "Forcefully removed #{n} locked #{n == 1 ? "tag" : "tags"}: #{overlap.join(", ")}")
end
tags -= to_remove
end
if to_add
missing = to_add - tags
n = missing.size
if n > 0
self.warnings.add(:base, "Forcefully added #{n} locked #{n == 1 ? "tag" : "tags"}: #{missing.join(", ")}")
end
tags += to_add
end
tags
end
def remove_invalid_tags(tags)
tags = tags.reject do |tag|
if tag.errors.size > 0
self.warnings.add(:base, "Can't add tag #{tag.name}: #{tag.errors.full_messages.join('; ')}")
end
tag.errors.size > 0
end
tags
end
def remove_negated_tags(tags)
@negated_tags, tags = tags.partition {|x| x =~ /\A-/i}
@negated_tags = @negated_tags.map {|x| x[1..-1]}
@negated_tags = TagAlias.to_aliased(@negated_tags)
return tags - @negated_tags
end
def add_automatic_tags(tags)
return tags if !Danbooru.config.enable_dimension_autotagging?
tags -= %w[thumbnail low_res hi_res absurd_res superabsurd_res huge_filesize flash webm mp4 wide_image long_image]
if has_dimensions?
tags << "superabsurd_res" if image_width >= 10_000 && image_height >= 10_000
tags << "absurd_res" if image_width >= 3200 || image_height >= 2400
tags << "hi_res" if image_width >= 1600 || image_height >= 1200
tags << "low_res" if image_width <= 500 && image_height <= 500
tags << "thumbnail" if image_width <= 250 && image_height <= 250
if image_width >= 1024 && image_width.to_f / image_height >= 4
tags << "wide_image"
tags << "long_image"
elsif image_height >= 1024 && image_height.to_f / image_width >= 4
tags << "tall_image"
tags << "long_image"
end
end
if file_size >= 30.megabytes
tags << "huge_filesize"
end
if is_flash?
tags << "flash"
end
if is_webm?
tags << "webm"
end
unless is_gif?
tags -= ["animated_gif"]
end
unless is_png?
tags -= ["animated_png"]
end
return tags
end
def apply_casesensitive_metatags(tags)
casesensitive_metatags, tags = tags.partition {|x| x =~ /\A(?:source):/i}
#Reuse the following metatags after the post has been saved
casesensitive_metatags += tags.select {|x| x =~ /\A(?:newpool):/i}
if casesensitive_metatags.length > 0
case casesensitive_metatags[-1]
when /^source:none$/i
self.source = ""
when /^source:"(.*)"$/i
self.source = $1
when /^source:(.*)$/i
self.source = $1
when /^newpool:(.+)$/i
pool = Pool.find_by_name($1)
if pool.nil?
pool = Pool.create(:name => $1, :description => "This pool was automatically generated")
end
end
end
return tags
end
def filter_metatags(tags)
@bad_type_changes = []
@pre_metatags, tags = tags.partition {|x| x =~ /\A(?:rating|parent|-parent|-?locked):/i}
tags = apply_categorization_metatags(tags)
@post_metatags, tags = tags.partition {|x| x =~ /\A(?:-pool|pool|newpool|-set|set|fav|-fav|child|-child|upvote|downvote):/i}
apply_pre_metatags
if @bad_type_changes.size > 0
bad_tags = @bad_type_changes.map {|x| "[[#{x}]]"}
self.warnings.add(:base, "Failed to update the tag category for the following tags: #{bad_tags.join(', ')}. You can not edit the tag category of existing tags using prefixes. Please review usage of the tags, and if you are sure that the tag categories should be changed, then you can change them using the \"Tags\":/tags section of the website")
end
tags
end
def apply_categorization_metatags(tags)
prefixed, unprefixed = tags.partition {|x| x =~ Tag.categories.regexp}
prefixed = Tag.find_or_create_by_name_list(prefixed)
prefixed.map! do |tag|
@bad_type_changes << tag.name if tag.errors.include? :category
tag.name
end
prefixed + unprefixed
end
def apply_post_metatags
return unless @post_metatags
@post_metatags.each do |tag|
case tag
when /^-pool:(\d+)$/i
pool = Pool.find_by_id($1.to_i)
pool.remove!(self) if pool
when /^-pool:(.+)$/i
pool = Pool.find_by_name($1)
pool.remove!(self) if pool
when /^pool:(\d+)$/i
pool = Pool.find_by_id($1.to_i)
pool.add!(self) if pool
when /^pool:(.+)$/i
pool = Pool.find_by_name($1)
pool.add!(self) if pool
when /^newpool:(.+)$/i
pool = Pool.find_by_name($1)
pool.add!(self) if pool
when /^set:(\d+)$/i
set = PostSet.find_by_id($1.to_i)
set.add!(self) if set&.can_edit_posts?(CurrentUser.user)
when /^-set:(\d+)$/i
set = PostSet.find_by_id($1.to_i)
set.remove!(self) if set&.can_edit_posts?(CurrentUser.user)
when /^set:(.+)$/i
set = PostSet.find_by_shortname($1)
set.add!(self) if set&.can_edit_posts?(CurrentUser.user)
when /^-set:(.+)$/i
set = PostSet.find_by_shortname($1)
set.remove!(self) if set&.can_edit_posts?(CurrentUser.user)
when /^child:none$/i
children.each do |post|
post.update!(parent_id: nil)
end
when /^-child:(.+)$/i
children.numeric_attribute_matches(:id, $1).each do |post|
post.update!(parent_id: nil)
end
when /^child:(.+)$/i
Post.numeric_attribute_matches(:id, $1).where.not(id: id).limit(10).each do |post|
post.update!(parent_id: id)
end
end
end
end
def apply_pre_metatags
return unless @pre_metatags
@pre_metatags.each do |tag|
case tag
when /^parent:none$/i, /^parent:0$/i
self.parent_id = nil
when /^-parent:(\d+)$/i
if parent_id == $1.to_i
self.parent_id = nil
end
when /^parent:(\d+)$/i
if $1.to_i != id && Post.exists?(["id = ?", $1.to_i])
self.parent_id = $1.to_i
remove_parent_loops
end
when /^rating:([qse])/i
self.rating = $1
when /^(-?)locked:notes?$/i
self.is_note_locked = ($1 != "-") if CurrentUser.is_janitor?
when /^(-?)locked:rating$/i
self.is_rating_locked = ($1 != "-") if CurrentUser.is_janitor?
when /^(-?)locked:status$/i
self.is_status_locked = ($1 != "-") if CurrentUser.is_admin?
end
end
end
def has_tag?(tag)
!!(tag_string =~ /(?:^| )(?:#{tag})(?:$| )/)
end
def add_tag(tag)
set_tag_string("#{tag_string} #{tag}")
end
def remove_tag(tag)
set_tag_string((tag_array - Array(tag)).join(" "))
end
def inject_tag_categories(tag_cats)
@tag_categories = tag_cats
@typed_tags = tag_array.group_by do |x|
@tag_categories[x] || 'general'
end
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
def copy_tags_to_parent
return unless parent_id.present?
parent.tag_string += " #{tag_string}"
end
end
module FavoriteMethods
def clean_fav_string!
array = fav_string.split.uniq
self.fav_string = array.join(" ")
self.fav_count = array.size
end
def favorited_by?(user_id = CurrentUser.id)
!!(fav_string =~ /(?:\A| )fav:#{user_id}(?:\Z| )/)
end
alias_method :is_favorited?, :favorited_by?
def append_user_to_fav_string(user_id)
self.fav_string = (fav_string + " fav:#{user_id}").strip
clean_fav_string!
end
def delete_user_from_fav_string(user_id)
self.fav_string = fav_string.gsub(/(?:\A| )fav:#{user_id}(?:\Z| )/, " ").strip
clean_fav_string!
end
# users who favorited this post, ordered by users who favorited it first
def favorited_users
favorited_user_ids = fav_string.scan(/\d+/).map(&:to_i)
visible_users = User.find(favorited_user_ids).reject(&:hide_favorites?)
ordered_users = visible_users.index_by(&:id).slice(*favorited_user_ids).values
ordered_users
end
def remove_from_favorites
Favorite.where(post_id: id).delete_all
user_ids = fav_string.scan(/\d+/)
UserStatus.where(:user_id => user_ids).update_all("favorite_count = favorite_count - 1")
end
end
module UploaderMethods
def initialize_uploader
if uploader_id.blank?
self.uploader_id = CurrentUser.id
self.uploader_ip_addr = CurrentUser.ip_addr
end
end
def uploader_name
if association(:uploader).loaded?
return uploader&.name || "Anonymous"
end
User.id_to_name(uploader_id)
end
end
module SetMethods
def set_ids
pool_string.scan(/set\:(\d+)/).map {|set| set[0].to_i}
end
def post_sets
@post_sets ||= begin
return PostSet.none if pool_string.blank?
PostSet.where(id: set_ids)
end
end
def belongs_to_post_set(set)
pool_string =~ /(?:\A| )set:#{set.id}(?:\z| )/
end
def add_set!(set, force = false)
return if belongs_to_post_set(set) && !force
with_lock do
self.pool_string = "#{pool_string} set:#{set.id}".strip
end
end
def remove_set!(set)
with_lock do
self.pool_string = (pool_string.split(' ') - ["set:#{set.id}"]).join(' ').strip
end
end
def give_post_sets_to_parent
transaction do
post_sets.find_each do |set|
begin
set.remove([id])
set.add([parent.id]) if parent_id.present? && set.transfer_on_delete
set.save!
rescue
#Ignore set errors due to things like set post count
end
end
end
end
def remove_from_post_sets
post_sets.find_each do |set|
set.remove!(self)
end
end
end
module PoolMethods
def pool_ids
pool_string.scan(/pool\:(\d+)/).map {|pool| pool[0].to_i}
end
def pools
@pools ||= begin
return Pool.none if pool_string.blank?
Pool.where(id: pool_ids).series_first
end
end
def has_active_pools?
pools.any?
end
def belongs_to_pool?(pool)
pool_string =~ /(?:\A| )pool:#{pool.id}(?:\Z| )/
end
def add_pool!(pool)
return if belongs_to_pool?(pool)
with_lock do
self.pool_string = "#{pool_string} pool:#{pool.id}".strip
end