Class: UserUpdater

Inherits:
Object
  • Object
show all
Defined in:
app/services/user_updater.rb

Constant Summary collapse

CATEGORY_IDS =
{
  watched_first_post_category_ids: :watching_first_post,
  watched_category_ids: :watching,
  tracked_category_ids: :tracking,
  regular_category_ids: :regular,
  muted_category_ids: :muted,
}
TAG_NAMES =
{
  watching_first_post_tags: :watching_first_post,
  watched_tags: :watching,
  tracked_tags: :tracking,
  muted_tags: :muted,
}
OPTION_ATTR =
%i[
  mailing_list_mode
  mailing_list_mode_frequency
  email_digests
  email_level
  email_messages_level
  external_links_in_new_tab
  enable_quoting
  enable_defer
  color_scheme_id
  dark_scheme_id
  dynamic_favicon
  automatically_unpin_topics
  digest_after_minutes
  new_topic_duration_minutes
  auto_track_topics_after_msecs
  notification_level_when_replying
  email_previous_replies
  email_in_reply_to
  like_notification_frequency
  include_tl0_in_digests
  theme_ids
  allow_private_messages
  enable_allowed_pm_users
  homepage_id
  hide_profile_and_presence
  text_size
  title_count_mode
  timezone
  skip_new_user_tips
  seen_popups
  default_calendar
  bookmark_auto_delete_preference
  sidebar_link_to_filtered_list
  sidebar_show_count_of_new_items
  watched_precedence_over_muted
]
NOTIFICATION_SCHEDULE_ATTRS =
-> do
  attrs = [:enabled]
  7.times do |n|
    attrs.push("day_#{n}_start_time".to_sym)
    attrs.push("day_#{n}_end_time".to_sym)
  end
  { user_notification_schedule: attrs }
end.call

Instance Method Summary collapse

Constructor Details

#initialize(actor, user) ⇒ UserUpdater

Returns a new instance of UserUpdater.



66
67
68
69
70
71
# File 'app/services/user_updater.rb', line 66

def initialize(actor, user)
  @user = user
  @user_guardian = Guardian.new(user)
  @guardian = Guardian.new(actor)
  @actor = actor
end

Instance Method Details

#update(attributes = {}) ⇒ Object



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
# File 'app/services/user_updater.rb', line 73

def update(attributes = {})
   = user.
  .dismissed_banner_key = attributes[:dismissed_banner_key] if attributes[
    :dismissed_banner_key
  ].present?
  unless SiteSetting.enable_discourse_connect && SiteSetting.discourse_connect_overrides_bio
    .bio_raw = attributes.fetch(:bio_raw) { .bio_raw }
  end

  unless SiteSetting.enable_discourse_connect && SiteSetting.discourse_connect_overrides_location
    .location = attributes.fetch(:location) { .location }
  end

  unless SiteSetting.enable_discourse_connect && SiteSetting.discourse_connect_overrides_website
    .website = format_url(attributes.fetch(:website) { .website })
  end

  if attributes[:profile_background_upload_url] == "" ||
       !guardian.can_upload_profile_header?(user)
    .profile_background_upload_id = nil
  elsif upload = Upload.get_from_url(attributes[:profile_background_upload_url])
    .profile_background_upload_id = upload.id
  end

  if attributes[:card_background_upload_url] == "" ||
       !guardian.can_upload_user_card_background?(user)
    .card_background_upload_id = nil
  elsif upload = Upload.get_from_url(attributes[:card_background_upload_url])
    .card_background_upload_id = upload.id
  end

  if attributes[:user_notification_schedule]
    user_notification_schedule =
      user.user_notification_schedule || UserNotificationSchedule.new(user: user)
    user_notification_schedule.assign_attributes(attributes[:user_notification_schedule])
  end

  old_user_name = user.name.present? ? user.name : ""

  user.name = attributes.fetch(:name) { user.name } if guardian.can_edit_name?(user)

  user.locale = attributes.fetch(:locale) { user.locale }
  user.date_of_birth = attributes.fetch(:date_of_birth) { user.date_of_birth }

  if attributes[:title] && attributes[:title] != user.title &&
       guardian.can_grant_title?(user, attributes[:title])
    user.title = attributes[:title]
  end

  if SiteSetting.user_selected_primary_groups && attributes[:primary_group_id] &&
       attributes[:primary_group_id] != user.primary_group_id &&
       guardian.can_use_primary_group?(user, attributes[:primary_group_id])
    user.primary_group_id = attributes[:primary_group_id]
  elsif SiteSetting.user_selected_primary_groups && attributes[:primary_group_id] &&
        attributes[:primary_group_id].blank?
    user.primary_group_id = nil
  end

  if attributes[:flair_group_id] && attributes[:flair_group_id] != user.flair_group_id &&
       (
         attributes[:flair_group_id].blank? ||
           guardian.can_use_flair_group?(user, attributes[:flair_group_id])
       )
    user.flair_group_id = attributes[:flair_group_id]
  end

  if @guardian.can_change_tracking_preferences?(user)
    CATEGORY_IDS.each do |attribute, level|
      if ids = attributes[attribute]
        CategoryUser.batch_set(user, level, ids)
      end
    end

    TAG_NAMES.each do |attribute, level|
      if attributes.has_key?(attribute)
        TagUser.batch_set(user, level, attributes[attribute]&.split(",") || [])
      end
    end
  end

  save_options = false

  # special handling for theme_id cause we need to bump a sequence number
  if attributes.key?(:theme_ids)
    attributes[:theme_ids].reject!(&:blank?)
    attributes[:theme_ids].map!(&:to_i)

    if @user_guardian.allow_themes?(attributes[:theme_ids])
      user.user_option.theme_key_seq += 1 if user.user_option.theme_ids != attributes[:theme_ids]
    else
      attributes.delete(:theme_ids)
    end
  end

  if attributes.key?(:text_size)
    user.user_option.text_size_seq += 1 if user.user_option.text_size.to_s !=
      attributes[:text_size]
  end

  OPTION_ATTR.each do |attribute|
    if attributes.key?(attribute)
      save_options = true

      if [true, false].include?(user.user_option.public_send(attribute))
        val = attributes[attribute].to_s == "true"
        user.user_option.public_send("#{attribute}=", val)
      else
        user.user_option.public_send("#{attribute}=", attributes[attribute])
      end
    end
  end

  if attributes.key?(:skip_new_user_tips) && user.user_option.skip_new_user_tips
    user.user_option.seen_popups = [-1]
  end

  # automatically disable digests when mailing_list_mode is enabled
  user.user_option.email_digests = false if user.user_option.mailing_list_mode

  fields = attributes[:custom_fields]
  user.custom_fields = user.custom_fields.merge(fields) if fields.present?

  saved = nil

  User.transaction do
    update_muted_users(attributes[:muted_usernames]) if attributes.key?(:muted_usernames)

    if attributes.key?(:allowed_pm_usernames)
      update_allowed_pm_users(attributes[:allowed_pm_usernames])
    end

    if attributes.key?(:discourse_connect)
      update_discourse_connect(attributes[:discourse_connect])
    end

    if attributes.key?(:user_associated_accounts)
      updated_associated_accounts(attributes[:user_associated_accounts])
    end

    if attributes.key?(:sidebar_category_ids)
      SidebarSectionLinksUpdater.update_category_section_links(
        user,
        category_ids:
          Category
            .secured(@user_guardian)
            .where(id: attributes[:sidebar_category_ids])
            .pluck(:id),
      )
    end

    if attributes.key?(:sidebar_tag_names) && SiteSetting.tagging_enabled
      SidebarSectionLinksUpdater.update_tag_section_links(
        user,
        tag_ids:
          DiscourseTagging
            .filter_visible(Tag, @user_guardian)
            .where(name: attributes[:sidebar_tag_names])
            .pluck(:id),
      )
    end

    if SiteSetting.enable_user_status?
      update_user_status(attributes[:status]) if attributes.has_key?(:status)
    end

    name_changed = user.name_changed?
    saved =
      (!save_options || user.user_option.save) &&
        (user_notification_schedule.nil? || user_notification_schedule.save) &&
        .save && user.save

    if saved && (name_changed && old_user_name.casecmp(attributes.fetch(:name)) != 0)
      StaffActionLogger.new(@actor).log_name_change(
        user.id,
        old_user_name,
        attributes.fetch(:name) { "" },
      )
    end
    DiscourseEvent.trigger(:within_user_updater_transaction, user, attributes)
  rescue Addressable::URI::InvalidURIError => e
    # Prevent 500 for crazy url input
    return saved
  end

  if saved
    if user_notification_schedule
      if user_notification_schedule.enabled
        user_notification_schedule.create_do_not_disturb_timings(delete_existing: true)
      else
        user_notification_schedule.destroy_scheduled_timings
      end
    end
    if attributes.key?(:seen_popups) || attributes.key?(:skip_new_user_tips)
      MessageBus.publish(
        "/user-tips/#{user.id}",
        user.user_option.seen_popups,
        user_ids: [user.id],
      )
    end
    DiscourseEvent.trigger(:user_updated, user)
  end

  saved
end

#update_allowed_pm_users(usernames) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'app/services/user_updater.rb', line 298

def update_allowed_pm_users(usernames)
  usernames ||= ""
  desired_usernames = usernames.split(",").reject { |username| user.username == username }
  desired_ids = User.where(username: desired_usernames).pluck(:id)

  if desired_ids.empty?
    AllowedPmUser.where(user_id: user.id).destroy_all
  else
    AllowedPmUser.where(
      "user_id = ? AND allowed_pm_user_id not in (?)",
      user.id,
      desired_ids,
    ).destroy_all

    # SQL is easier here than figuring out how to do the same in AR
    DB.exec(<<~SQL, now: Time.zone.now, user_id: user.id, desired_ids: desired_ids)
      INSERT into allowed_pm_users(user_id, allowed_pm_user_id, created_at, updated_at)
      SELECT :user_id, id, :now, :now
      FROM users
      WHERE id in (:desired_ids)
      ON CONFLICT DO NOTHING
    SQL
  end
end

#update_muted_users(usernames) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'app/services/user_updater.rb', line 278

def update_muted_users(usernames)
  usernames ||= ""
  desired_usernames = usernames.split(",").reject { |username| user.username == username }
  desired_ids = User.where(username: desired_usernames).pluck(:id)
  if desired_ids.empty?
    MutedUser.where(user_id: user.id).destroy_all
  else
    MutedUser.where("user_id = ? AND muted_user_id not in (?)", user.id, desired_ids).destroy_all

    # SQL is easier here than figuring out how to do the same in AR
    DB.exec(<<~SQL, now: Time.now, user_id: user.id, desired_ids: desired_ids)
      INSERT into muted_users(user_id, muted_user_id, created_at, updated_at)
      SELECT :user_id, id, :now, :now
      FROM users
      WHERE id in (:desired_ids)
      ON CONFLICT DO NOTHING
    SQL
  end
end

#updated_associated_accounts(associations) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'app/services/user_updater.rb', line 323

def updated_associated_accounts(associations)
  associations.each do |association|
     =
      UserAssociatedAccount.find_or_initialize_by(
        user_id: user.id,
        provider_name: association[:provider_name],
      )
    if association[:provider_uid].present?
      .update!(provider_uid: association[:provider_uid])
    else
      .destroy!
    end
  end
end