Make members of a group watch a category by default

@alehandrof, for the record:

# based on https://github.com/discourse/discourse-watch-category-mcneel/blob/master/plugin.rb
groups = {
  "Group_1" => {},
  "Group_2" => {category: "News"},
  "Group_3" => {tag: "content"},
  "Group_4" => {tag: "content", category: "News"}
}

# levels: :watching :watching_first_post etc.
level = :watching

groups.each do |group_name, subscriptions|
  group = Group.find_by_name(group_name)
  next if group.nil? # skip if group not found
  puts "group: #{group.name}"
  
  # watch group inbox
  # found in discourse/spec/services/post_alerter_spec.rb
  # GroupUser.where(user_id: user.id, group_id: group.id).update_all(notification_level: level) # change for one user
  GroupUser.where(group_id: group.id).update_all(notification_level: GroupUser.notification_levels[level]) # change for whole group
  
  # watch tag
  tag_name = subscriptions[:tag]
  if tag_name
    tag = Tag.find_by_name(tag_name)
    unless tag.nil?
      puts "tag: #{tag.name}"
      # TagUser.where(tag_id: tag.id).update_all(notification_level: GroupUser.notification_levels[:level])
      group.users.each do |user|
        watched_tags = TagUser.lookup(user, level).pluck(:tag_id)
        TagUser.change(user.id, tag.id, TagUser.notification_levels[level]) unless watched_tags.include?(tag.id)
      end
    end
  end  
  
  # watch category
  category_slug = subscriptions[:category]
  if category_slug
    category = Category.find_by_slug(category_slug)
    unless category.nil?
      puts "category: #{category.name}"
      group.users.each do |user|
        watched_categories = CategoryUser.lookup(user, level).pluck(:category_id)
        CategoryUser.set_notification_level_for_category(user, CategoryUser.notification_levels[level], category.id) unless watched_categories.include?(category.id)
      end
    end    
  end
end
4 Likes