2022-11-02 21:41:30 +08:00
# frozen_string_literal: true
##
# From time to time, site admins may choose to sunset a chat channel and archive
2023-01-12 08:04:46 +08:00
# the messages within. It cannot be used for DM channels in its current iteration.
2022-11-02 21:41:30 +08:00
#
# To archive a channel, we mark it read_only first to prevent any further message
# additions or changes, and create a record to track whether the archive topic
# will be new or existing. When we archive the channel, messages are copied into
# posts in batches using the [chat] BBCode to quote the messages. The messages are
# deleted once the batch has its post made. The execute action of this class is
# idempotent, so if we fail halfway through the archive process it can be run again.
#
# Once all of the messages have been copied then we mark the channel as archived.
class Chat :: ChatChannelArchiveService
ARCHIVED_MESSAGES_PER_POST = 100
2023-01-12 08:04:46 +08:00
class ArchiveValidationError < StandardError
attr_reader :errors
def initialize ( errors : [ ] )
super
@errors = errors
end
end
def self . create_archive_process ( chat_channel : , acting_user : , topic_params : )
2022-11-02 21:41:30 +08:00
return if ChatChannelArchive . exists? ( chat_channel : chat_channel )
2023-01-12 08:04:46 +08:00
# Only need to validate topic params for a new topic, not an existing one.
if topic_params [ :topic_id ] . blank?
valid , errors =
Chat :: ChatChannelArchiveService . validate_topic_params (
Guardian . new ( acting_user ) ,
topic_params ,
)
raise ArchiveValidationError . new ( errors : errors ) if ! valid
end
2022-11-02 21:41:30 +08:00
ChatChannelArchive . transaction do
chat_channel . read_only! ( acting_user )
archive =
ChatChannelArchive . create! (
chat_channel : chat_channel ,
archived_by : acting_user ,
total_messages : chat_channel . chat_messages . count ,
destination_topic_id : topic_params [ :topic_id ] ,
destination_topic_title : topic_params [ :topic_title ] ,
destination_category_id : topic_params [ :category_id ] ,
destination_tags : topic_params [ :tags ] ,
)
Jobs . enqueue ( :chat_channel_archive , chat_channel_archive_id : archive . id )
archive
end
end
def self . retry_archive_process ( chat_channel : )
return if ! chat_channel . chat_channel_archive & . failed?
Jobs . enqueue (
:chat_channel_archive ,
chat_channel_archive_id : chat_channel . chat_channel_archive . id ,
)
DEV: start glimmer-ification and optimisations of chat plugin (#19531)
Note this is a very large PR, and some of it could have been splited, but keeping it one chunk made it to merge conflicts and to revert if necessary. Actual new code logic is also not that much, as most of the changes are removing js tests, adding system specs or moving things around.
To make it possible this commit is doing the following changes:
- converting (and adding new) existing js acceptances tests into system tests. This change was necessary to ensure as little regressions as possible while changing paradigm
- moving away from store. Using glimmer and tracked properties requires to have class objects everywhere and as a result works well with models. However store/adapters are suffering from many bugs and limitations. As a workaround the `chat-api` and `chat-channels-manager` are an answer to this problem by encapsulating backend calls and frontend storage logic; while still using js models.
- dropping `appEvents` as much as possible. Using tracked properties and a better local storage of channel models, allows to be much more reactive and doesn’t require arbitrary manual updates everywhere in the app.
- while working on replacing store, the existing work of a chat api (backend) has been continued to support more cases.
- removing code from the `chat` service to separate concerns, `chat-subscriptions-manager` and `chat-channels-manager`, being the largest examples of where the code has been rewritten/moved.
Future wok:
- improve behavior when closing/deleting a channel, it's already slightly buggy on live, it's rare enough that it's not a big issue, but should be improved
- improve page objects used in chat
- move more endpoints to the API
- finish temporarily skipped tests
- extract more code from the `chat` service
- use glimmer for `chat-messages`
- separate concerns in `chat-live-pane`
- eventually add js tests for `chat-api`, `chat-channels-manager` and `chat-subscriptions-manager`, they are indirectly heavy tested through system tests but it would be nice to at least test the public API
<!-- NOTE: All pull requests should have tests (rspec in Ruby, qunit in JavaScript). If your code does not include test coverage, please include an explanation of why it was omitted. -->
2022-12-21 20:21:02 +08:00
chat_channel . chat_channel_archive
2022-11-02 21:41:30 +08:00
end
2023-01-12 08:04:46 +08:00
def self . validate_topic_params ( guardian , topic_params )
topic_creator =
TopicCreator . new (
Discourse . system_user ,
guardian ,
{
title : topic_params [ :topic_title ] ,
category : topic_params [ :category_id ] ,
tags : topic_params [ :tags ] ,
import_mode : true ,
} ,
)
[ topic_creator . valid? , topic_creator . errors . full_messages ]
end
2022-11-02 21:41:30 +08:00
attr_reader :chat_channel_archive , :chat_channel , :chat_channel_title
def initialize ( chat_channel_archive )
@chat_channel_archive = chat_channel_archive
@chat_channel = chat_channel_archive . chat_channel
@chat_channel_title = chat_channel . title ( chat_channel_archive . archived_by )
end
def execute
chat_channel_archive . update ( archive_error : nil )
begin
2023-01-12 08:04:46 +08:00
return if ! ensure_destination_topic_exists!
2022-11-02 21:41:30 +08:00
Rails . logger . info (
" Creating posts from message batches for #{ chat_channel_title } archive, #{ chat_channel_archive . total_messages } messages to archive ( #{ chat_channel_archive . total_messages / ARCHIVED_MESSAGES_PER_POST } posts). " ,
)
2023-01-12 08:04:46 +08:00
# A batch should be idempotent, either the post is created and the
2022-11-02 21:41:30 +08:00
# messages are deleted or we roll back the whole thing.
#
2023-01-12 08:04:46 +08:00
# At some point we may want to reconsider disabling post validations,
2022-11-02 21:41:30 +08:00
# and add in things like dynamic resizing of the number of messages per
2023-01-12 08:04:46 +08:00
# post based on post length, but that can be done later.
2022-11-02 21:41:30 +08:00
#
2023-01-12 08:04:46 +08:00
# Another future improvement is to send a MessageBus message for each
2022-11-02 21:41:30 +08:00
# completed batch, so the UI can receive updates and show a progress
2023-01-12 08:04:46 +08:00
# bar or something similar.
2022-11-02 21:41:30 +08:00
chat_channel
. chat_messages
. find_in_batches ( batch_size : ARCHIVED_MESSAGES_PER_POST ) do | chat_messages |
create_post (
ChatTranscriptService . new (
chat_channel ,
chat_channel_archive . archived_by ,
messages_or_ids : chat_messages ,
opts : {
no_link : true ,
include_reactions : true ,
} ,
) . generate_markdown ,
) { delete_message_batch ( chat_messages . map ( & :id ) ) }
end
kick_all_users
complete_archive
rescue = > err
2023-01-12 08:04:46 +08:00
notify_archiver ( :failed , error_message : err . message )
2022-11-02 21:41:30 +08:00
raise err
end
end
private
def create_post ( raw )
pc = nil
Post . transaction do
pc =
PostCreator . new (
Discourse . system_user ,
raw : raw ,
# we must skip these because the posts are created in a big transaction,
# we do them all at the end instead
skip_jobs : true ,
# we do not want to be sending out notifications etc. from this
# automatic background process
import_mode : true ,
# don't want to be stopped by watched word or post length validations
skip_validations : true ,
topic_id : chat_channel_archive . destination_topic_id ,
)
pc . create
# so we can also delete chat messages in the same transaction
yield if block_given?
end
pc . enqueue_jobs
end
def ensure_destination_topic_exists!
if ! chat_channel_archive . destination_topic . present?
Rails . logger . info ( " Creating topic for #{ chat_channel_title } archive. " )
Topic . transaction do
topic_creator =
TopicCreator . new (
Discourse . system_user ,
Guardian . new ( chat_channel_archive . archived_by ) ,
{
title : chat_channel_archive . destination_topic_title ,
category : chat_channel_archive . destination_category_id ,
tags : chat_channel_archive . destination_tags ,
import_mode : true ,
} ,
)
2023-01-12 08:04:46 +08:00
if topic_creator . valid?
chat_channel_archive . update! ( destination_topic : topic_creator . create )
else
Rails . logger . info ( " Destination topic for #{ chat_channel_title } archive was not valid. " )
notify_archiver (
:failed_no_topic ,
error_message : topic_creator . errors . full_messages . join ( " \n " ) ,
)
end
2022-11-02 21:41:30 +08:00
end
2023-01-12 08:04:46 +08:00
if chat_channel_archive . destination_topic . present?
Rails . logger . info ( " Creating first post for #{ chat_channel_title } archive. " )
create_post (
I18n . t (
" chat.channel.archive.first_post_raw " ,
channel_name : chat_channel_title ,
channel_url : chat_channel . url ,
) ,
)
end
2022-11-02 21:41:30 +08:00
else
Rails . logger . info ( " Topic already exists for #{ chat_channel_title } archive. " )
end
2023-01-12 08:04:46 +08:00
if chat_channel_archive . destination_topic . present?
update_destination_topic_status
return true
end
false
2022-11-02 21:41:30 +08:00
end
def update_destination_topic_status
2023-01-12 08:04:46 +08:00
# We only want to do this when the destination topic is new, not an
2022-11-02 21:41:30 +08:00
# existing topic, because we don't want to update the status unexpectedly
# on an existing topic
2023-01-12 08:04:46 +08:00
if chat_channel_archive . new_topic?
2022-11-02 21:41:30 +08:00
if SiteSetting . chat_archive_destination_topic_status == " archived "
chat_channel_archive . destination_topic . update! ( archived : true )
elsif SiteSetting . chat_archive_destination_topic_status == " closed "
chat_channel_archive . destination_topic . update! ( closed : true )
end
end
end
def delete_message_batch ( message_ids )
ChatMessage . transaction do
ChatMessage . where ( id : message_ids ) . update_all (
deleted_at : DateTime . now ,
deleted_by_id : chat_channel_archive . archived_by . id ,
)
chat_channel_archive . update! (
archived_messages : chat_channel_archive . archived_messages + message_ids . length ,
)
end
Rails . logger . info (
" Archived #{ chat_channel_archive . archived_messages } messages for #{ chat_channel_title } archive. " ,
)
end
def complete_archive
Rails . logger . info ( " Creating posts completed for #{ chat_channel_title } archive. " )
chat_channel . archived! ( chat_channel_archive . archived_by )
notify_archiver ( :success )
end
2023-01-12 08:04:46 +08:00
def notify_archiver ( result , error_message : nil )
2022-11-02 21:41:30 +08:00
base_translation_params = {
2023-01-16 08:20:37 +08:00
channel_hashtag_or_name : channel_hashtag_or_name ,
2023-01-12 08:04:46 +08:00
topic_title : chat_channel_archive . destination_topic & . title ,
topic_url : chat_channel_archive . destination_topic & . url ,
topic_validation_errors : result == :failed_no_topic ? error_message : nil ,
2022-11-02 21:41:30 +08:00
}
2023-01-12 08:04:46 +08:00
if result == :failed || result == :failed_no_topic
2022-11-02 21:41:30 +08:00
Discourse . warn_exception (
2023-01-12 08:04:46 +08:00
error_message ,
2022-11-02 21:41:30 +08:00
message : " Error when archiving chat channel #{ chat_channel_title } . " ,
env : {
chat_channel_id : chat_channel . id ,
chat_channel_name : chat_channel_title ,
} ,
)
error_translation_params =
base_translation_params . merge (
channel_url : chat_channel . url ,
messages_archived : chat_channel_archive . archived_messages ,
)
2023-01-12 08:04:46 +08:00
chat_channel_archive . update ( archive_error : error_message )
message_translation_key =
case result
when :failed
:chat_channel_archive_failed
when :failed_no_topic
:chat_channel_archive_failed_no_topic
end
2022-11-02 21:41:30 +08:00
SystemMessage . create_from_system_user (
chat_channel_archive . archived_by ,
2023-01-12 08:04:46 +08:00
message_translation_key ,
2022-11-02 21:41:30 +08:00
error_translation_params ,
)
else
SystemMessage . create_from_system_user (
chat_channel_archive . archived_by ,
:chat_channel_archive_complete ,
base_translation_params ,
)
end
ChatPublisher . publish_archive_status (
chat_channel ,
2023-01-12 08:04:46 +08:00
archive_status : result != :success ? :failed : :success ,
2022-11-02 21:41:30 +08:00
archived_messages : chat_channel_archive . archived_messages ,
archive_topic_id : chat_channel_archive . destination_topic_id ,
total_messages : chat_channel_archive . total_messages ,
)
end
def kick_all_users
Chat :: ChatChannelMembershipManager . new ( chat_channel ) . unfollow_all_users
end
2023-01-16 08:20:37 +08:00
def channel_hashtag_or_name
if chat_channel . slug . present? && SiteSetting . enable_experimental_hashtag_autocomplete
return " # #{ chat_channel . slug } ::channel "
end
chat_channel_title
end
2022-11-02 21:41:30 +08:00
end