Class: GroupsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/groups_controller.rb

Constant Summary collapse

TYPE_FILTERS =
{
  my:
    Proc.new do |groups, user|
      raise Discourse::NotFound unless user
      Group.member_of(groups, user)
    end,
  owner:
    Proc.new do |groups, user|
      raise Discourse::NotFound unless user
      Group.owner_of(groups, user)
    end,
  public: Proc.new { |groups| groups.where(public_admission: true, automatic: false) },
  close: Proc.new { |groups| groups.where(public_admission: false, automatic: false) },
  automatic: Proc.new { |groups| groups.where(automatic: true) },
  non_automatic: Proc.new { |groups| groups.where(automatic: false) },
}
ADD_MEMBERS_LIMIT =
1000
MEMBERS_MAX_PAGE_SIZE =
1_000
MEMBERS_DEFAULT_PAGE_SIZE =
50

Constants inherited from ApplicationController

ApplicationController::LEGACY_NO_THEMES, ApplicationController::LEGACY_NO_UNOFFICIAL_PLUGINS, ApplicationController::NO_PLUGINS, ApplicationController::NO_THEMES, ApplicationController::NO_UNOFFICIAL_PLUGINS, ApplicationController::SAFE_MODE

Constants included from CanonicalURL::ControllerExtensions

CanonicalURL::ControllerExtensions::ALLOWED_CANONICAL_PARAMS

Instance Attribute Summary

Attributes inherited from ApplicationController

#theme_id

Instance Method Summary collapse

Methods inherited from ApplicationController

#application_layout, #can_cache_content?, #clear_notifications, #conditionally_allow_site_embedding, #current_homepage, #discourse_expires_in, #dont_cache_page, #ember_cli_required?, #fetch_user_from_params, #guardian, #handle_permalink, #handle_theme, #handle_unverified_request, #has_escaped_fragment?, #immutable_for, #no_cookies, #perform_refresh_session, #post_ids_including_replies, #preload_json, #rate_limit_second_factor!, #redirect_with_client_support, #render_json_dump, #render_serialized, requires_plugin, #rescue_discourse_actions, #resolve_safe_mode, #secure_session, #serialize_data, #set_current_user_for_logs, #set_layout, #set_mobile_view, #set_mp_snapshot_fields, #show_browser_update?, #store_preloaded, #use_crawler_layout?, #with_resolved_locale

Methods included from VaryHeader

#ensure_vary_header

Methods included from ReadOnlyMixin

#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_mode, included, #staff_writes_only_mode?

Methods included from Hijack

#hijack

Methods included from GlobalPath

#cdn_path, #cdn_relative_path, #full_cdn_url, #path, #upload_cdn_path

Methods included from JsonError

#create_errors_json

Methods included from CanonicalURL::ControllerExtensions

#canonical_url, #default_canonical, included

Methods included from CurrentUser

#clear_current_user, #current_user, has_auth_cookie?, #is_api?, #is_user_api?, #log_off_user, #log_on_user, lookup_from_env, #refresh_session

Instance Method Details

#add_membersObject



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
# File 'app/controllers/groups_controller.rb', line 326

def add_members
  group = Group.find(params[:id])
  guardian.ensure_can_edit!(group)

  users = users_from_params.to_a
  emails = []
  if params[:emails]
    params[:emails]
      .split(",")
      .each do |email|
        existing_user = User.find_by_email(email)
        existing_user.present? ? users.push(existing_user) : emails.push(email)
      end
  end

  guardian.ensure_can_invite_to_forum!([group]) if emails.present?

  if users.empty? && emails.empty?
    raise Discourse::InvalidParameters.new(I18n.t("groups.errors.usernames_or_emails_required"))
  end

  if users.length > ADD_MEMBERS_LIMIT
    return(
      render_json_error(I18n.t("groups.errors.adding_too_many_users", count: ADD_MEMBERS_LIMIT))
    )
  end

  usernames_already_in_group = group.users.where(id: users.map(&:id)).pluck(:username)
  if usernames_already_in_group.present? && usernames_already_in_group.length == users.length &&
       emails.blank?
    render_json_error(
      I18n.t(
        "groups.errors.member_already_exist",
        username: usernames_already_in_group.sort.join(", "),
        count: usernames_already_in_group.size,
      ),
    )
  else
    notify = params[:notify_users]&.to_s == "true"
    uniq_users = users.uniq
    uniq_users.each { |user| add_user_to_group(group, user, notify) }

    emails.each do |email|
      begin
        Invite.generate(current_user, email: email, group_ids: [group.id])
      rescue RateLimiter::LimitExceeded => e
        return(
          render_json_error(
            I18n.t(
              "invite.rate_limit",
              count: SiteSetting.max_invites_per_day,
              time_left: e.time_left,
            ),
          )
        )
      end
    end

    render json: success_json.merge!(usernames: uniq_users.map(&:username), emails: emails)
  end
end

#add_ownersObject



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
# File 'app/controllers/groups_controller.rb', line 388

def add_owners
  group = Group.find_by(id: params.require(:id))
  raise Discourse::NotFound unless group

  return can_not_modify_automatic if group.automatic
  guardian.ensure_can_edit_group!(group)

  users = users_from_params
  group_action_logger = GroupActionLogger.new(current_user, group)

  users.each do |user|
    if !group.users.include?(user)
      group.add(user)
      group_action_logger.log_add_user_to_group(user)
    end
    group.group_users.where(user_id: user.id).update_all(owner: true)
    group_action_logger.log_make_user_group_owner(user)

    group.notify_added_to_group(user, owner: true) if params[:notify_users].to_s == "true"
  end

  group.restore_user_count!

  render json: success_json.merge!(usernames: users.pluck(:username))
end

#check_nameObject



479
480
481
482
483
# File 'app/controllers/groups_controller.rb', line 479

def check_name
  group_name = params.require(:group_name)
  checker = UsernameCheckerService.new(allow_reserved_username: true)
  render json: checker.check_username(group_name, nil)
end

#editObject



147
148
# File 'app/controllers/groups_controller.rb', line 147

def edit
end

#handle_membership_requestObject



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
# File 'app/controllers/groups_controller.rb', line 428

def handle_membership_request
  group = Group.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) if group.blank?
  guardian.ensure_can_edit!(group)

  user = User.find_by(id: params[:user_id])
  raise Discourse::InvalidParameters.new(:user_id) if user.blank?

  ActiveRecord::Base.transaction do
    if params[:accept]
      group.add(user)
      GroupActionLogger.new(current_user, group).log_add_user_to_group(user)
    end

    GroupRequest.where(group_id: group.id, user_id: user.id).delete_all
  end

  if params[:accept]
    PostCreator.new(
      current_user,
      title: I18n.t("groups.request_accepted_pm.title", group_name: group.name),
      raw: I18n.t("groups.request_accepted_pm.body", group_name: group.name),
      archetype: Archetype.private_message,
      target_usernames: user.username,
      skip_validations: true,
    ).create!
  end

  render json: success_json
end

#historiesObject



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'app/controllers/groups_controller.rb', line 591

def histories
  group = find_group(:group_id)
  guardian.ensure_can_edit!(group) unless guardian.can_admin_group?(group)

  page_size = 25
  offset = (params[:offset] && params[:offset].to_i) || 0

  group_histories =
    GroupHistory.with_filters(group, params[:filters]).limit(page_size).offset(offset * page_size)

  render_json_dump(
    logs: serialize_data(group_histories, BasicGroupHistorySerializer),
    all_loaded: group_histories.count < page_size,
  )
end

#indexObject



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
# File 'app/controllers/groups_controller.rb', line 39

def index
  unless SiteSetting.enable_group_directory? || current_user&.staff?
    raise Discourse::InvalidAccess.new(:enable_group_directory)
  end

  order = %w[name user_count].delete(params[:order])
  dir = params[:asc].to_s == "true" ? "ASC" : "DESC"
  sort = order ? "#{order} #{dir}" : nil
  groups = Group.visible_groups(current_user, sort)
  type_filters = TYPE_FILTERS.keys

  if (username = params[:username]).present?
    raise Discourse::NotFound unless user = User.find_by_username(username)
    groups = TYPE_FILTERS[:my].call(groups.members_visible_groups(current_user, sort), user)
    type_filters = type_filters - %i[my owner]
  end

  if (filter = params[:filter]).present?
    groups = Group.search_groups(filter, groups: groups)
  end

  if !guardian.is_staff?
    # hide automatic groups from all non stuff to de-clutter page
    groups =
      groups.where("groups.automatic IS FALSE OR groups.id = ?", Group::AUTO_GROUPS[:moderators])
    type_filters.delete(:automatic)
  end

  if Group.preloaded_custom_field_names.present?
    Group.preload_custom_fields(groups, Group.preloaded_custom_field_names)
  end

  if type = params[:type]&.to_sym
    raise Discourse::InvalidParameters.new(:type) unless callback = TYPE_FILTERS[type]
    groups = callback.call(groups, current_user)
  end

  if current_user
    group_users = GroupUser.where(group: groups, user: current_user)
    user_group_ids = group_users.pluck(:group_id)
    owner_group_ids = group_users.where(owner: true).pluck(:group_id)
  else
    type_filters = type_filters - %i[my owner]
  end

  groups = DiscoursePluginRegistry.apply_modifier(:groups_index_query, groups, self)

  type_filters.delete(:non_automatic)

  # count the total before doing pagination
  total = groups.count

  page = fetch_int_from_params(:page, default: 0)
  page_size = MobileDetection.mobile_device?(request.user_agent) ? 15 : 36
  groups = groups.offset(page * page_size).limit(page_size)

  render_json_dump(
    groups:
      serialize_data(
        groups,
        BasicGroupSerializer,
        user_group_ids: user_group_ids || [],
        owner_group_ids: owner_group_ids || [],
      ),
    extras: {
      type_filters: type_filters,
    },
    total_rows_groups: total,
    load_more_groups:
      groups_path(page: page + 1, type: type, order: order, asc: params[:asc], filter: filter),
  )
end

#joinObject



414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'app/controllers/groups_controller.rb', line 414

def join
  ensure_logged_in
  unless current_user.staff?
    RateLimiter.new(current_user, "public_group_membership", 3, 1.minute).performed!
  end

  group = Group.find(params[:id])
  raise Discourse::NotFound unless group
  raise Discourse::InvalidAccess unless group.public_admission

  return if group.users.exists?(id: current_user.id)
  add_user_to_group(group, current_user)
end

#leaveObject



518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'app/controllers/groups_controller.rb', line 518

def leave
  ensure_logged_in
  unless current_user.staff?
    RateLimiter.new(current_user, "public_group_membership", 3, 1.minute).performed!
  end

  group = Group.find_by(id: params[:id])
  raise Discourse::NotFound unless group
  raise Discourse::InvalidAccess unless group.public_exit

  if group.remove(current_user)
    GroupActionLogger.new(current_user, group).log_remove_user_from_group(current_user)
  end
end

#membersObject



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
# File 'app/controllers/groups_controller.rb', line 236

def members
  group = find_group(:group_id)

  guardian.ensure_can_see_group_members!(group)

  limit = fetch_limit_from_params(default: MEMBERS_DEFAULT_PAGE_SIZE, max: MEMBERS_MAX_PAGE_SIZE)
  offset = params[:offset].to_i

  raise Discourse::InvalidParameters.new(:offset) if offset < 0

  dir = (params[:asc] && params[:asc].present?) ? "ASC" : "DESC"
  order = "NOT group_users.owner"

  if params[:requesters]
    guardian.ensure_can_edit!(group)

    users = group.requesters
    total = users.count

    if (filter = params[:filter]).present?
      filter = filter.split(",") if filter.include?(",")

      if current_user&.admin
        users = users.filter_by_username_or_email(filter)
      else
        users = users.filter_by_username(filter)
      end
    end

    users =
      users
        .select("users.*, group_requests.reason, group_requests.created_at requested_at")
        .order(params[:order] == "requested_at" ? "group_requests.created_at #{dir}" : "")
        .order(username_lower: dir)
        .limit(limit)
        .offset(offset)

    return(
      render json: {
               members: serialize_data(users, GroupRequesterSerializer),
               meta: {
                 total: total,
                 limit: limit,
                 offset: offset,
               },
             }
    )
  end

  if params[:order] && %w[last_posted_at last_seen_at].include?(params[:order])
    order = "#{params[:order]} #{dir} NULLS LAST"
  elsif params[:order] == "added_at"
    order = "group_users.created_at #{dir}"
  end

  users = group.users.human_users
  total = users.count

  if (filter = params[:filter]).present?
    filter = filter.split(",") if filter.include?(",")

    if current_user&.admin
      users = users.filter_by_username_or_email(filter)
    else
      users = users.filter_by_username(filter)
    end
  end

  users =
    users
      .includes(:primary_group)
      .includes(:user_option)
      .select("users.*, group_users.created_at as added_at")
      .order(order)
      .order(username_lower: dir)

  members = users.limit(limit).offset(offset)
  owners = users.where("group_users.owner")

  render json: {
           members: serialize_data(members, GroupUserSerializer),
           owners: serialize_data(owners, GroupUserSerializer),
           meta: {
             total: total,
             limit: limit,
             offset: offset,
           },
         }
end

#mentionableObject



459
460
461
462
463
464
465
466
467
# File 'app/controllers/groups_controller.rb', line 459

def mentionable
  group = find_group(:group_id, ensure_can_see: false)

  if group
    render json: { mentionable: Group.mentionable(current_user).where(id: group.id).present? }
  else
    raise Discourse::InvalidAccess.new
  end
end

#mentionsObject



213
214
215
216
217
218
219
# File 'app/controllers/groups_controller.rb', line 213

def mentions
  raise Discourse::NotFound unless SiteSetting.enable_mentions?
  group = find_group(:group_id)
  posts =
    group.mentioned_posts_for(guardian, params.permit(:before_post_id, :category_id)).limit(20)
  render_serialized posts.to_a, GroupPostSerializer
end

#mentions_feedObject



221
222
223
224
225
226
227
228
229
230
231
# File 'app/controllers/groups_controller.rb', line 221

def mentions_feed
  raise Discourse::NotFound unless SiteSetting.enable_mentions?
  group = find_group(:group_id)
  @posts =
    group.mentioned_posts_for(guardian, params.permit(:before_post_id, :category_id)).limit(50)
  @title =
    "#{SiteSetting.title} - #{I18n.t("rss_description.group_mentions", group_name: group.name)}"
  @link = Discourse.base_url
  @description = I18n.t("rss_description.group_mentions", group_name: group.name)
  render "posts/latest", formats: [:rss]
end

#messageableObject



469
470
471
472
473
474
475
476
477
# File 'app/controllers/groups_controller.rb', line 469

def messageable
  group = find_group(:group_id, ensure_can_see: false)

  if group
    render json: { messageable: guardian.can_send_private_message?(group) }
  else
    raise Discourse::InvalidAccess.new
  end
end

#newObject



144
145
# File 'app/controllers/groups_controller.rb', line 144

def new
end

#permissionsObject



630
631
632
633
634
635
636
637
638
639
640
# File 'app/controllers/groups_controller.rb', line 630

def permissions
  group = find_group(:id)
  category_groups =
    group.category_groups.select do |category_group|
      guardian.can_see_category?(category_group.category)
    end
  render_serialized(
    category_groups.sort_by { |category_group| category_group.category.name },
    CategoryGroupSerializer,
  )
end

#postsObject



193
194
195
196
197
198
199
# File 'app/controllers/groups_controller.rb', line 193

def posts
  group = find_group(:group_id)
  guardian.ensure_can_see_group_members!(group)

  posts = group.posts_for(guardian, params.permit(:before_post_id, :category_id)).limit(20)
  render_serialized posts.to_a, GroupPostSerializer
end

#posts_feedObject



201
202
203
204
205
206
207
208
209
210
211
# File 'app/controllers/groups_controller.rb', line 201

def posts_feed
  group = find_group(:group_id)
  guardian.ensure_can_see_group_members!(group)

  @posts = group.posts_for(guardian, params.permit(:before_post_id, :category_id)).limit(50)
  @title =
    "#{SiteSetting.title} - #{I18n.t("rss_description.group_posts", group_name: group.name)}"
  @link = Discourse.base_url
  @description = I18n.t("rss_description.group_posts", group_name: group.name)
  render "posts/latest", formats: [:rss]
end

#remove_memberObject



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
# File 'app/controllers/groups_controller.rb', line 485

def remove_member
  group = Group.find_by(id: params[:id])
  raise Discourse::NotFound unless group
  guardian.ensure_can_edit!(group)

  # Maintain backwards compatibility
  params[:usernames] = params[:username] if params[:username].present?
  params[:user_emails] = params[:user_email] if params[:user_email].present?

  users = users_from_params
  if users.empty?
    raise Discourse::InvalidParameters.new("user_ids or usernames or user_emails must be present")
  end

  removed_users = []
  skipped_users = []

  users.each do |user|
    if group.remove(user)
      removed_users << user.username
      GroupActionLogger.new(current_user, group).log_remove_user_from_group(user)
    else
      if group.users.exclude? user
        skipped_users << user.username
      else
        raise Discourse::InvalidParameters
      end
    end
  end

  render json: success_json.merge!(usernames: removed_users, skipped_usernames: skipped_users)
end

#request_membershipObject



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
# File 'app/controllers/groups_controller.rb', line 535

def request_membership
  params.require(:reason)

  group = find_group(:id)

  begin
    GroupRequest.create!(group: group, user: current_user, reason: params[:reason])
  rescue ActiveRecord::RecordNotUnique
    return(
      render json: failed_json.merge(error: I18n.t("groups.errors.already_requested_membership")),
             status: 409
    )
  end

  usernames = [current_user.username].concat(
    group
      .users
      .where("group_users.owner")
      .order("users.last_seen_at DESC")
      .limit(MAX_NOTIFIED_OWNERS)
      .pluck("users.username"),
  )

  post =
    PostCreator.new(
      current_user,
      title: I18n.t("groups.request_membership_pm.title", group_name: group.name),
      raw: params[:reason],
      archetype: Archetype.private_message,
      target_usernames: usernames.join(","),
      topic_opts: {
        custom_fields: {
          requested_group_id: group.id,
        },
      },
      skip_validations: true,
    ).create!

  render json: success_json.merge(relative_url: post.topic.relative_url)
end

#searchObject



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'app/controllers/groups_controller.rb', line 607

def search
  groups =
    Group
      .visible_groups(current_user)
      .where("groups.id <> ?", Group::AUTO_GROUPS[:everyone])
      .includes(:flair_upload)
      .order(:name)

  if (term = params[:term]).present?
    groups =
      groups.where("groups.name ILIKE :term OR groups.full_name ILIKE :term", term: "%#{term}%")
  end

  groups = groups.where(automatic: false) if params[:ignore_automatic].to_s == "true"
  groups = DiscoursePluginRegistry.apply_modifier(:groups_search_query, groups, self)

  if Group.preloaded_custom_field_names.present?
    Group.preload_custom_fields(groups, Group.preloaded_custom_field_names)
  end

  render_serialized(groups, BasicGroupSerializer)
end

#set_notificationsObject



576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'app/controllers/groups_controller.rb', line 576

def set_notifications
  group = find_group(:id)
  notification_level = params.require(:notification_level)

  user_id = current_user.id
  user_id = params[:user_id] || user_id if guardian.is_staff?

  GroupUser
    .where(group_id: group.id)
    .where(user_id: user_id)
    .update_all(notification_level: notification_level)

  render json: success_json
end

#showObject



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
# File 'app/controllers/groups_controller.rb', line 112

def show
  respond_to do |format|
    group = find_group(:id)

    format.html do
      @title = group.full_name.present? ? group.full_name.capitalize : group.name
      @full_title = "#{@title} - #{SiteSetting.title}"
      @description_meta =
        group.bio_cooked.present? ? PrettyText.excerpt(group.bio_cooked, 300) : @title
      render :show
    end

    format.json do
      groups = Group.visible_groups(current_user)
      if !guardian.is_staff?
        groups =
          groups.where(
            "groups.automatic IS FALSE OR groups.id = ?",
            Group::AUTO_GROUPS[:moderators],
          )
      end

      render_json_dump(
        group: serialize_data(group, GroupShowSerializer, root: nil),
        extras: {
          visible_group_names: groups.pluck(:name),
        },
      )
    end
  end
end

#test_email_settingsObject



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
# File 'app/controllers/groups_controller.rb', line 642

def test_email_settings
  params.require(:group_id)
  params.require(:protocol)
  params.require(:port)
  params.require(:host)
  params.require(:username)
  params.require(:password)
  params.require(:ssl)

  group = Group.find(params[:group_id])
  guardian.ensure_can_edit!(group)

  RateLimiter.new(current_user, "group_test_email_settings", 5, 1.minute).performed!

  settings = params.except(:group_id, :protocol)
  enable_tls = settings[:ssl] == "true"
  email_host = params[:host]

  if !%w[smtp imap].include?(params[:protocol])
    raise Discourse::InvalidParameters.new("Valid protocols to test are smtp and imap")
  end

  hijack do
    begin
      case params[:protocol]
      when "smtp"
        enable_starttls_auto = false
        settings.delete(:ssl)

        final_settings =
          settings.merge(
            enable_tls: enable_tls,
            enable_starttls_auto: enable_starttls_auto,
          ).permit(:host, :port, :username, :password, :enable_tls, :enable_starttls_auto, :debug)
        EmailSettingsValidator.validate_as_user(
          current_user,
          "smtp",
          **final_settings.to_h.symbolize_keys,
        )
      when "imap"
        final_settings =
          settings.merge(ssl: enable_tls).permit(:host, :port, :username, :password, :ssl, :debug)
        EmailSettingsValidator.validate_as_user(
          current_user,
          "imap",
          **final_settings.to_h.symbolize_keys,
        )
      end

      render json: success_json
    rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS, StandardError => err
      render_json_error(EmailSettingsExceptionHandler.friendly_exception_message(err, email_host))
    end
  end
end

#updateObject



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
# File 'app/controllers/groups_controller.rb', line 150

def update
  group = Group.find(params[:id])
  guardian.ensure_can_edit!(group) if !guardian.can_admin_group?(group)

  group_attributes = group_params(automatic: group.automatic)
  reset_group_email_settings_if_disabled!(group, group_attributes)

  categories, tags = []
  if !group.automatic || current_user.admin
    notification_level, categories, tags = user_default_notifications(group, group_attributes)

    if params[:update_existing_users].blank?
      user_count = count_existing_users(group.group_users, notification_level, categories, tags)
      if user_count > 0
        return(
          render status: 422,
                 json: {
                   user_count: user_count,
                   errors: [I18n.t("invalid_params", message: :update_existing_users)],
                 }
        )
      end
    end
  end

  if group.update(group_attributes)
    GroupActionLogger.new(current_user, group).log_change_group_settings
    group.record_email_setting_changes!(current_user)
    group.expire_imap_mailbox_cache
    if params[:update_existing_users] == "true"
      update_existing_users(group.group_users, notification_level, categories, tags)
    end
    AdminDashboardData.clear_found_problem("group_#{group.id}_email_credentials")

    # Redirect user to groups index page if they can no longer see the group
    return redirect_with_client_support groups_path if !guardian.can_see?(group)

    render json: success_json
  else
    render_json_error(group)
  end
end