/
pseud.rb
472 lines (407 loc) · 16.5 KB
/
pseud.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
class Pseud < ApplicationRecord
include ActiveModel::ForbiddenAttributesProtection
include Searchable
include WorksOwner
has_attached_file :icon,
styles: { standard: "100x100>" },
path: %w(staging production).include?(Rails.env) ? ":attachment/:id/:style.:extension" : ":rails_root/public:url",
storage: %w(staging production).include?(Rails.env) ? :s3 : :filesystem,
s3_protocol: "https",
s3_credentials: "#{Rails.root}/config/s3.yml",
bucket: %w(staging production).include?(Rails.env) ? YAML.load_file("#{Rails.root}/config/s3.yml")['bucket'] : "",
default_url: "/images/skins/iconsets/default/icon_user.png"
validates_attachment_content_type :icon, content_type: /image\/\S+/, allow_nil: true
validates_attachment_size :icon, less_than: 500.kilobytes, allow_nil: true
NAME_LENGTH_MIN = 1
NAME_LENGTH_MAX = 40
DESCRIPTION_MAX = 500
belongs_to :user
delegate :login, to: :user, prefix: true
has_many :kudos
has_many :bookmarks, dependent: :destroy
has_many :recs, -> { where(rec: true) }, class_name: 'Bookmark'
has_many :comments
has_many :creatorships
has_many :works, -> { readonly(false) }, through: :creatorships, source: :creation, source_type: 'Work'
has_many :tags, through: :works
has_many :filters, through: :works
has_many :direct_filters, through: :works
has_many :chapters, -> { readonly(false) }, through: :creatorships, source: :creation, source_type: 'Chapter'
has_many :series, -> { readonly(false) }, through: :creatorships, source: :creation, source_type: 'Series'
has_many :collection_participants, dependent: :destroy
has_many :collections, through: :collection_participants
has_many :tag_set_ownerships, dependent: :destroy
has_many :tag_sets, through: :tag_set_ownerships
has_many :challenge_signups, dependent: :destroy
has_many :gifts, -> { where(rejected: false) }
has_many :gift_works, through: :gifts, source: :work
has_many :rejected_gifts, -> { where(rejected: true) }, class_name: "Gift"
has_many :rejected_gift_works, through: :rejected_gifts, source: :work
has_many :offer_assignments, -> { where("challenge_assignments.sent_at IS NOT NULL") }, through: :challenge_signups
has_many :pinch_hit_assignments, -> { where("challenge_assignments.sent_at IS NOT NULL") }, class_name: "ChallengeAssignment", foreign_key: "pinch_hitter_id"
has_many :prompts, dependent: :destroy
before_validation :clear_icon
validates_presence_of :name
validates_length_of :name,
within: NAME_LENGTH_MIN..NAME_LENGTH_MAX,
too_short: ts("is too short (minimum is %{min} characters)", min: NAME_LENGTH_MIN),
too_long: ts("is too long (maximum is %{max} characters)", max: NAME_LENGTH_MAX)
validates_uniqueness_of :name, scope: :user_id, case_sensitive: false
validates_format_of :name,
message: ts('can contain letters, numbers, spaces, underscores, and dashes.'),
with: /\A[\p{Word} -]+\Z/u
validates_format_of :name,
message: ts('must contain at least one letter or number.'),
with: /\p{Alnum}/u
validates_length_of :description, allow_blank: true, maximum: DESCRIPTION_MAX,
too_long: ts("must be less than %{max} characters long.", max: DESCRIPTION_MAX)
validates_length_of :icon_alt_text, allow_blank: true, maximum: ArchiveConfig.ICON_ALT_MAX,
too_long: ts("must be less than %{max} characters long.", max: ArchiveConfig.ICON_ALT_MAX)
validates_length_of :icon_comment_text, allow_blank: true, maximum: ArchiveConfig.ICON_COMMENT_MAX,
too_long: ts("must be less than %{max} characters long.", max: ArchiveConfig.ICON_COMMENT_MAX)
after_update :check_default_pseud
after_update :expire_caches
after_commit :reindex_creations
scope :on_works, lambda {|owned_works|
select("DISTINCT pseuds.*").
joins(:works).
where(works: {id: owned_works.collect(&:id)}).
order(:name)
}
scope :with_works, -> {
select("pseuds.*, count(pseuds.id) AS work_count").
joins(:works).
group(:id).
order(:name)
}
scope :with_posted_works, -> { with_works.merge(Work.visible_to_registered_user) }
scope :with_public_works, -> { with_works.merge(Work.visible_to_all) }
scope :with_bookmarks, -> {
select("pseuds.*, count(pseuds.id) AS bookmark_count").
joins(:bookmarks).
group(:id).
order(:name)
}
# conditions: {bookmarks: {private: false, hidden_by_admin: false}},
scope :with_public_bookmarks, -> { with_bookmarks.merge(Bookmark.is_public) }
scope :with_public_recs, -> {
select("pseuds.*, count(pseuds.id) AS rec_count").
joins(:bookmarks).
group(:id).
order(:name).
merge(Bookmark.is_public.recs)
}
scope :alphabetical, -> { order(:name) }
scope :starting_with, lambda {|letter| where('SUBSTR(name,1,1) = ?', letter)}
scope :coauthor_of, lambda {|pseuds|
select("pseuds.*").
joins("LEFT JOIN creatorships ON creatorships.pseud_id = pseuds.id
LEFT JOIN creatorships c2 ON c2.creation_id = creatorships.creation_id").
where(["creatorships.creation_type = 'Work' AND
c2.creation_type = 'Work' AND
c2.pseud_id IN (?) AND
creatorships.pseud_id NOT IN (?)",
pseuds.collect(&:id),
pseuds.collect(&:id)]).
group("pseuds.id").
includes(:user)
}
def self.not_orphaned
where("user_id != ?", User.orphan_account)
end
# Enigel Dec 12 08: added sort method
# sorting by pseud name or by login name in case of equality
def <=>(other)
(self.name.downcase <=> other.name.downcase) == 0 ? (self.user_name.downcase <=> other.user_name.downcase) : (self.name.downcase <=> other.name.downcase)
end
# For use with the work and chapter forms
def user_name
self.user.login
end
def to_param
name
end
# Gets the number of works by this user that the current user can see
def visible_works_count
if User.current_user.nil?
self.works.posted.unhidden.unrestricted.count
else
self.works.posted.unhidden.count
end
end
# Gets the number of recs by this user
def visible_recs_count
self.recs.is_public.size
end
scope :public_work_count_for, -> (pseud_ids) {
select('pseuds.id, count(pseuds.id) AS work_count')
.joins(:works)
.where(
pseuds: { id: pseud_ids }, works: { posted: true, hidden_by_admin: false, restricted: false }
).group('pseuds.id')
}
scope :posted_work_count_for, -> (pseud_ids) {
select('pseuds.id, count(pseuds.id) AS work_count')
.joins(:works)
.where(
pseuds: { id: pseud_ids }, works: { posted: true, hidden_by_admin: false }
).group('pseuds.id')
}
scope :public_rec_count_for, -> (pseud_ids) {
select('pseuds.id, count(pseuds.id) AS rec_count')
.joins(:bookmarks)
.where(
pseuds: { id: pseud_ids }, bookmarks: { private: false, hidden_by_admin: false, rec: true }
)
.group('pseuds.id')
}
def self.rec_counts_for_pseuds(pseuds)
if pseuds.blank?
{}
else
pseuds_with_counts = Pseud.public_rec_count_for(pseuds.collect(&:id))
count_hash = {}
pseuds_with_counts.each {|p| count_hash[p.id] = p.rec_count.to_i}
count_hash
end
end
def self.work_counts_for_pseuds(pseuds)
if pseuds.blank?
{}
else
if User.current_user.nil?
pseuds_with_counts = Pseud.public_work_count_for(pseuds.collect(&:id))
else
pseuds_with_counts = Pseud.posted_work_count_for(pseuds.collect(&:id))
end
count_hash = {}
pseuds_with_counts.each {|p| count_hash[p.id] = p.work_count.to_i}
count_hash
end
end
def unposted_works
@unposted_works = self.works.where(posted: false).order(created_at: :desc)
end
# look up by byline
scope :by_byline, -> (byline) {
joins(:user)
.where('users.login = ? AND pseuds.name = ?',
(byline.include?('(') ? byline.split('(', 2)[1].strip.chop : byline),
(byline.include?('(') ? byline.split('(', 2)[0].strip : byline)
)
}
# Produces a byline that indicates the user's name if pseud is not unique
def byline
(name != user_name) ? name + " (" + user_name + ")" : name
end
# get the former byline
def byline_was
past_name = name_was.blank? ? name : name_was
# if we have a user and their login has changed get the old one
past_user_name = user.blank? ? "" : (user.login_was.blank? ? user.login : user.login_was)
(past_name != past_user_name) ? "#{past_name} (#{past_user_name})" : past_name
end
# Parse a string of the "pseud.name (user.login)" format into a pseud
def self.parse_byline(byline, options = {})
pseud_name = ""
login = ""
if byline.include?("(")
pseud_name, login = byline.split('(', 2)
pseud_name = pseud_name.strip
login = login.strip.chop
conditions = ['users.login = ? AND pseuds.name = ?', login, pseud_name]
else
pseud_name = byline.strip
if options[:assume_matching_login]
conditions = ['users.login = ? AND pseuds.name = ?', pseud_name, pseud_name]
else
conditions = ['pseuds.name = ?', pseud_name]
end
end
Pseud.joins(:user).where(conditions)
end
# Takes a comma-separated list of bylines
# Returns a hash containing an array of pseuds and an array of bylines that couldn't be found
def self.parse_bylines(list, options = {})
valid_pseuds, ambiguous_pseuds, failures = [], {}, []
bylines = list.split ","
for byline in bylines
pseuds = Pseud.parse_byline(byline, options)
banned_pseuds = pseuds.select { |pseud| pseud.user.banned? || pseud.user.suspended? }
if banned_pseuds.present?
pseuds = pseuds - banned_pseuds
banned_pseuds = banned_pseuds.map(&:byline)
end
if pseuds.length == 1
valid_pseuds << pseuds.first
elsif pseuds.length > 1
ambiguous_pseuds[pseuds.first.name] = pseuds
else
failures << byline.strip
end
end
{
pseuds: valid_pseuds,
ambiguous_pseuds: ambiguous_pseuds,
invalid_pseuds: failures,
banned_pseuds: banned_pseuds
}
end
## AUTOCOMPLETE
# set up autocomplete and override some methods
include AutocompleteSource
def autocomplete_prefixes
[ "autocomplete_pseud" ]
end
def autocomplete_value
"#{id}#{AUTOCOMPLETE_DELIMITER}#{byline}"
end
# This method is for use in before_* callbacks
def autocomplete_value_was
"#{id}#{AUTOCOMPLETE_DELIMITER}#{byline_was}"
end
# See byline_before_last_save for the reasoning behind why both this and
# autocomplete_value_was exist in this model
#
# This method is for use in after_* callbacks
def autocomplete_value_before_last_save
"#{id}#{AUTOCOMPLETE_DELIMITER}#{byline_before_last_save}"
end
def byline_before_last_save
past_name = name_before_last_save.blank? ? name : name_before_last_save
# In this case, self belongs to a user that has already been saved
# during it's (self's) callback cycle, which means we need to
# look *back* at the user's [attributes]_before_last_save, since
# [attribute]_was for the pseud's user will behave as if this were an
# after_* callback on the user, instead of a before_* callback on self.
#
# see psued_sweeper.rb:13 for more context
#
past_user_name = user.blank? ? "" : (user.login_before_last_save.blank? ? user.login : user.login_before_last_save)
(past_name != past_user_name) ? "#{past_name} (#{past_user_name})" : past_name
end
# This method is for removing stale autocomplete records in a before_*
# callback, such as the one used in PseudSweeper
#
# This is a particular case for the Pseud model
def remove_stale_from_autocomplete_before_save
Rails.logger.debug "Removing stale from autocomplete: #{autocomplete_search_string_was}"
self.class.remove_from_autocomplete(self.autocomplete_search_string_was, self.autocomplete_prefixes, self.autocomplete_value_was)
end
## END AUTOCOMPLETE
def creations
self.works + self.chapters + self.series
end
def replace_me_with_default
self.creations.each {|creation| change_ownership(creation, self.user.default_pseud) }
Comment.where("pseud_id = #{self.id}").update_all("pseud_id = #{self.user.default_pseud.id}") unless self.comments.blank?
# NB: updates the kudos to use the new default pseud, but the cache will not expire
Kudo.where("pseud_id = #{self.id}").update_all("pseud_id = #{self.user.default_pseud.id}") unless self.kudos.blank?
change_collections_membership
change_gift_recipients
change_challenge_participation
self.destroy
end
# Change the ownership of a creation from one pseud to another
# Options: skip_series -- if you begin by changing ownership of the series, you don't
# want to go back up again and get stuck in a loop
def change_ownership(creation, pseud, options={})
# Should only transfer creatorship if we're a co-creator.
if creation.pseuds.include?(self)
creation.pseuds.delete(self)
creation.pseuds << pseud unless pseud.nil? || creation.pseuds.include?(pseud)
end
if creation.is_a?(Work)
creation.chapters.each {|chapter| self.change_ownership(chapter, pseud)}
unless options[:skip_series]
for series in creation.series
if series.works.count > 1 && (series.works - [creation]).collect(&:pseuds).flatten.include?(self)
series.pseuds << pseud rescue nil
else
self.change_ownership(series, pseud)
end
end
end
comments = creation.total_comments.where("comments.pseud_id = ?", self.id)
comments.each do |comment|
comment.update_attribute(:pseud_id, pseud.id)
end
elsif creation.is_a?(Series) && options[:skip_series]
creation.works.each {|work| self.change_ownership(work, pseud)}
end
# make sure changes affect caching/search/author fields
creation.save rescue nil
end
def change_membership(collection, new_pseud)
self.collection_participants.in_collection(collection).each do |cparticipant|
cparticipant.pseud = new_pseud
cparticipant.save
end
end
def change_challenge_participation
# We want to update all prompts associated with this pseud, but although
# each prompt contains a pseud_id column, they're not indexed on it. That
# means doing the search Prompt.where(pseud_id: self.id) would require
# searching all rows of the prompts table. So instead, we do a join on the
# challenge_signups table and look up prompts whose ChallengeSignup has the
# pseud_id that we want to change.
Prompt.joins(:challenge_signup).
where("challenge_signups.pseud_id = #{id}").
update_all("prompts.pseud_id = #{user.default_pseud.id}")
ChallengeSignup.where("pseud_id = #{self.id}").update_all("pseud_id = #{self.user.default_pseud.id}")
ChallengeAssignment.where("pinch_hitter_id = #{self.id}").update_all("pinch_hitter_id = #{self.user.default_pseud.id}")
return
end
def change_gift_recipients
Gift.where("pseud_id = #{self.id}").update_all("pseud_id = #{self.user.default_pseud.id}")
end
def change_bookmarks_ownership
Bookmark.where("pseud_id = #{self.id}").update_all("pseud_id = #{self.user.default_pseud.id}")
end
def change_collections_membership
CollectionParticipant.where("pseud_id = #{self.id}").update_all("pseud_id = #{self.user.default_pseud.id}")
end
def check_default_pseud
if !self.is_default? && self.user.pseuds.to_enum.find(&:is_default?) == nil
default_pseud = self.user.pseuds.select{|ps| ps.name.downcase == self.user_name.downcase}.first
default_pseud.update_attribute(:is_default, true)
end
end
def expire_caches
if saved_change_to_name?
self.works.each{ |work| work.touch }
end
end
# Delete current icon (thus reverting to archive default icon)
def delete_icon=(value)
@delete_icon = !value.to_i.zero?
end
def delete_icon
!!@delete_icon
end
alias_method :delete_icon?, :delete_icon
def clear_icon
self.icon = nil if delete_icon? && !icon.dirty?
end
#################################
## SEARCH #######################
#################################
def collection_ids
collections.pluck(:id)
end
def document_json
PseudIndexer.new({}).document(self)
end
def should_reindex_creations?
pertinent_attributes = %w[id name]
destroyed? || (saved_changes.keys & pertinent_attributes).present?
end
# If the pseud gets renamed, anything indexed with the old name needs to be reindexed:
# works, series, bookmarks.
def reindex_creations
return unless should_reindex_creations?
IndexQueue.enqueue_ids(Work, works.pluck(:id), :main)
IndexQueue.enqueue_ids(Bookmark, bookmarks.pluck(:id), :main)
IndexQueue.enqueue_ids(Series, series.pluck(:id), :main)
end
end