Class: User

Inherits:
ApplicationRecord show all
Extended by:
OmniauthCallbacks
Includes:
BaseModel, Redis::Objects, Searchable
Defined in:
app/models/user.rb,
app/models/user/omniauth_callbacks.rb

Defined Under Namespace

Modules: OmniauthCallbacks

Constant Summary collapse

ALLOW_LOGIN_CHARS_REGEXP =
/\A[A-Za-z0-9\-\_\.]+\z/
ACCESSABLE_ATTRS =
[:name, :email_public, :location, :company, :bio, :website, :github, :twitter,
:tagline, :avatar, :by, :current_password, :password, :password_confirmation,
:_rucaptcha]
STATE =
{
  # 软删除
  deleted: -1,
  # 正常
  normal: 1,
  # 屏蔽
  blocked: 2
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from OmniauthCallbacks

new_from_provider_data

Methods included from BaseModel

#pull, #push

Instance Attribute Details

#password_confirmationObject

Returns the value of attribute password_confirmation


29
30
31
# File 'app/models/user.rb', line 29

def password_confirmation
  @password_confirmation
end

Class Method Details

.fetch_github_repositories(user_id) ⇒ Object


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
# File 'app/models/user.rb', line 358

def self.fetch_github_repositories(user_id)
  user = User.find_by_id(user_id)
  return false if user.blank?

   = user.github || user.

  url = "https://api.github.com/users/#{}/repos?type=owner&sort=pushed&client_id=#{Setting.github_token}&client_secret=#{Setting.github_secret}"
  begin
    json = Timeout.timeout(10) do
      open(url).read
    end
  rescue => e
    Rails.logger.error("GitHub Repositiory fetch Error: #{e}")
    items = []
    $file_store.write(user.github_repositories_cache_key, items, expires_in: 1.minutes)
    return false
  end

  items = JSON.parse(json)
  items = items.collect do |a1|
    {
      name: a1['name'],
      url: a1['html_url'],
      watchers: a1['watchers'],
      language: a1['language'],
      description: a1['description']
    }
  end
  items = items.sort { |a1, a2| a2[:watchers] <=> a1[:watchers] }.take(10)
  $file_store.write(user.github_repositories_cache_key, items, expires_in: 15.days)
  items
end

.find_by_email(email) ⇒ Object


191
192
193
# File 'app/models/user.rb', line 191

def self.find_by_email(email)
  fetch_by_uniq_keys(email: email)
end

.find_by_login_or_email(login_or_email) ⇒ Object


205
206
207
208
# File 'app/models/user.rb', line 205

def self.()
   = .downcase
  fetch_by_uniq_keys(login: ) || fetch_by_uniq_keys(email: )
end

.find_for_database_authentication(warden_conditions) ⇒ Object


210
211
212
213
214
215
# File 'app/models/user.rb', line 210

def self.find_for_database_authentication(warden_conditions)
  conditions = warden_conditions.dup
   = conditions.delete(:login)
  .downcase!
  where(conditions.to_h).where(["lower(login) = :value OR lower(email) = :value", { value:  }]).first
end

.find_login(slug) ⇒ Object


199
200
201
202
203
# File 'app/models/user.rb', line 199

def self.(slug)
  return nil unless slug =~ ALLOW_LOGIN_CHARS_REGEXP
  slug = slug.downcase
  fetch_by_uniq_keys(login: slug)
end

.find_login!(slug) ⇒ Object


195
196
197
# File 'app/models/user.rb', line 195

def self.find_login!(slug)
  (slug) || fail(ActiveRecord::RecordNotFound.new(slug: slug))
end

Instance Method Details

#admin?Boolean

是否是管理员

Returns:

  • (Boolean)

109
110
111
# File 'app/models/user.rb', line 109

def admin?
  Setting.admin_emails.include?(email)
end

#avatar?Boolean

Returns:

  • (Boolean)

501
502
503
# File 'app/models/user.rb', line 501

def avatar?
  self[:avatar].present?
end

#bind?(provider) ⇒ Boolean

Returns:

  • (Boolean)

222
223
224
# File 'app/models/user.rb', line 222

def bind?(provider)
  authorizations.collect(&:provider).include?(provider)
end

#bind_service(response) ⇒ Object


226
227
228
229
230
# File 'app/models/user.rb', line 226

def bind_service(response)
  provider = response['provider']
  uid = response['uid'].to_s
  authorizations.create(provider: provider, uid: uid)
end

#block_node(node_id) ⇒ Object


401
402
403
404
405
# File 'app/models/user.rb', line 401

def block_node(node_id)
  new_node_id = node_id.to_i
  return false if blocked_node_ids.include?(new_node_id)
  push(blocked_node_ids: new_node_id)
end

#block_user(user_id) ⇒ Object


421
422
423
424
425
# File 'app/models/user.rb', line 421

def block_user(user_id)
  user_id = user_id.to_i
  return false if self.blocked_user?(user_id)
  push(blocked_user_ids: user_id)
end

#blocked?Boolean

Returns:

  • (Boolean)

137
138
139
# File 'app/models/user.rb', line 137

def blocked?
  state == STATE[:blocked]
end

#blocked_user?(user) ⇒ Boolean

Returns:

  • (Boolean)

416
417
418
419
# File 'app/models/user.rb', line 416

def blocked_user?(user)
  uid = user.is_a?(User) ? user.id : user
  blocked_user_ids.include?(uid)
end

#blocked_users?Boolean

Returns:

  • (Boolean)

412
413
414
# File 'app/models/user.rb', line 412

def blocked_users?
  blocked_user_ids.count > 0
end

#calendar_dataObject


510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'app/models/user.rb', line 510

def calendar_data
  user = self
  Rails.cache.fetch(["user", self.id, 'calendar_data', Date.today, 'by-months']) do
    date_from = 12.months.ago.beginning_of_month.to_date
    dates = (date_from..Date.today).to_a
    replies = user.replies.where('created_at > ?', date_from)
                           .group('date(created_at)')
                           .select('date(created_at) as date, count(id) as total_amount').all
    timestamps = {}
    replies.map do |reply|
      timestamps[reply['date'].to_time.to_i.to_s] = reply['total_amount']
    end
    timestamps
  end
end

#deleted?Boolean

Returns:

  • (Boolean)

141
142
143
# File 'app/models/user.rb', line 141

def deleted?
  state == STATE[:deleted]
end

#email=(val) ⇒ Object


69
70
71
72
# File 'app/models/user.rb', line 69

def email=(val)
  self.email_md5 = Digest::MD5.hexdigest(val || '')
  self[:email] = val
end

#email_locked?Boolean

Returns:

  • (Boolean)

506
507
508
# File 'app/models/user.rb', line 506

def email_locked?
  self.email.index('@example.com') == nil
end

#ensure_private_token!Object


397
398
399
# File 'app/models/user.rb', line 397

def ensure_private_token!
  update_private_token if private_token.blank?
end

#favorite_topic(topic_id) ⇒ Object

收藏话题


304
305
306
307
308
309
310
# File 'app/models/user.rb', line 304

def favorite_topic(topic_id)
  return false if topic_id.blank?
  topic_id = topic_id.to_i
  return false if favorited_topic?(topic_id)
  push(favorite_topic_ids: topic_id)
  true
end

#favorite_topics_countObject


325
326
327
# File 'app/models/user.rb', line 325

def favorite_topics_count
  favorite_topic_ids.size
end

#favorited_topic?(topic_id) ⇒ Boolean

是否收藏过话题

Returns:

  • (Boolean)

321
322
323
# File 'app/models/user.rb', line 321

def favorited_topic?(topic_id)
  favorite_topic_ids.include?(topic_id)
end

#favorites_countObject


462
463
464
# File 'app/models/user.rb', line 462

def favorites_count
  favorite_topic_ids.count
end

#filter_readed_topics(topics) ⇒ Object


239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'app/models/user.rb', line 239

def filter_readed_topics(topics)
  t1 = Time.now
  return [] if topics.blank?
  cache_keys = topics.map { |t| "user:#{id}:topic_read:#{t.id}" }
  results = Rails.cache.read_multi(*cache_keys)
  ids = []
  topics.each do |topic|
    val = results["user:#{id}:topic_read:#{topic.id}"]
    if (val == (topic.last_reply_id || -1))
      ids << topic.id
    end
  end
  t2 = Time.now
  logger.info "  User filter_readed_topics (#{(t2 - t1) * 1000}ms)"
  ids
end

#follow_user(user) ⇒ Object


437
438
439
440
441
442
443
444
# File 'app/models/user.rb', line 437

def follow_user(user)
  return false if user.blank?
  self.transaction do
    self.push(following_ids: user.id)
    user.push(follower_ids: self.id)
  end
  Notification.notify_follow(user.id, self.id)
end

#followed?(user) ⇒ Boolean

Returns:

  • (Boolean)

432
433
434
435
# File 'app/models/user.rb', line 432

def followed?(user)
  uid = user.is_a?(User) ? user.id : user
  following_ids.include?(uid)
end

#followersObject


61
62
63
# File 'app/models/user.rb', line 61

def followers
  User.where(id: self.follower_ids)
end

#followers_countObject


446
447
448
# File 'app/models/user.rb', line 446

def followers_count
  follower_ids.count
end

#followingObject


57
58
59
# File 'app/models/user.rb', line 57

def following
  User.where(id: self.following_ids)
end

#following_countObject


450
451
452
# File 'app/models/user.rb', line 450

def following_count
  following_ids.count
end

#fullnameObject


103
104
105
106
# File 'app/models/user.rb', line 103

def fullname
  return  if name.blank?
  "#{} (#{name})"
end

#github_repositoriesObject

GitHub 项目


344
345
346
347
348
349
350
351
352
# File 'app/models/user.rb', line 344

def github_repositories
  cache_key = github_repositories_cache_key
  items = $file_store.read(cache_key)
  if items.nil?
    GithubRepoFetcherJob.perform_later(id)
    items = []
  end
  items
end

#github_repositories_cache_keyObject


354
355
356
# File 'app/models/user.rb', line 354

def github_repositories_cache_key
  "github-repos:#{github}"
end

#github_urlObject


88
89
90
91
# File 'app/models/user.rb', line 88

def github_url
  return '' if github.blank?
  "https://github.com/#{github.split('/').last}"
end

#google_profile_urlObject


98
99
100
101
# File 'app/models/user.rb', line 98

def google_profile_url
  return '' if email.blank? || !email.match(/gmail\.com/)
  "http://www.google.com/profiles/#{email.split('@').first}"
end

#has_role?(role) ⇒ Boolean

Returns:

  • (Boolean)

145
146
147
148
149
150
151
152
153
# File 'app/models/user.rb', line 145

def has_role?(role)
  case role
  when :admin then admin?
  when :wiki_editor then wiki_editor?
  when :site_editor then site_editor?
  when :member then state == STATE[:normal]
  else false
  end
end

#hr?Boolean

Returns:

  • (Boolean)

129
130
131
# File 'app/models/user.rb', line 129

def hr?
  hr == true
end

#large_avatar_urlObject


493
494
495
496
497
498
499
# File 'app/models/user.rb', line 493

def large_avatar_url
  if self[:avatar].present?
    self.avatar.url(:large)
  else
    self.letter_avatar_url(240)
  end
end

#letter_avatar_url(size) ⇒ Object


487
488
489
490
491
# File 'app/models/user.rb', line 487

def letter_avatar_url(size)
  path = LetterAvatar.generate(self., size).sub('public/','/')

  "#{Setting.protocol}://#{Setting.domain}#{path}"
end

#levelObject

用户的账号类型


467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'app/models/user.rb', line 467

def level
  if admin?
    return 'admin'
  elsif verified?
    return 'vip'
  elsif hr?
    return 'hr'
  elsif blocked?
    return 'blocked'
  elsif newbie?
    return 'newbie'
  else
    return 'normal'
  end
end

#level_nameObject


483
484
485
# File 'app/models/user.rb', line 483

def level_name
  return I18n.t("common.#{level}_user")
end

#like(likeable) ⇒ Object

收藏东西


278
279
280
281
282
283
284
285
# File 'app/models/user.rb', line 278

def like(likeable)
  return false if likeable.blank?
  return false if liked?(likeable)
  likeable.transaction do
    likeable.push(liked_user_ids: id)
    likeable.increment!(:likes_count)
  end
end

#liked?(likeable) ⇒ Boolean

是否喜欢过

Returns:

  • (Boolean)

299
300
301
# File 'app/models/user.rb', line 299

def liked?(likeable)
  likeable.liked_by_user?(self) || likeable.user_id == self.id
end

#newbie?Boolean

是否能发帖

Returns:

  • (Boolean)

124
125
126
127
# File 'app/models/user.rb', line 124

def newbie?
  return false if verified? or hr?
  created_at > 1.week.ago
end

#password_required?Boolean

Returns:

  • (Boolean)

80
81
82
# File 'app/models/user.rb', line 80

def password_required?
  (authorizations.empty? || !password.blank?) && super
end

#profile_urlObject


84
85
86
# File 'app/models/user.rb', line 84

def profile_url
  "/#{}"
end

#read_topic(topic, opts = {}) ⇒ Object

将 topic 的最后回复设置为已读


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'app/models/user.rb', line 257

def read_topic(topic, opts = {})
  return if topic.blank?
  return if self.topic_read?(topic)

  opts[:replies_ids] ||= topic.replies.pluck(:id)

  any_sql = "
    (target_type = 'Topic' AND target_id = ?) or
    (target_type = 'Reply' AND target_id in (?))
  "
  notifications.unread
    .where(any_sql, topic.id, opts[:replies_ids])
    .update_all(read_at: Time.now)
  Notification.realtime_push_to_client(self)

  # 处理 last_reply_id 是空的情况
  last_reply_id = topic.last_reply_id || -1
  Rails.cache.write("user:#{id}:topic_read:#{topic.id}", last_reply_id)
end

#send_devise_notification(notification, *args) ⇒ Object

Override Devise to send mails with async


218
219
220
# File 'app/models/user.rb', line 218

def send_devise_notification(notification, *args)
  devise_mailer.send(notification, self, *args).deliver_later
end

#send_welcome_mailObject


162
163
164
# File 'app/models/user.rb', line 162

def send_welcome_mail
  UserMailer.welcome(id).deliver_later
end

#site_editor?Boolean

回帖大于 150 的才有酷站的发布权限

Returns:

  • (Boolean)

119
120
121
# File 'app/models/user.rb', line 119

def site_editor?
  self.admin? || replies_count >= 100
end

#soft_deleteObject

软删除 只是把用户信息修改了


331
332
333
334
335
336
337
338
339
340
341
# File 'app/models/user.rb', line 331

def soft_delete
  # assuming you have deleted_at column added already
  self.bio = ''
  self.website = ''
  self.github = ''
  self.tagline = ''
  self.location = ''
  self.authorizations = []
  self.state = STATE[:deleted]
  save(validate: false)
end

#store_locationObject


168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'app/models/user.rb', line 168

def store_location
  if self.location_changed?
    if !location.blank?
      old_location = Location.location_find_by_name(self.location_was)
      old_location.decrement!(:users_count) unless old_location.blank?
      location = Location.location_find_or_create_by_name(self.location)
      location.increment!(:users_count)
      self.location_id = (location.blank? ? nil : location.id)
    else
      self.location_id = nil
    end
  end
end

#temp_access_tokenObject


74
75
76
77
78
# File 'app/models/user.rb', line 74

def temp_access_token
  Rails.cache.fetch("user-#{id}-temp_access_token-#{Time.now.strftime('%Y%m%d')}") do
    SecureRandom.hex
  end
end

#to_paramObject


65
66
67
# File 'app/models/user.rb', line 65

def to_param
  
end

#topic_read?(topic) ⇒ Boolean

是否读过 topic 的最近更新

Returns:

  • (Boolean)

233
234
235
236
237
# File 'app/models/user.rb', line 233

def topic_read?(topic)
  # 用 last_reply_id 作为 cache key ,以便不热门的数据自动被 Memcached 挤掉
  last_reply_id = topic.last_reply_id || -1
  Rails.cache.read("user:#{id}:topic_read:#{topic.id}") == last_reply_id
end

#twitter_urlObject


93
94
95
96
# File 'app/models/user.rb', line 93

def twitter_url
  return '' if twitter.blank?
  "https://twitter.com/#{twitter}"
end

#unblock_node(node_id) ⇒ Object


407
408
409
410
# File 'app/models/user.rb', line 407

def unblock_node(node_id)
  new_node_id = node_id.to_i
  pull(blocked_node_ids: new_node_id)
end

#unblock_user(user_id) ⇒ Object


427
428
429
430
# File 'app/models/user.rb', line 427

def unblock_user(user_id)
  user_id = user_id.to_i
  pull(blocked_user_ids: user_id)
end

#unfavorite_topic(topic_id) ⇒ Object

取消对话题的收藏


313
314
315
316
317
318
# File 'app/models/user.rb', line 313

def unfavorite_topic(topic_id)
  return false if topic_id.blank?
  topic_id = topic_id.to_i
  pull(favorite_topic_ids: topic_id)
  true
end

#unfollow_user(user) ⇒ Object


454
455
456
457
458
459
460
# File 'app/models/user.rb', line 454

def unfollow_user(user)
  return false if user.blank?
  self.transaction do
    self.pull(following_ids: user.id)
    user.pull(follower_ids: self.id)
  end
end

#unlike(likeable) ⇒ Object

取消收藏


288
289
290
291
292
293
294
295
296
# File 'app/models/user.rb', line 288

def unlike(likeable)
  return false if likeable.blank?
  return false unless liked?(likeable)
  return false if likeable.user_id == self.id
  likeable.transaction do
    likeable.pull(liked_user_ids: id)
    likeable.decrement!(:likes_count)
  end
end

#update_private_tokenObject

重新生成 Private Token


392
393
394
395
# File 'app/models/user.rb', line 392

def update_private_token
  random_key = "#{SecureRandom.hex(10)}:#{id}"
  update_attribute(:private_token, random_key)
end

#update_with_password(params = {}) ⇒ Object


182
183
184
185
186
187
188
189
# File 'app/models/user.rb', line 182

def update_with_password(params = {})
  if !params[:current_password].blank? || !params[:password].blank? || !params[:password_confirmation].blank?
    super
  else
    params.delete(:current_password)
    update_without_password(params)
  end
end

#verified?Boolean

Returns:

  • (Boolean)

133
134
135
# File 'app/models/user.rb', line 133

def verified?
  verified == true
end

#wiki_editor?Boolean

是否有 Wiki 维护权限

Returns:

  • (Boolean)

114
115
116
# File 'app/models/user.rb', line 114

def wiki_editor?
  self.admin? || verified == true
end