2019-05-02 18:17:27 -04:00
# frozen_string_literal: true
2013-08-23 02:21:52 -04:00
require " digest/sha1 "
require " fileutils "
2022-03-21 10:28:52 -04:00
require " plugin/metadata "
require " auth "
2013-08-23 02:21:52 -04:00
2016-07-22 12:59:43 -04:00
class Plugin :: CustomEmoji
2020-03-30 14:16:10 -04:00
CACHE_KEY || = " plugin-emoji "
2016-07-22 12:59:43 -04:00
def self . cache_key
2020-03-30 14:16:10 -04:00
@@cache_key || = CACHE_KEY
2016-07-22 12:59:43 -04:00
end
def self . emojis
@@emojis || = { }
end
2020-03-30 14:16:10 -04:00
def self . clear_cache
@@cache_key = CACHE_KEY
@@emojis = { }
2020-05-27 14:11:52 -04:00
@@translations = { }
2016-07-22 12:59:43 -04:00
end
2019-01-04 09:14:16 -05:00
2020-03-30 14:16:10 -04:00
def self . register ( name , url , group = Emoji :: DEFAULT_GROUP )
@@cache_key = Digest :: SHA1 . hexdigest ( cache_key + name + group ) [ 0 .. 10 ]
new_group = emojis [ group ] || { }
new_group [ name ] = url
emojis [ group ] = new_group
end
def self . unregister ( name , group = Emoji :: DEFAULT_GROUP )
emojis [ group ] . delete ( name )
2019-07-03 03:23:40 -04:00
end
2020-05-27 06:08:24 -04:00
def self . translations
@@translations || = { }
end
def self . translate ( from , to )
@@cache_key = Digest :: SHA1 . hexdigest ( cache_key + from ) [ 0 .. 10 ]
translations [ from ] = to
end
2016-07-22 12:59:43 -04:00
end
2013-08-23 02:21:52 -04:00
class Plugin :: Instance
2013-08-25 21:04:16 -04:00
attr_accessor :path , :metadata
2015-02-06 17:32:59 -05:00
attr_reader :admin_route
2013-08-23 02:21:52 -04:00
2015-02-04 12:59:18 -05:00
# Memoized array readers
2023-01-09 07:10:19 -05:00
% i [
2017-01-12 15:43:09 -05:00
assets
initializers
javascripts
2018-01-25 06:09:18 -05:00
locales
2017-11-22 20:02:01 -05:00
service_workers
2017-01-12 15:43:09 -05:00
styles
2018-11-30 09:51:45 -05:00
themes
csp_extensions
2020-03-13 11:30:31 -04:00
asset_filters
2018-11-30 09:51:45 -05:00
] . each do | att |
2015-02-04 12:59:18 -05:00
class_eval %Q{
def #{att}
@ #{att} ||= []
end
}
end
2024-03-26 23:12:51 -04:00
def root_dir
return if Rails . env . production?
File . dirname ( path )
end
2016-07-22 12:59:43 -04:00
def seed_data
@seed_data || = HashWithIndifferentAccess . new ( { } )
2015-06-04 15:56:17 -04:00
end
2020-06-15 17:28:07 -04:00
def seed_fu_filter ( filter = nil )
@seed_fu_filter = filter
end
2023-12-15 14:47:20 -05:00
# This method returns Core stats + stats registered by plugins
def self . stats
Stat . all_stats
end
2013-08-23 02:21:52 -04:00
def self . find_all ( parent_path )
[ ] . tap do | plugins |
2013-10-21 05:18:24 -04:00
# also follows symlinks - http://stackoverflow.com/q/357754
2023-11-22 17:40:55 -05:00
Dir [ " #{ parent_path } /*/plugin.rb " ] . sort . each { | path | plugins << parse_from_source ( path ) }
2023-01-09 07:10:19 -05:00
end
2013-08-23 02:21:52 -04:00
end
2023-11-22 17:40:55 -05:00
def self . parse_from_source ( path )
source = File . read ( path )
metadata = Plugin :: Metadata . parse ( source )
self . new ( metadata , path )
end
2013-08-25 21:04:16 -04:00
def initialize ( metadata = nil , path = nil )
2013-08-23 02:21:52 -04:00
@metadata = metadata
@path = path
2015-08-21 11:28:17 -04:00
@idx = 0
2013-08-23 02:21:52 -04:00
end
2019-12-05 14:57:18 -05:00
def register_anonymous_cache_key ( key , & block )
key_method = " key_ #{ key } "
2019-12-11 09:07:22 -05:00
add_to_class ( Middleware :: AnonymousCache :: Helper , key_method , & block )
2019-12-05 14:57:18 -05:00
Middleware :: AnonymousCache . cache_key_segments [ key ] = key_method
Middleware :: AnonymousCache . compile_key_builder
end
2024-03-12 23:15:12 -04:00
def add_admin_route ( label , location , opts = { } )
@admin_route = {
label : label ,
location : location ,
use_new_show_route : opts . fetch ( :use_new_show_route , false ) ,
}
end
2023-05-10 09:21:48 -04:00
def configurable?
true
end
def visible?
configurable? && ! @hidden
end
2015-02-04 16:23:39 -05:00
def enabled?
2023-05-10 09:21:48 -04:00
return false if ! configurable?
2019-05-06 21:00:09 -04:00
@enabled_site_setting ? SiteSetting . get ( @enabled_site_setting ) : true
2013-08-25 21:04:16 -04:00
end
2024-01-07 18:57:25 -05:00
delegate :name , to : :metadata
def humanized_name
( setting_category_name || name ) . delete_prefix ( " Discourse " ) . delete_prefix ( " discourse- " )
end
2015-02-04 16:23:39 -05:00
2023-04-24 07:17:51 -04:00
def add_to_serializer (
serializer ,
attr ,
deprecated_respect_plugin_enabled = nil ,
respect_plugin_enabled : true ,
include_condition : nil ,
& block
)
if ! deprecated_respect_plugin_enabled . nil?
Discourse . deprecate (
" add_to_serializer's respect_plugin_enabled argument should be passed as a keyword argument " ,
)
respect_plugin_enabled = deprecated_respect_plugin_enabled
end
if attr . to_s . starts_with? ( " include_ " )
Discourse . deprecate (
" add_to_serializer should not be used to directly override include_*? methods. Use the include_condition keyword argument instead " ,
)
end
2017-08-09 16:22:18 -04:00
reloadable_patch do | plugin |
2019-08-27 04:21:53 -04:00
base =
2023-01-09 07:10:19 -05:00
begin
2019-08-27 04:21:53 -04:00
" #{ serializer . to_s . classify } Serializer " . constantize
rescue StandardError
2023-12-06 17:25:00 -05:00
" #{ serializer } Serializer " . constantize
2023-01-09 07:10:19 -05:00
end
2015-04-23 13:33:29 -04:00
2019-08-27 04:21:53 -04:00
# we have to work through descendants cause serializers may already be baked and cached
( [ base ] + base . descendants ) . each do | klass |
unless attr . to_s . start_with? ( " include_ " )
klass . attributes ( attr )
2015-04-23 13:33:29 -04:00
2023-04-24 07:17:51 -04:00
if respect_plugin_enabled || include_condition
2019-08-27 04:21:53 -04:00
# Don't include serialized methods if the plugin is disabled
2023-04-24 07:17:51 -04:00
klass . public_send ( :define_method , " include_ #{ attr } ? " ) do
next false if respect_plugin_enabled && ! plugin . enabled?
next instance_exec ( & include_condition ) if include_condition
true
end
2019-08-27 04:21:53 -04:00
end
2017-08-09 16:22:18 -04:00
end
2019-08-27 04:21:53 -04:00
klass . public_send ( :define_method , attr , & block )
end
2017-08-09 12:28:32 -04:00
end
2015-02-04 16:23:39 -05:00
end
2023-03-29 23:39:55 -04:00
def register_modifier ( modifier_name , & blk )
DiscoursePluginRegistry . register_modifier ( self , modifier_name , & blk )
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2018-06-19 09:00:11 -04:00
def add_report ( name , & block )
2018-07-25 11:44:09 -04:00
reloadable_patch { | plugin | Report . add_report ( name , & block ) }
2018-06-19 09:00:11 -04:00
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2020-07-02 10:47:43 -04:00
def replace_flags ( settings : :: FlagSettings . new , score_type_names : [ ] )
2024-05-22 22:19:07 -04:00
Discourse . deprecate (
" replace flags should not be used as flags were moved to the database. Instead, a flag record should be added to the database. Alternatively, soon, the admin will be able to do this in the admin panel. " ,
)
2020-01-17 09:59:38 -05:00
next_flag_id = ReviewableScore . types . values . max + 1
2020-07-03 15:21:06 -04:00
yield ( settings , next_flag_id ) if block_given?
2017-10-17 13:31:45 -04:00
reloadable_patch do | plugin |
2018-07-25 11:44:09 -04:00
:: PostActionType . replace_flag_settings ( settings )
2020-01-17 09:59:38 -05:00
:: ReviewableScore . reload_types
2020-07-02 10:47:43 -04:00
:: ReviewableScore . add_new_types ( score_type_names )
2017-10-17 13:31:45 -04:00
end
end
2020-07-26 20:23:54 -04:00
def allow_staff_user_custom_field ( field )
2020-05-15 09:04:38 -04:00
DiscoursePluginRegistry . register_staff_user_custom_field ( field , self )
2016-03-11 15:52:18 -05:00
end
2020-07-26 20:23:54 -04:00
def allow_public_user_custom_field ( field )
2020-05-15 09:04:38 -04:00
DiscoursePluginRegistry . register_public_user_custom_field ( field , self )
2018-10-17 05:33:27 -04:00
end
2023-10-09 23:23:56 -04:00
def register_editable_topic_custom_field ( field , staff_only : false )
if staff_only
DiscoursePluginRegistry . register_staff_editable_topic_custom_field ( field , self )
else
DiscoursePluginRegistry . register_public_editable_topic_custom_field ( field , self )
end
end
2019-10-11 04:57:55 -04:00
def register_editable_user_custom_field ( field , staff_only : false )
2020-05-15 09:04:38 -04:00
if staff_only
DiscoursePluginRegistry . register_staff_editable_user_custom_field ( field , self )
else
DiscoursePluginRegistry . register_self_editable_user_custom_field ( field , self )
2018-09-04 06:45:36 -04:00
end
end
2019-06-05 22:05:33 -04:00
def register_editable_group_custom_field ( field )
2020-05-15 09:04:38 -04:00
DiscoursePluginRegistry . register_editable_group_custom_field ( field , self )
2019-06-05 22:05:33 -04:00
end
2024-07-17 12:36:38 -04:00
# Allows to define custom filter utilizing the user's input.
# Ensure proper input sanitization before using it in a query.
#
# Example usage:
# add_filter_custom_filter("word_count") do |scope, value|
# scope.where(word_count: value)
# end
def add_filter_custom_filter ( name , & block )
DiscoursePluginRegistry . register_custom_filter_mapping ( { name = > block } , self )
end
2024-04-26 06:53:17 -04:00
# Allows to define custom "status:" filter. Example usage:
# register_custom_filter_by_status("foobar") do |scope|
# scope.where("word_count = 42")
# end
def register_custom_filter_by_status ( status , & block )
TopicsFilter . add_filter_by_status ( status , & block )
end
2020-08-06 22:47:00 -04:00
# Allows to define custom search order. Example usage:
# Search.advanced_order(:chars) do |posts|
# posts.reorder("(SELECT LENGTH(raw) FROM posts WHERE posts.topic_id = subquery.topic_id) DESC")
# end
def register_search_advanced_order ( trigger , & block )
Search . advanced_order ( trigger , & block )
end
# Allows to define custom search filters. Example usage:
# Search.advanced_filter(/^min_chars:(\d+)$/) do |posts, match|
# posts.where("(SELECT LENGTH(p2.raw) FROM posts p2 WHERE p2.id = posts.id) >= ?", match.to_i)
# end
def register_search_advanced_filter ( trigger , & block )
Search . advanced_filter ( trigger , & block )
end
2021-05-09 18:57:58 -04:00
# Allows to define TopicView posts filters. Example usage:
# TopicView.advanced_filter do |posts, opts|
# posts.where(wiki: true)
# end
def register_topic_view_posts_filter ( trigger , & block )
TopicView . add_custom_filter ( trigger , & block )
end
2021-08-25 06:16:08 -04:00
# Allows to add more user IDs to the list of preloaded users. This can be
# useful to efficiently change the list of posters or participants.
# Example usage:
# register_topic_list_preload_user_ids do |topics, user_ids, topic_list|
# user_ids << Discourse::SYSTEM_USER_ID
# end
def register_topic_list_preload_user_ids ( & block )
TopicList . on_preload_user_ids ( & block )
end
2020-09-13 21:58:28 -04:00
# Allow to eager load additional tables in Search. Useful to avoid N+1 performance problems.
# Example usage:
# register_search_topic_eager_load do |opts|
# %i(example_table)
# end
# OR
# register_search_topic_eager_load(%i(example_table))
def register_search_topic_eager_load ( tables = nil , & block )
Search . custom_topic_eager_load ( tables , & block )
end
2020-05-23 00:56:13 -04:00
# Request a new size for topic thumbnails
# Will respect plugin enabled setting is enabled
# Size should be an array with two elements [max_width, max_height]
def register_topic_thumbnail_size ( size )
if ! ( size . kind_of? ( Array ) && size . length == 2 )
raise ArgumentError . new ( " Topic thumbnail dimension is not valid " )
end
DiscoursePluginRegistry . register_topic_thumbnail_size ( size , self )
end
2021-07-19 01:54:19 -04:00
# Register a callback to add custom payload to Site#categories
# Example usage:
# register_site_categories_callback do |categories|
# categories.each do |category|
# category[:some_field] = 'test'
# end
# end
def register_site_categories_callback ( & block )
Site . add_categories_callbacks ( & block )
end
2022-02-16 02:00:30 -05:00
def register_upload_unused ( & block )
Upload . add_unused_callback ( & block )
end
def register_upload_in_use ( & block )
Upload . add_in_use_callback ( & block )
end
2023-10-26 09:34:23 -04:00
# Registers a category custom field to be loaded when rendering a category list
# Example usage:
2023-11-09 11:23:24 -05:00
# register_preloaded_category_custom_fields("custom_field")
def register_preloaded_category_custom_fields ( field )
Site . preloaded_category_custom_fields << field
2023-10-26 09:34:23 -04:00
end
2024-03-28 02:00:47 -04:00
def register_problem_check ( klass )
DiscoursePluginRegistry . register_problem_check ( klass , self )
end
2017-08-30 14:24:03 -04:00
def custom_avatar_column ( column )
reloadable_patch do | plugin |
2020-07-17 05:48:08 -04:00
UserLookup . lookup_columns << column
UserLookup . lookup_columns . uniq!
2017-08-30 14:24:03 -04:00
end
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2017-09-28 13:16:51 -04:00
def add_body_class ( class_name )
2018-07-25 11:44:09 -04:00
reloadable_patch { | plugin | :: ApplicationHelper . extra_body_classes << class_name }
2017-09-28 13:16:51 -04:00
end
2017-10-02 12:04:59 -04:00
def rescue_from ( exception , & block )
reloadable_patch { | plugin | :: ApplicationController . rescue_from ( exception , & block ) }
end
2015-02-04 16:23:39 -05:00
# Extend a class but check that the plugin is enabled
2015-08-21 11:28:17 -04:00
# for class methods use `add_class_method`
2017-08-09 12:28:32 -04:00
def add_to_class ( class_name , attr , & block )
2017-08-09 16:22:18 -04:00
reloadable_patch do | plugin |
2017-08-09 12:28:32 -04:00
klass =
2023-01-09 07:10:19 -05:00
begin
2017-08-09 12:28:32 -04:00
class_name . to_s . classify . constantize
rescue StandardError
class_name . to_s . constantize
2023-01-09 07:10:19 -05:00
end
2017-08-09 12:28:32 -04:00
hidden_method_name = :" #{ attr } _without_enable_check "
2019-05-06 21:27:05 -04:00
klass . public_send ( :define_method , hidden_method_name , & block )
2017-08-09 12:28:32 -04:00
2022-12-21 12:02:40 -05:00
klass . public_send ( :define_method , attr ) do | * args , ** kwargs |
public_send ( hidden_method_name , * args , ** kwargs ) if plugin . enabled?
2017-08-09 12:28:32 -04:00
end
2015-02-04 16:23:39 -05:00
end
2015-01-12 10:52:55 -05:00
end
2015-08-21 11:28:17 -04:00
# Adds a class method to a class, respecting if plugin is enabled
2017-08-09 12:28:32 -04:00
def add_class_method ( klass_name , attr , & block )
2017-08-09 16:22:18 -04:00
reloadable_patch do | plugin |
2017-08-09 12:28:32 -04:00
klass =
2023-01-09 07:10:19 -05:00
begin
2017-08-09 12:28:32 -04:00
klass_name . to_s . classify . constantize
rescue StandardError
klass_name . to_s . constantize
2023-01-09 07:10:19 -05:00
end
2015-08-21 11:28:17 -04:00
2017-08-09 12:28:32 -04:00
hidden_method_name = :" #{ attr } _without_enable_check "
2019-05-06 21:27:05 -04:00
klass . public_send ( :define_singleton_method , hidden_method_name , & block )
2015-08-21 11:28:17 -04:00
2022-12-21 12:02:40 -05:00
klass . public_send ( :define_singleton_method , attr ) do | * args , ** kwargs |
public_send ( hidden_method_name , * args , ** kwargs ) if plugin . enabled?
2017-08-09 12:28:32 -04:00
end
2015-08-21 11:28:17 -04:00
end
end
2017-08-09 12:28:32 -04:00
def add_model_callback ( klass_name , callback , options = { } , & block )
2017-08-09 16:22:18 -04:00
reloadable_patch do | plugin |
2017-08-09 12:28:32 -04:00
klass =
2023-01-09 07:10:19 -05:00
begin
2017-08-09 12:28:32 -04:00
klass_name . to_s . classify . constantize
rescue StandardError
klass_name . to_s . constantize
2023-01-09 07:10:19 -05:00
end
2015-08-21 11:28:17 -04:00
2017-08-09 12:28:32 -04:00
# generate a unique method name
method_name = " #{ plugin . name } _ #{ klass . name } _ #{ callback } #{ @idx } " . underscore
@idx += 1
hidden_method_name = :" #{ method_name } _without_enable_check "
2019-05-06 21:27:05 -04:00
klass . public_send ( :define_method , hidden_method_name , & block )
2015-08-21 11:28:17 -04:00
2022-12-21 12:02:40 -05:00
klass . public_send ( callback , ** options ) do | * args , ** kwargs |
public_send ( hidden_method_name , * args , ** kwargs ) if plugin . enabled?
2017-08-09 12:28:32 -04:00
end
2015-08-21 11:28:17 -04:00
2017-08-09 12:28:32 -04:00
hidden_method_name
end
2015-08-21 11:28:17 -04:00
end
2020-07-26 20:23:54 -04:00
# Add a post_custom_fields_allowlister block to the TopicView, respecting if the plugin is enabled
def topic_view_post_custom_fields_allowlister ( & block )
2017-08-11 22:21:02 -04:00
reloadable_patch do | plugin |
2021-10-21 22:22:09 -04:00
:: TopicView . add_post_custom_fields_allowlister do | user , topic |
plugin . enabled? ? block . call ( user , topic ) : [ ]
2018-07-25 11:44:09 -04:00
end
2017-08-11 22:21:02 -04:00
end
end
2020-08-04 05:57:33 -04:00
# Allows to add additional user_ids to the list of people notified when doing a post revision
def add_post_revision_notifier_recipients ( & block )
reloadable_patch do | plugin |
:: PostActionNotifier . add_post_revision_notifier_recipients do | post_revision |
plugin . enabled? ? block . call ( post_revision ) : [ ]
end
end
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2017-08-11 22:21:02 -04:00
def add_preloaded_group_custom_field ( field )
2018-07-25 11:44:09 -04:00
reloadable_patch { | plugin | :: Group . preloaded_custom_field_names << field }
2017-08-11 22:21:02 -04:00
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2017-08-11 22:21:02 -04:00
def add_preloaded_topic_list_custom_field ( field )
2018-07-25 11:44:09 -04:00
reloadable_patch { | plugin | :: TopicList . preloaded_custom_fields << field }
2017-08-11 22:21:02 -04:00
end
2018-07-25 11:44:09 -04:00
# Add a permitted_create_param to Post, respecting if the plugin is enabled
2019-12-20 11:37:12 -05:00
def add_permitted_post_create_param ( name , type = :string )
2017-08-11 22:21:02 -04:00
reloadable_patch do | plugin |
2019-12-20 11:37:12 -05:00
:: Post . plugin_permitted_create_params [ name ] = { plugin : plugin , type : type }
2017-08-11 22:21:02 -04:00
end
end
2021-03-24 11:22:16 -04:00
# Add a permitted_update_param to Post, respecting if the plugin is enabled
def add_permitted_post_update_param ( attribute , & block )
reloadable_patch do | plugin |
:: Post . plugin_permitted_update_params [ attribute ] = { plugin : plugin , handler : block }
end
end
2021-09-05 20:18:51 -04:00
# Add a permitted_param to Group, respecting if the plugin is enabled
# Used in GroupsController#update and Admin::GroupsController#create
def register_group_param ( param )
DiscoursePluginRegistry . register_group_param ( param , self )
end
2021-09-07 19:38:45 -04:00
# Add a custom callback for search to Group
# Callback is called in UsersController#search_users
# Block takes groups and optional current_user
# For example:
# plugin.register_groups_callback_for_users_search_controller_action(:admins_filter) do |groups, user|
# groups.where(name: "admins")
# end
def register_groups_callback_for_users_search_controller_action ( callback , & block )
if DiscoursePluginRegistry . groups_callback_for_users_search_controller_action . key? ( callback )
raise " groups_callback_for_users_search_controller_action callback already registered "
end
DiscoursePluginRegistry . groups_callback_for_users_search_controller_action [ callback ] = block
2021-09-05 20:18:51 -04:00
end
2015-04-23 13:33:29 -04:00
# Add validation method but check that the plugin is enabled
2015-04-25 18:12:19 -04:00
def validate ( klass , name , & block )
2015-04-23 13:33:29 -04:00
klass = klass . to_s . classify . constantize
2019-05-06 21:27:05 -04:00
klass . public_send ( :define_method , name , & block )
2015-04-23 13:33:29 -04:00
plugin = self
2015-04-25 18:12:19 -04:00
klass . validate ( name , if : - > { plugin . enabled? } )
2015-04-23 13:33:29 -04:00
end
2013-08-23 02:21:52 -04:00
# will make sure all the assets this plugin needs are registered
def generate_automatic_assets!
paths = [ ]
2015-11-06 09:02:40 -05:00
assets = [ ]
2013-08-23 02:21:52 -04:00
automatic_assets . each do | path , contents |
2015-11-06 09:02:40 -05:00
write_asset ( path , contents )
paths << path
2019-09-16 12:06:34 -04:00
assets << [ path , nil , directory_name ]
2015-11-06 09:02:40 -05:00
end
2013-08-23 02:21:52 -04:00
delete_extra_automatic_assets ( paths )
2015-11-06 09:02:40 -05:00
assets
2013-08-23 02:21:52 -04:00
end
2021-06-22 14:00:04 -04:00
def add_directory_column ( column_name , query : , icon : nil )
validate_directory_column_name ( column_name )
DiscourseEvent . on ( " before_directory_refresh " ) do
DirectoryColumn . find_or_create_plugin_directory_column (
column_name : column_name ,
icon : icon ,
query : query ,
)
end
end
2013-08-23 02:21:52 -04:00
def delete_extra_automatic_assets ( good_paths )
2022-01-05 12:45:08 -05:00
return unless Dir . exist? auto_generated_path
2013-09-20 17:39:14 -04:00
2013-08-23 02:21:52 -04:00
filenames = good_paths . map { | f | File . basename ( f ) }
# nuke old files
Dir . foreach ( auto_generated_path ) do | p |
next if %w[ . .. ] . include? ( p )
next if filenames . include? ( p )
File . delete ( auto_generated_path + " / #{ p } " )
end
end
def ensure_directory ( path )
dirname = File . dirname ( path )
FileUtils . mkdir_p ( dirname ) unless File . directory? ( dirname )
end
2017-01-12 15:43:09 -05:00
def directory
File . dirname ( path )
end
2013-08-23 02:21:52 -04:00
def auto_generated_path
File . dirname ( path ) << " /auto_generated "
end
2013-09-16 20:23:21 -04:00
def after_initialize ( & block )
2015-02-04 12:59:18 -05:00
initializers << block
2013-09-16 20:23:21 -04:00
end
2023-06-26 00:39:57 -04:00
def commit_hash
git_repo . latest_local_commit
end
def commit_url
return if commit_hash . blank?
" #{ git_repo . url } /commit/ #{ commit_hash } "
end
def git_repo
@git_repo || = GitRepo . new ( directory , name )
end
2023-11-20 18:37:11 -05:00
def discourse_owned?
2023-11-23 21:08:10 -05:00
return false if commit_hash . blank?
2023-11-20 18:37:11 -05:00
parsed_commit_url = UrlHelper . relaxed_parse ( self . commit_url )
2023-11-23 21:08:10 -05:00
return false if parsed_commit_url . blank?
2023-11-20 18:37:11 -05:00
github_org = parsed_commit_url . path . split ( " / " ) [ 1 ]
( github_org == " discourse " || github_org == " discourse-org " ) &&
parsed_commit_url . host == " github.com "
end
2015-02-04 16:23:39 -05:00
# A proxy to `DiscourseEvent.on` which does nothing if the plugin is disabled
def on ( event_name , & block )
2022-12-21 12:02:40 -05:00
DiscourseEvent . on ( event_name ) { | * args , ** kwargs | block . call ( * args , ** kwargs ) if enabled? }
2015-02-04 16:23:39 -05:00
end
2024-07-31 14:38:10 -04:00
# A proxy to `DiscourseEvent.on(:site_setting_changed)` triggered when the plugin enabled setting specified by
# `enabled_site_setting` value is changed, including when the plugin is turned off.
#
# It is useful when the plugin needs to perform tasks like properly clearing caches when enabled/disabled
# note it will not be triggered when a plugin is installed/uninstalled by adding/removing its code
def on_enabled_change ( & block )
event_proc =
Proc . new do | setting_name , old_value , new_value |
block . call ( old_value , new_value ) if setting_name == @enabled_site_setting
end
DiscourseEvent . on ( :site_setting_changed , & event_proc )
# returns the block to be used for DiscourseEvent.off(:site_setting_changed, &block) for testing purposes
event_proc
end
2013-09-16 20:23:21 -04:00
def notify_after_initialize
2015-02-04 12:59:18 -05:00
initializers . each do | callback |
2015-08-25 16:38:25 -04:00
begin
callback . call ( self )
rescue ActiveRecord :: StatementInvalid = > e
2017-08-11 22:21:02 -04:00
# When running `db:migrate` for the first time on a new database,
# plugin initializers might try to use models.
# Tolerate it.
2015-08-25 16:38:25 -04:00
raise e unless e . message . try ( :include? , " PG::UndefinedTable " )
end
2013-09-16 20:23:21 -04:00
end
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2023-11-29 15:17:12 -05:00
def register_category_custom_field_type ( name , type , max_length : nil )
reloadable_patch do | plugin |
Category . register_custom_field_type ( name , type , max_length : max_length )
end
2017-08-17 02:59:31 -04:00
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2023-11-29 15:17:12 -05:00
def register_topic_custom_field_type ( name , type , max_length : nil )
reloadable_patch do | plugin |
:: Topic . register_custom_field_type ( name , type , max_length : max_length )
end
2017-08-11 22:21:02 -04:00
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2023-11-29 15:17:12 -05:00
def register_post_custom_field_type ( name , type , max_length : nil )
reloadable_patch do | plugin |
:: Post . register_custom_field_type ( name , type , max_length : max_length )
end
2017-08-11 22:21:02 -04:00
end
2018-07-25 11:44:09 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2023-11-29 15:17:12 -05:00
def register_group_custom_field_type ( name , type , max_length : nil )
reloadable_patch do | plugin |
:: Group . register_custom_field_type ( name , type , max_length : max_length )
end
2017-08-11 22:21:02 -04:00
end
2019-07-24 12:38:44 -04:00
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
2023-11-29 15:17:12 -05:00
def register_user_custom_field_type ( name , type , max_length : nil )
reloadable_patch do | plugin |
:: User . register_custom_field_type ( name , type , max_length : max_length )
end
2019-07-24 12:38:44 -04:00
end
2016-10-25 02:55:53 -04:00
def register_seedfu_fixtures ( paths )
paths = [ paths ] if ! paths . kind_of? ( Array )
SeedFu . fixture_paths . concat ( paths )
end
2020-06-15 17:28:07 -04:00
def register_seedfu_filter ( filter = nil )
DiscoursePluginRegistry . register_seedfu_filter ( filter )
end
2014-12-11 11:08:47 -05:00
def listen_for ( event_name )
return unless self . respond_to? ( event_name )
DiscourseEvent . on ( event_name , & self . method ( event_name ) )
end
2013-08-23 02:21:52 -04:00
def register_css ( style )
2015-02-04 12:59:18 -05:00
styles << style
2013-08-23 02:21:52 -04:00
end
def register_javascript ( js )
2015-02-04 12:59:18 -05:00
javascripts << js
2013-08-23 02:21:52 -04:00
end
2018-11-26 16:49:57 -05:00
def register_svg_icon ( icon )
DiscoursePluginRegistry . register_svg_icon ( icon )
end
2018-11-30 09:51:45 -05:00
def extend_content_security_policy ( extension )
csp_extensions << extension
end
2020-03-13 11:30:31 -04:00
# Register a block to run when adding css and js assets
# Two arguments will be passed: (type, request)
# Type is :css or :js. `request` is an instance of Rack::Request
# When using this, make sure to consider the effect on AnonymousCache
def register_asset_filter ( & blk )
asset_filters << blk
end
2018-01-25 06:09:18 -05:00
# @option opts [String] :name
# @option opts [String] :nativeName
# @option opts [String] :fallbackLocale
# @option opts [Hash] :plural
def register_locale ( locale , opts = { } )
locales << [ locale , opts ]
end
2014-06-04 21:39:33 -04:00
def register_custom_html ( hash )
DiscoursePluginRegistry . custom_html . merge! ( hash )
end
2017-04-17 15:47:21 -04:00
def register_html_builder ( name , & block )
2019-12-04 12:26:23 -05:00
plugin = self
2022-12-21 12:02:40 -05:00
DiscoursePluginRegistry . register_html_builder ( name ) do | * args , ** kwargs |
block . call ( * args , ** kwargs ) if plugin . enabled?
2019-12-04 12:26:23 -05:00
end
2017-04-17 15:47:21 -04:00
end
2023-06-26 01:16:03 -04:00
def register_email_poller ( poller )
plugin = self
DiscoursePluginRegistry . register_mail_poller ( poller ) if plugin . enabled?
end
2014-04-07 10:33:35 -04:00
def register_asset ( file , opts = nil )
2022-11-24 14:03:06 -05:00
raise << ~ ERROR if file . end_with? ( " .hbs " , " .handlebars " )
[ #{name}] Handlebars templates can no longer be included via `register_asset`.
Any hbs files under ` assets/javascripts ` will be automatically compiled and included . "
ERROR
2024-02-01 06:48:31 -05:00
raise << ~ ERROR if file . start_with? ( " javascripts/ " ) && file . end_with? ( " .js " , " .js.es6 " )
[ #{name}] Javascript files under `assets/javascripts` are automatically included in JS bundles.
Manual register_asset calls should be removed . ( attempted to add #{file})
ERROR
2018-04-10 02:37:16 -04:00
if opts && opts == :vendored_core_pretty_text
full_path = DiscoursePluginRegistry . core_asset_for_name ( file )
else
full_path = File . dirname ( path ) << " /assets/ " << file
end
2019-08-20 12:39:52 -04:00
assets << [ full_path , opts , directory_name ]
2013-08-23 02:21:52 -04:00
end
2017-11-22 20:02:01 -05:00
def register_service_worker ( file , opts = nil )
service_workers << [ File . join ( File . dirname ( path ) , " assets " , file ) , opts ]
end
2015-06-04 15:56:17 -04:00
def register_seed_data ( key , value )
seed_data [ key ] = value
end
2014-06-03 12:36:34 -04:00
2017-11-16 14:42:38 -05:00
def register_seed_path_builder ( & block )
DiscoursePluginRegistry . register_seed_path_builder ( & block )
end
2020-03-30 14:16:10 -04:00
def register_emoji ( name , url , group = Emoji :: DEFAULT_GROUP )
2024-05-27 09:24:55 -04:00
name = Emoji . sanitize_emoji_name ( name )
2020-03-30 14:16:10 -04:00
Plugin :: CustomEmoji . register ( name , url , group )
Emoji . clear_cache
2015-11-05 11:25:26 -05:00
end
2020-05-27 06:08:24 -04:00
def translate_emoji ( from , to )
Plugin :: CustomEmoji . translate ( from , to )
end
2013-08-23 02:21:52 -04:00
def automatic_assets
2015-02-04 12:59:18 -05:00
css = styles . join ( " \n " )
js = javascripts . join ( " \n " )
2013-08-23 02:21:52 -04:00
2015-11-06 09:02:40 -05:00
# Generate an IIFE for the JS
js = " (function(){ #{ js } })(); " if js . present?
result = [ ]
result << [ css , " css " ] if css . present?
result << [ js , " js " ] if js . present?
result . map do | asset , extension |
hash = Digest :: SHA1 . hexdigest asset
[ " #{ auto_generated_path } /plugin_ #{ hash } . #{ extension } " , asset ]
end
end
2021-05-20 21:43:47 -04:00
# note, we need to be able to parse separately to activation.
2013-08-23 02:21:52 -04:00
# this allows us to present information about a plugin in the UI
# prior to activations
def activate!
2013-09-11 21:27:13 -04:00
self . instance_eval File . read ( path ) , path
2013-08-23 02:21:52 -04:00
if auto_assets = generate_automatic_assets!
2015-11-06 09:02:40 -05:00
assets . concat ( auto_assets )
2013-08-23 02:21:52 -04:00
end
2014-12-30 16:29:28 -05:00
2024-05-27 06:27:13 -04:00
register_assets! if assets . present?
2018-01-25 06:09:18 -05:00
register_locales!
2017-11-22 20:02:01 -05:00
register_service_workers!
2015-06-04 15:56:17 -04:00
seed_data . each { | key , value | DiscoursePluginRegistry . register_seed_data ( key , value ) }
2024-02-02 14:06:16 -05:00
# Allow plugins to `register_asset` for images under /assets
Rails . configuration . assets . paths << File . dirname ( path ) + " /assets "
2015-05-04 10:01:57 -04:00
# Automatically include rake tasks
Rake . add_rakelib ( File . dirname ( path ) + " /lib/tasks " )
# Automatically include migrations
2019-12-16 14:11:55 -05:00
migration_paths = ActiveRecord :: Tasks :: DatabaseTasks . migrations_paths
2018-10-09 01:11:45 -04:00
migration_paths << File . dirname ( path ) + " /db/migrate "
unless Discourse . skip_post_deployment_migrations?
migration_paths << " #{ File . dirname ( path ) } / #{ Discourse :: DB_POST_MIGRATE_PATH } "
end
2015-05-04 10:01:57 -04:00
2013-11-19 22:38:21 -05:00
public_data = File . dirname ( path ) + " /public "
2022-01-05 12:45:08 -05:00
if Dir . exist? ( public_data )
2013-11-19 22:38:21 -05:00
target = Rails . root . to_s + " /public/plugins/ "
2017-03-17 02:21:30 -04:00
Discourse :: Utils . execute_command ( " mkdir " , " -p " , target )
2014-01-17 18:35:52 -05:00
target << name . gsub ( / \ s / , " _ " )
2020-03-04 12:28:26 -05:00
Discourse :: Utils . atomic_ln_s ( public_data , target )
2013-11-19 22:38:21 -05:00
end
2019-07-15 10:52:54 -04:00
2024-02-01 06:48:31 -05:00
write_extra_js!
2013-08-23 02:21:52 -04:00
end
2013-08-25 22:52:36 -04:00
def auth_provider ( opts )
2023-10-26 05:54:30 -04:00
after_initialize do
2018-11-30 11:58:18 -05:00
provider = Auth :: AuthProvider . new
2015-09-25 11:29:05 -04:00
2018-11-30 11:58:18 -05:00
Auth :: AuthProvider . auth_attributes . each do | sym |
2019-05-06 22:05:58 -04:00
provider . public_send ( " #{ sym } = " , opts . delete ( sym ) ) if opts . has_key? ( sym )
2018-11-30 11:58:18 -05:00
end
2018-07-23 11:51:57 -04:00
2018-11-30 11:58:18 -05:00
DiscoursePluginRegistry . register_auth_provider ( provider )
end
2013-08-23 02:21:52 -04:00
end
# shotgun approach to gem loading, in future we need to hack bundler
# to at least determine dependencies do not clash before loading
#
# Additionally we want to support multiple ruby versions correctly and so on
#
# This is a very rough initial implementation
def gem ( name , version , opts = { } )
2017-01-09 17:10:14 -05:00
PluginGem . load ( path , name , version , opts )
2013-08-23 02:21:52 -04:00
end
2018-05-08 01:24:58 -04:00
def hide_plugin
2023-05-10 09:21:48 -04:00
@hidden = true
2018-05-07 22:30:33 -04:00
end
2015-07-02 12:45:17 -04:00
def enabled_site_setting ( setting = nil )
if setting
@enabled_site_setting = setting
else
@enabled_site_setting
end
2015-02-04 16:23:39 -05:00
end
2016-11-14 19:42:55 -05:00
def javascript_includes
assets
. map do | asset , opts |
2018-04-10 02:37:16 -04:00
next if opts == :vendored_core_pretty_text
2016-11-14 19:42:55 -05:00
next unless asset =~ DiscoursePluginRegistry :: JS_REGEX
asset
end
. compact
end
2019-01-03 12:03:01 -05:00
def register_reviewable_type ( reviewable_type_class )
2024-07-09 11:56:22 -04:00
return unless reviewable_type_class < Reviewable
extend_list_method ( Reviewable , :types , reviewable_type_class )
2019-04-08 13:42:36 -04:00
end
def extend_list_method ( klass , method , new_attributes )
2024-07-09 11:56:22 -04:00
register_name = [ klass , method ] . join ( " _ " ) . underscore
DiscoursePluginRegistry . define_filtered_register ( register_name )
DiscoursePluginRegistry . public_send (
" register_ #{ register_name . singularize } " ,
new_attributes ,
self ,
)
2019-01-03 12:03:01 -05:00
2024-07-09 11:56:22 -04:00
original_method_alias = " __original_ #{ method } __ "
return if klass . respond_to? ( original_method_alias )
reloadable_patch do
klass . singleton_class . alias_method ( original_method_alias , method )
klass . define_singleton_method ( method ) do
public_send ( original_method_alias ) |
DiscoursePluginRegistry . public_send ( register_name ) . flatten
end
end
2019-01-03 12:03:01 -05:00
end
2019-08-20 12:39:52 -04:00
def directory_name
@directory_name || = File . dirname ( path ) . split ( " / " ) . last
end
2019-08-21 23:09:10 -04:00
def css_asset_exists? ( target = nil )
DiscoursePluginRegistry . stylesheets_exists? ( directory_name , target )
2019-07-15 10:52:54 -04:00
end
def js_asset_exists?
2022-09-21 07:38:02 -04:00
# If assets/javascripts exists, ember-cli will output a .js file
File . exist? ( " #{ File . dirname ( @path ) } /assets/javascripts " )
2022-08-22 04:56:39 -04:00
end
def extra_js_asset_exists?
2022-09-21 07:38:02 -04:00
File . exist? ( extra_js_file_path )
2019-07-15 10:52:54 -04:00
end
2022-08-25 06:36:02 -04:00
def admin_js_asset_exists?
2022-09-21 07:38:02 -04:00
# If this directory exists, ember-cli will output a .js file
File . exist? ( " #{ File . dirname ( @path ) } /admin/assets/javascripts " )
2022-08-25 06:36:02 -04:00
end
2019-11-22 14:33:10 -05:00
# Receives an array with two elements:
# 1. A symbol that represents the name of the value to filter.
# 2. A Proc that takes the existing ActiveRecord::Relation and the value received from the front-end.
def add_custom_reviewable_filter ( filter )
reloadable_patch { Reviewable . add_custom_filter ( filter ) }
end
2021-02-17 12:42:44 -05:00
# Register a new API key scope.
#
# Example:
# add_api_key_scope(:groups, { delete: { actions: %w[groups#add_members], params: %i[id] } })
#
# This scope lets you add members to a group. Additionally, you can specify which group ids are allowed.
# The delete action is added to the groups resource.
2020-07-16 14:51:24 -04:00
def add_api_key_scope ( resource , action )
DiscoursePluginRegistry . register_api_key_scope_mapping ( { resource = > action } , self )
end
2020-10-09 09:52:48 -04:00
# Register a new UserApiKey scope, and its allowed routes. Scope will be prefixed
2021-05-20 21:43:47 -04:00
# with the (parameterized) plugin name followed by a colon.
2020-10-09 09:52:48 -04:00
#
# For example, if discourse-awesome-plugin registered this:
#
# add_user_api_key_scope(:read_my_route,
# methods: :get,
# actions: "mycontroller#myaction",
# formats: :ics,
2021-07-25 12:49:24 -04:00
# params: :testparam
2020-10-09 09:52:48 -04:00
# )
#
# The scope registered would be `discourse-awesome-plugin:read_my_route`
#
# Multiple matchers can be attached by supplying an array of parameter hashes
#
# See UserApiKeyScope::SCOPES for more examples
# And lib/route_matcher.rb for the route matching logic
def add_user_api_key_scope ( scope_name , matcher_parameters )
raise ArgumentError . new ( " scope_name must be a symbol " ) if ! scope_name . is_a? ( Symbol )
matcher_parameters = [ matcher_parameters ] if ! matcher_parameters . is_a? ( Array )
prefixed_scope_name = :" #{ ( name || directory_name ) . parameterize } : #{ scope_name } "
DiscoursePluginRegistry . register_user_api_key_scope_mapping (
{ prefixed_scope_name = > matcher_parameters & . map { | m | RouteMatcher . new ( ** m ) } } ,
self ,
)
end
2020-08-24 05:24:52 -04:00
# Register a route which can be authenticated using an api key or user api key
# in a query parameter rather than a header. For example:
#
# add_api_parameter_route(
2020-10-06 12:20:15 -04:00
# methods: :get,
# actions: "users#bookmarks",
# formats: :ics
2020-08-24 05:24:52 -04:00
# )
#
# See Auth::DefaultCurrentUserProvider::PARAMETER_API_PATTERNS for more examples
# and Auth::DefaultCurrentUserProvider#api_parameter_allowed? for implementation
2023-07-21 00:22:33 -04:00
def add_api_parameter_route ( methods : nil , actions : nil , formats : nil )
2020-10-06 12:20:15 -04:00
DiscoursePluginRegistry . register_api_parameter_route (
RouteMatcher . new ( methods : methods , actions : actions , formats : formats ) ,
self ,
)
2020-08-24 05:24:52 -04:00
end
2020-12-16 04:43:39 -05:00
# Register a new demon process to be forked by the Unicorn master.
# The demon_class should inherit from Demon::Base.
# With great power comes great responsibility - this method should
# be used with extreme caution. See `config/unicorn.conf.rb`.
def register_demon_process ( demon_class )
raise " Not a demon class " if ! demon_class . ancestors . include? ( Demon :: Base )
DiscoursePluginRegistry . demon_processes << demon_class
end
2021-03-02 11:28:27 -05:00
def add_permitted_reviewable_param ( type , param )
DiscoursePluginRegistry . register_reviewable_param ( { type : type , param : param } , self )
end
DEV: Introduce PresenceChannel API for core and plugin use
PresenceChannel aims to be a generic system for allow the server, and end-users, to track the number and identity of users performing a specific task on the site. For example, it might be used to track who is currently 'replying' to a specific topic, editing a specific wiki post, etc.
A few key pieces of information about the system:
- PresenceChannels are identified by a name of the format `/prefix/blah`, where `prefix` has been configured by some core/plugin implementation, and `blah` can be any string the implementation wants to use.
- Presence is a boolean thing - each user is either present, or not present. If a user has multiple clients 'present' in a channel, they will be deduplicated so that the user is only counted once
- Developers can configure the existence and configuration of channels 'just in time' using a callback. The result of this is cached for 2 minutes.
- Configuration of a channel can specify permissions in a similar way to MessageBus (public boolean, a list of allowed_user_ids, and a list of allowed_group_ids). A channel can also be placed in 'count_only' mode, where the identity of present users is not revealed to end-users.
- The backend implementation uses redis lua scripts, and is designed to scale well. In the future, hard limits may be introduced on the maximum number of users that can be present in a channel.
- Clients can enter/leave at will. If a client has not marked itself 'present' in the last 60 seconds, they will automatically 'leave' the channel. The JS implementation takes care of this regular check-in.
- On the client-side, PresenceChannel instances can be fetched from the `presence` ember service. Each PresenceChannel can be used entered/left/subscribed/unsubscribed, and the service will automatically deduplicate information before interacting with the server.
- When a client joins a PresenceChannel, the JS implementation will automatically make a GET request for the current channel state. To avoid this, the channel state can be serialized into one of your existing endpoints, and then passed to the `subscribe` method on the channel.
- The PresenceChannel JS object is an ember object. The `users` and `count` property can be used directly in ember templates, and in computed properties.
- It is important to make sure that you `unsubscribe()` and `leave()` any PresenceChannel objects after use
An example implementation may look something like this. On the server:
```ruby
register_presence_channel_prefix("site") do |channel|
next nil unless channel == "/site/online"
PresenceChannel::Config.new(public: true)
end
```
And on the client, a component could be implemented like this:
```javascript
import Component from "@ember/component";
import { inject as service } from "@ember/service";
export default Component.extend({
presence: service(),
init() {
this._super(...arguments);
this.set("presenceChannel", this.presence.getChannel("/site/online"));
},
didInsertElement() {
this.presenceChannel.enter();
this.presenceChannel.subscribe();
},
willDestroyElement() {
this.presenceChannel.leave();
this.presenceChannel.unsubscribe();
},
});
```
With this template:
```handlebars
Online: {{presenceChannel.count}}
<ul>
{{#each presenceChannel.users as |user|}}
<li>{{avatar user imageSize="tiny"}} {{user.username}}</li>
{{/each}}
</ul>
```
2021-08-27 09:43:39 -04:00
# Register a new PresenceChannel prefix. See {PresenceChannel.register_prefix}
# for usage instructions
def register_presence_channel_prefix ( prefix , & block )
DiscoursePluginRegistry . register_presence_channel_prefix ( [ prefix , block ] , self )
end
2023-11-08 11:29:00 -05:00
# Registers a new email notification filter. Notification is passed into block, and if all
# filters return `true`, the email notification will be sent.
def register_email_notification_filter ( & block )
DiscoursePluginRegistry . register_email_notification_filter ( block , self )
end
2021-11-03 13:21:33 -04:00
# Registers a new push notification filter. User and notification payload are passed into block, and if all
# filters return `true`, the push notification will be sent.
def register_push_notification_filter ( & block )
DiscoursePluginRegistry . register_push_notification_filter ( block , self )
end
2021-10-07 11:41:57 -04:00
# Register a ReviewableScore setting_name associated with a reason.
# We'll use this to build a site setting link and add it to the reason's translation.
#
# If your plugin has a reason translation looking like this:
#
# my_plugin_reason: "This is the reason this post was flagged. See %{link}."
#
# And you associate the reason with a setting:
#
# add_reviewable_score_link(:my_plugin_reason, 'a_plugin_setting')
#
# We'll generate the following link and attach it to the translation:
#
# <a href="/admin/site_settings/category/all_results?filter=a_plugin_setting">
# a plugin setting
# </a>
def add_reviewable_score_link ( reason , setting_name )
DiscoursePluginRegistry . register_reviewable_score_link (
{ reason : reason . to_sym , setting : setting_name } ,
self ,
)
end
REFACTOR: Improve support for consolidating notifications. (#14904)
* REFACTOR: Improve support for consolidating notifications.
Before this commit, we didn't have a single way of consolidating notifications. For notifications like group summaries, we manually removed old ones before creating a new one. On the other hand, we used an after_create callback for likes and group membership requests, which caused unnecessary work, as we need to delete the record we created to replace it with a consolidated one.
We now have all the consolidation rules centralized in a single place: the consolidation planner class. Other parts of the app looking to create a consolidable notification can do so by calling Notification#consolidate_or_save!, instead of the default Notification#create! method.
Finally, we added two more rules: one for re-using existing group summaries and another for deleting duplicated dashboard problems PMs notifications when the user is tracking the moderator's inbox. Setting the threshold to one forces the planner to apply this rule every time.
I plan to add plugin support for adding custom rules in another PR to keep this one relatively small.
* DEV: Introduces a plugin API for consolidating notifications.
This commit removes the `Notification#filter_by_consolidation_data` scope since plugins could have to define their criteria. The Plan class now receives two blocks, one to query for an already consolidated notification, which we'll try to update, and another to query for existing ones to consolidate.
It also receives a consolidation window, which accepts an ActiveSupport::Duration object, and filter notifications created since that value.
2021-11-30 11:36:14 -05:00
# If your plugin creates notifications, and you'd like to consolidate/collapse similar ones,
# you're in the right place.
# This method receives a plan object, which must be an instance of `Notifications::ConsolidateNotifications`.
#
# Instead of using `Notification#create!`, you should use `Notification#consolidate_or_save!`,
# which will automatically pick your plan and apply it, updating an already consolidated notification,
# consolidating multiple ones, or creating a regular one.
#
# The rule object is quite complex. We strongly recommend you write tests to ensure your plugin consolidates notifications correctly.
#
2021-12-10 08:32:15 -05:00
# - Threshold and time window consolidation plan: https://github.com/discourse/discourse/blob/main/app/services/notifications/consolidate_notifications.rb
# - Create a new notification and delete previous versions plan: https://github.com/discourse/discourse/blob/main/app/services/notifications/delete_previous_notifications.rb
REFACTOR: Improve support for consolidating notifications. (#14904)
* REFACTOR: Improve support for consolidating notifications.
Before this commit, we didn't have a single way of consolidating notifications. For notifications like group summaries, we manually removed old ones before creating a new one. On the other hand, we used an after_create callback for likes and group membership requests, which caused unnecessary work, as we need to delete the record we created to replace it with a consolidated one.
We now have all the consolidation rules centralized in a single place: the consolidation planner class. Other parts of the app looking to create a consolidable notification can do so by calling Notification#consolidate_or_save!, instead of the default Notification#create! method.
Finally, we added two more rules: one for re-using existing group summaries and another for deleting duplicated dashboard problems PMs notifications when the user is tracking the moderator's inbox. Setting the threshold to one forces the planner to apply this rule every time.
I plan to add plugin support for adding custom rules in another PR to keep this one relatively small.
* DEV: Introduces a plugin API for consolidating notifications.
This commit removes the `Notification#filter_by_consolidation_data` scope since plugins could have to define their criteria. The Plan class now receives two blocks, one to query for an already consolidated notification, which we'll try to update, and another to query for existing ones to consolidate.
It also receives a consolidation window, which accepts an ActiveSupport::Duration object, and filter notifications created since that value.
2021-11-30 11:36:14 -05:00
# - Base plans: https://github.com/discourse/discourse/blob/main/app/services/notifications/consolidation_planner.rb
def register_notification_consolidation_plan ( plan )
2021-12-10 08:32:15 -05:00
if ! plan . class . ancestors . include? ( Notifications :: ConsolidationPlan )
raise ArgumentError . new ( " Not a consolidation plan " )
2023-01-09 07:10:19 -05:00
end
REFACTOR: Improve support for consolidating notifications. (#14904)
* REFACTOR: Improve support for consolidating notifications.
Before this commit, we didn't have a single way of consolidating notifications. For notifications like group summaries, we manually removed old ones before creating a new one. On the other hand, we used an after_create callback for likes and group membership requests, which caused unnecessary work, as we need to delete the record we created to replace it with a consolidated one.
We now have all the consolidation rules centralized in a single place: the consolidation planner class. Other parts of the app looking to create a consolidable notification can do so by calling Notification#consolidate_or_save!, instead of the default Notification#create! method.
Finally, we added two more rules: one for re-using existing group summaries and another for deleting duplicated dashboard problems PMs notifications when the user is tracking the moderator's inbox. Setting the threshold to one forces the planner to apply this rule every time.
I plan to add plugin support for adding custom rules in another PR to keep this one relatively small.
* DEV: Introduces a plugin API for consolidating notifications.
This commit removes the `Notification#filter_by_consolidation_data` scope since plugins could have to define their criteria. The Plan class now receives two blocks, one to query for an already consolidated notification, which we'll try to update, and another to query for existing ones to consolidate.
It also receives a consolidation window, which accepts an ActiveSupport::Duration object, and filter notifications created since that value.
2021-11-30 11:36:14 -05:00
DiscoursePluginRegistry . register_notification_consolidation_plan ( plan , self )
end
2021-12-15 22:24:11 -05:00
# Allows customizing existing topic-backed static pages, like:
# faq, tos, privacy (see: StaticController) The block passed to this
# method has to return a SiteSetting name that contains a topic id.
#
# add_topic_static_page("faq") do |controller|
# current_user&.locale == "pl" ? "polish_faq_topic_id" : "faq_topic_id"
# end
#
# You can also add new pages in a plugin, but remember to add a route,
# for example:
#
# get "contact" => "static#show", id: "contact"
def add_topic_static_page ( page , options = { } , & blk )
StaticController :: CUSTOM_PAGES [ page ] = blk ? { topic_id : blk } : options
end
2022-06-21 14:49:47 -04:00
# Let plugin define custom unsubscribe keys,
# set custom instance variables on the `EmailController#unsubscribe` action,
# and describe what unsubscribing for that key does.
#
# The method receives a class that inherits from `Email::BaseEmailUnsubscriber`.
# Take a look at it to know how to implement your child class.
#
# In conjunction with this, you'll have to:
#
# - Register a new connector under app/views/connectors/unsubscribe_options.
# We'll include the HTML inside the unsubscribe form, so you can add your fields using the
# instance variables you set in the controller previously. When the form is submitted,
# it sends the updated preferences to `EmailController#perform_unsubscribe`.
#
# - Your code is responsible for creating the custom key by calling `UnsubscribeKey#create_key_for`.
def register_email_unsubscriber ( type , unsubscriber )
core_types = [ UnsubscribeKey :: ALL_TYPE , UnsubscribeKey :: DIGEST_TYPE , UnsubscribeKey :: TOPIC_TYPE ]
raise ArgumentError . new ( " Type already exists " ) if core_types . include? ( type )
if ! unsubscriber . ancestors . include? ( EmailControllerHelper :: BaseEmailUnsubscriber )
raise ArgumentError . new ( " Not an email unsubscriber " )
2023-01-09 07:10:19 -05:00
end
2022-06-21 14:49:47 -04:00
DiscoursePluginRegistry . register_email_unsubscriber ( { type = > unsubscriber } , self )
end
FEATURE: Add plugin API to register About stat group (#17442)
This commit introduces a new plugin API to register
a group of stats that will be included in about.json
and also conditionally in the site about UI at /about.
The usage is like this:
```ruby
register_about_stat_group("chat_messages", show_in_ui: true) do
{
last_day: 1,
"7_days" => 10,
"30_days" => 100,
count: 1000,
previous_30_days: 120
}
end
```
In reality the stats will be generated any way the implementer
chooses within the plugin. The `last_day`, `7_days`, `30_days,` and `count`
keys must be present but apart from that additional stats may be added.
Only those core 4 stat keys will be shown in the UI, but everything will be shown
in about.json.
The stat group name is used to prefix the stats in about.json like so:
```json
"chat_messages_last_day": 2322,
"chat_messages_7_days": 2322,
"chat_messages_30_days": 2322,
"chat_messages_count": 2322,
```
The `show_in_ui` option (default false) is used to determine whether the
group of stats is shown on the site About page in the Site Statistics
table. Some stats may be needed purely for reporting purposes and thus
do not need to be shown in the UI to admins/users. An extension to the Site
serializer, `displayed_about_plugin_stat_groups`, has been added so this
can be inspected on the client-side.
2022-07-14 23:16:00 -04:00
# Allows the plugin to export additional site stats via the About class
# which will be shown on the /about route. The stats returned by the block
# should be in the following format (these four keys are _required_):
#
# {
# last_day: 1,
# 7_days: 10,
# 30_days: 100,
# count: 1000
# }
#
# Only keys above will be shown on the /about page in the UI,
# but all stats will be shown on the /about.json route. For example take
# this usage:
#
2023-11-09 15:44:05 -05:00
# register_stat("chat_messages") do
FEATURE: Add plugin API to register About stat group (#17442)
This commit introduces a new plugin API to register
a group of stats that will be included in about.json
and also conditionally in the site about UI at /about.
The usage is like this:
```ruby
register_about_stat_group("chat_messages", show_in_ui: true) do
{
last_day: 1,
"7_days" => 10,
"30_days" => 100,
count: 1000,
previous_30_days: 120
}
end
```
In reality the stats will be generated any way the implementer
chooses within the plugin. The `last_day`, `7_days`, `30_days,` and `count`
keys must be present but apart from that additional stats may be added.
Only those core 4 stat keys will be shown in the UI, but everything will be shown
in about.json.
The stat group name is used to prefix the stats in about.json like so:
```json
"chat_messages_last_day": 2322,
"chat_messages_7_days": 2322,
"chat_messages_30_days": 2322,
"chat_messages_count": 2322,
```
The `show_in_ui` option (default false) is used to determine whether the
group of stats is shown on the site About page in the Site Statistics
table. Some stats may be needed purely for reporting purposes and thus
do not need to be shown in the UI to admins/users. An extension to the Site
serializer, `displayed_about_plugin_stat_groups`, has been added so this
can be inspected on the client-side.
2022-07-14 23:16:00 -04:00
# { last_day: 1, "7_days" => 10, "30_days" => 100, count: 1000, previous_30_days: 150 }
# end
#
# In the UI we will show a table like this:
#
# | 24h | 7 days | 30 days | all time|
# Chat Messages | 1 | 10 | 100 | 1000 |
#
# But the JSON will be like this:
#
# {
# "chat_messages_last_day": 1,
# "chat_messages_7_days": 10,
# "chat_messages_30_days": 100,
# "chat_messages_count": 1000,
# }
#
# The show_in_ui option (default false) is used to determine whether the
# group of stats is shown on the site About page in the Site Statistics
# table. Some stats may be needed purely for reporting purposes and thus
# do not need to be shown in the UI to admins/users.
2024-08-20 09:16:05 -04:00
#
2024-09-04 12:58:14 -04:00
# TODO(osama): remove show_in_ui when experimental_redesigned_about_page_groups is removed
def register_stat (
name ,
show_in_ui : (
not_using_deprecated_arg = true
false
) ,
expose_via_api : false ,
& block
)
if ! not_using_deprecated_arg
Discourse . deprecate (
" `show_in_ui` argument of the `register_stat` API is deprecated. Please use the `addAboutPageActivity` JS API instead if you want your custom stat to be shown on the about page. " ,
since : " 3.4.0.beta2 " ,
drop_from : " 3.5.0.beta1 " ,
)
end
2023-03-01 17:10:16 -05:00
# We do not want to register and display the same group multiple times.
2023-11-09 15:44:05 -05:00
return if DiscoursePluginRegistry . stats . any? { | stat | stat . name == name }
2023-03-01 17:10:16 -05:00
2023-11-09 15:44:05 -05:00
stat = Stat . new ( name , show_in_ui : show_in_ui , expose_via_api : expose_via_api , & block )
DiscoursePluginRegistry . register_stat ( stat , self )
FEATURE: Add plugin API to register About stat group (#17442)
This commit introduces a new plugin API to register
a group of stats that will be included in about.json
and also conditionally in the site about UI at /about.
The usage is like this:
```ruby
register_about_stat_group("chat_messages", show_in_ui: true) do
{
last_day: 1,
"7_days" => 10,
"30_days" => 100,
count: 1000,
previous_30_days: 120
}
end
```
In reality the stats will be generated any way the implementer
chooses within the plugin. The `last_day`, `7_days`, `30_days,` and `count`
keys must be present but apart from that additional stats may be added.
Only those core 4 stat keys will be shown in the UI, but everything will be shown
in about.json.
The stat group name is used to prefix the stats in about.json like so:
```json
"chat_messages_last_day": 2322,
"chat_messages_7_days": 2322,
"chat_messages_30_days": 2322,
"chat_messages_count": 2322,
```
The `show_in_ui` option (default false) is used to determine whether the
group of stats is shown on the site About page in the Site Statistics
table. Some stats may be needed purely for reporting purposes and thus
do not need to be shown in the UI to admins/users. An extension to the Site
serializer, `displayed_about_plugin_stat_groups`, has been added so this
can be inspected on the client-side.
2022-07-14 23:16:00 -04:00
end
FEATURE: Generic hashtag autocomplete lookup and markdown cooking (#18937)
This commit fleshes out and adds functionality for the new `#hashtag` search and
lookup system, still hidden behind the `enable_experimental_hashtag_autocomplete`
feature flag.
**Serverside**
We have two plugin API registration methods that are used to define data sources
(`register_hashtag_data_source`) and hashtag result type priorities depending on
the context (`register_hashtag_type_in_context`). Reading the comments in plugin.rb
should make it clear what these are doing. Reading the `HashtagAutocompleteService`
in full will likely help a lot as well.
Each data source is responsible for providing its own **lookup** and **search**
method that returns hashtag results based on the arguments provided. For example,
the category hashtag data source has to take into account parent categories and
how they relate, and each data source has to define their own icon to use for the
hashtag, and so on.
The `Site` serializer has two new attributes that source data from `HashtagAutocompleteService`.
There is `hashtag_icons` that is just a simple array of all the different icons that
can be used for allowlisting in our markdown pipeline, and there is `hashtag_context_configurations`
that is used to store the type priority orders for each registered context.
When sending emails, we cannot render the SVG icons for hashtags, so
we need to change the HTML hashtags to the normal `#hashtag` text.
**Markdown**
The `hashtag-autocomplete.js` file is where I have added the new `hashtag-autocomplete`
markdown rule, and like all of our rules this is used to cook the raw text on both the clientside
and on the serverside using MiniRacer. Only on the server side do we actually reach out to
the database with the `hashtagLookup` function, on the clientside we just render a plainer
version of the hashtag HTML. Only in the composer preview do we do further lookups based
on this.
This rule is the first one (that I can find) that uses the `currentUser` based on a passed
in `user_id` for guardian checks in markdown rendering code. This is the `last_editor_id`
for both the post and chat message. In some cases we need to cook without a user present,
so the `Discourse.system_user` is used in this case.
**Chat Channels**
This also contains the changes required for chat so that chat channels can be used
as a data source for hashtag searches and lookups. This data source will only be
used when `enable_experimental_hashtag_autocomplete` is `true`, so we don't have
to worry about channel results suddenly turning up.
------
**Known Rough Edges**
- Onebox excerpts will not render the icon svg/use tags, I plan to address that in a follow up PR
- Selecting a hashtag + pressing the Quote button will result in weird behaviour, I plan to address that in a follow up PR
- Mixed hashtag contexts for hashtags without a type suffix will not work correctly, e.g. #ux which is both a category and a channel slug will resolve to a category when used inside a post or within a [chat] transcript in that post. Users can get around this manually by adding the correct suffix, for example ::channel. We may get to this at some point in future
- Icons will not show for the hashtags in emails since SVG support is so terrible in email (this is not likely to be resolved, but still noting for posterity)
- Additional refinements and review fixes wil
2022-11-20 17:37:06 -05:00
##
# Used to register data sources for HashtagAutocompleteService to look
# up results based on a #hashtag string.
2022-10-19 00:03:57 -04:00
#
FEATURE: Generic hashtag autocomplete lookup and markdown cooking (#18937)
This commit fleshes out and adds functionality for the new `#hashtag` search and
lookup system, still hidden behind the `enable_experimental_hashtag_autocomplete`
feature flag.
**Serverside**
We have two plugin API registration methods that are used to define data sources
(`register_hashtag_data_source`) and hashtag result type priorities depending on
the context (`register_hashtag_type_in_context`). Reading the comments in plugin.rb
should make it clear what these are doing. Reading the `HashtagAutocompleteService`
in full will likely help a lot as well.
Each data source is responsible for providing its own **lookup** and **search**
method that returns hashtag results based on the arguments provided. For example,
the category hashtag data source has to take into account parent categories and
how they relate, and each data source has to define their own icon to use for the
hashtag, and so on.
The `Site` serializer has two new attributes that source data from `HashtagAutocompleteService`.
There is `hashtag_icons` that is just a simple array of all the different icons that
can be used for allowlisting in our markdown pipeline, and there is `hashtag_context_configurations`
that is used to store the type priority orders for each registered context.
When sending emails, we cannot render the SVG icons for hashtags, so
we need to change the HTML hashtags to the normal `#hashtag` text.
**Markdown**
The `hashtag-autocomplete.js` file is where I have added the new `hashtag-autocomplete`
markdown rule, and like all of our rules this is used to cook the raw text on both the clientside
and on the serverside using MiniRacer. Only on the server side do we actually reach out to
the database with the `hashtagLookup` function, on the clientside we just render a plainer
version of the hashtag HTML. Only in the composer preview do we do further lookups based
on this.
This rule is the first one (that I can find) that uses the `currentUser` based on a passed
in `user_id` for guardian checks in markdown rendering code. This is the `last_editor_id`
for both the post and chat message. In some cases we need to cook without a user present,
so the `Discourse.system_user` is used in this case.
**Chat Channels**
This also contains the changes required for chat so that chat channels can be used
as a data source for hashtag searches and lookups. This data source will only be
used when `enable_experimental_hashtag_autocomplete` is `true`, so we don't have
to worry about channel results suddenly turning up.
------
**Known Rough Edges**
- Onebox excerpts will not render the icon svg/use tags, I plan to address that in a follow up PR
- Selecting a hashtag + pressing the Quote button will result in weird behaviour, I plan to address that in a follow up PR
- Mixed hashtag contexts for hashtags without a type suffix will not work correctly, e.g. #ux which is both a category and a channel slug will resolve to a category when used inside a post or within a [chat] transcript in that post. Users can get around this manually by adding the correct suffix, for example ::channel. We may get to this at some point in future
- Icons will not show for the hashtags in emails since SVG support is so terrible in email (this is not likely to be resolved, but still noting for posterity)
- Additional refinements and review fixes wil
2022-11-20 17:37:06 -05:00
# @param {Class} klass - Must be a class that implements methods with the following
# signatures:
#
2022-12-18 22:46:17 -05:00
# Roughly corresponding to a model, this is used as a unique
# key for the datasource and is also used when allowing different
# contexts to search for and lookup these types. The `category`
# and `tag` types are registered by default.
# def self.type
# end
#
# The FontAwesome icon to use for the data source in the search results
# and cooked markdown.
# def self.icon
# end
#
FEATURE: Generic hashtag autocomplete lookup and markdown cooking (#18937)
This commit fleshes out and adds functionality for the new `#hashtag` search and
lookup system, still hidden behind the `enable_experimental_hashtag_autocomplete`
feature flag.
**Serverside**
We have two plugin API registration methods that are used to define data sources
(`register_hashtag_data_source`) and hashtag result type priorities depending on
the context (`register_hashtag_type_in_context`). Reading the comments in plugin.rb
should make it clear what these are doing. Reading the `HashtagAutocompleteService`
in full will likely help a lot as well.
Each data source is responsible for providing its own **lookup** and **search**
method that returns hashtag results based on the arguments provided. For example,
the category hashtag data source has to take into account parent categories and
how they relate, and each data source has to define their own icon to use for the
hashtag, and so on.
The `Site` serializer has two new attributes that source data from `HashtagAutocompleteService`.
There is `hashtag_icons` that is just a simple array of all the different icons that
can be used for allowlisting in our markdown pipeline, and there is `hashtag_context_configurations`
that is used to store the type priority orders for each registered context.
When sending emails, we cannot render the SVG icons for hashtags, so
we need to change the HTML hashtags to the normal `#hashtag` text.
**Markdown**
The `hashtag-autocomplete.js` file is where I have added the new `hashtag-autocomplete`
markdown rule, and like all of our rules this is used to cook the raw text on both the clientside
and on the serverside using MiniRacer. Only on the server side do we actually reach out to
the database with the `hashtagLookup` function, on the clientside we just render a plainer
version of the hashtag HTML. Only in the composer preview do we do further lookups based
on this.
This rule is the first one (that I can find) that uses the `currentUser` based on a passed
in `user_id` for guardian checks in markdown rendering code. This is the `last_editor_id`
for both the post and chat message. In some cases we need to cook without a user present,
so the `Discourse.system_user` is used in this case.
**Chat Channels**
This also contains the changes required for chat so that chat channels can be used
as a data source for hashtag searches and lookups. This data source will only be
used when `enable_experimental_hashtag_autocomplete` is `true`, so we don't have
to worry about channel results suddenly turning up.
------
**Known Rough Edges**
- Onebox excerpts will not render the icon svg/use tags, I plan to address that in a follow up PR
- Selecting a hashtag + pressing the Quote button will result in weird behaviour, I plan to address that in a follow up PR
- Mixed hashtag contexts for hashtags without a type suffix will not work correctly, e.g. #ux which is both a category and a channel slug will resolve to a category when used inside a post or within a [chat] transcript in that post. Users can get around this manually by adding the correct suffix, for example ::channel. We may get to this at some point in future
- Icons will not show for the hashtags in emails since SVG support is so terrible in email (this is not likely to be resolved, but still noting for posterity)
- Additional refinements and review fixes wil
2022-11-20 17:37:06 -05:00
# @param {Guardian} guardian - Current user's guardian, used for permission-based filtering
# @param {Array} slugs - An array of strings that represent slugs to search this type for,
# e.g. category slugs.
# @returns {Hash} A hash with the slug as the key and the URL of the record as the value.
# def self.lookup(guardian, slugs)
# end
#
# @param {Guardian} guardian - Current user's guardian, used for permission-based filtering
# @param {String} term - The search term used to filter results
# @param {Integer} limit - The number of search results that should be returned by the query
# @returns {Array} An Array of HashtagAutocompleteService::HashtagItem
# def self.search(guardian, term, limit)
# end
2022-12-18 22:46:17 -05:00
#
# @param {Array} search_results - An array of HashtagAutocompleteService::HashtagItem to sort
# @param {String} term - The search term which was used, which may help with sorting.
# @returns {Array} An Array of HashtagAutocompleteService::HashtagItem
# def self.search_sort(search_results, term)
# end
#
# @param {Guardian} guardian - Current user's guardian, used for permission-based filtering
# @param {Integer} limit - The number of search results that should be returned by the query
# @returns {Array} An Array of HashtagAutocompleteService::HashtagItem
# def self.search_without_term(guardian, limit)
# end
def register_hashtag_data_source ( klass )
DiscoursePluginRegistry . register_hashtag_autocomplete_data_source ( klass , self )
FEATURE: Generic hashtag autocomplete lookup and markdown cooking (#18937)
This commit fleshes out and adds functionality for the new `#hashtag` search and
lookup system, still hidden behind the `enable_experimental_hashtag_autocomplete`
feature flag.
**Serverside**
We have two plugin API registration methods that are used to define data sources
(`register_hashtag_data_source`) and hashtag result type priorities depending on
the context (`register_hashtag_type_in_context`). Reading the comments in plugin.rb
should make it clear what these are doing. Reading the `HashtagAutocompleteService`
in full will likely help a lot as well.
Each data source is responsible for providing its own **lookup** and **search**
method that returns hashtag results based on the arguments provided. For example,
the category hashtag data source has to take into account parent categories and
how they relate, and each data source has to define their own icon to use for the
hashtag, and so on.
The `Site` serializer has two new attributes that source data from `HashtagAutocompleteService`.
There is `hashtag_icons` that is just a simple array of all the different icons that
can be used for allowlisting in our markdown pipeline, and there is `hashtag_context_configurations`
that is used to store the type priority orders for each registered context.
When sending emails, we cannot render the SVG icons for hashtags, so
we need to change the HTML hashtags to the normal `#hashtag` text.
**Markdown**
The `hashtag-autocomplete.js` file is where I have added the new `hashtag-autocomplete`
markdown rule, and like all of our rules this is used to cook the raw text on both the clientside
and on the serverside using MiniRacer. Only on the server side do we actually reach out to
the database with the `hashtagLookup` function, on the clientside we just render a plainer
version of the hashtag HTML. Only in the composer preview do we do further lookups based
on this.
This rule is the first one (that I can find) that uses the `currentUser` based on a passed
in `user_id` for guardian checks in markdown rendering code. This is the `last_editor_id`
for both the post and chat message. In some cases we need to cook without a user present,
so the `Discourse.system_user` is used in this case.
**Chat Channels**
This also contains the changes required for chat so that chat channels can be used
as a data source for hashtag searches and lookups. This data source will only be
used when `enable_experimental_hashtag_autocomplete` is `true`, so we don't have
to worry about channel results suddenly turning up.
------
**Known Rough Edges**
- Onebox excerpts will not render the icon svg/use tags, I plan to address that in a follow up PR
- Selecting a hashtag + pressing the Quote button will result in weird behaviour, I plan to address that in a follow up PR
- Mixed hashtag contexts for hashtags without a type suffix will not work correctly, e.g. #ux which is both a category and a channel slug will resolve to a category when used inside a post or within a [chat] transcript in that post. Users can get around this manually by adding the correct suffix, for example ::channel. We may get to this at some point in future
- Icons will not show for the hashtags in emails since SVG support is so terrible in email (this is not likely to be resolved, but still noting for posterity)
- Additional refinements and review fixes wil
2022-11-20 17:37:06 -05:00
end
##
# Used to set up the priority ordering of hashtag autocomplete results by
# type using HashtagAutocompleteService.
#
# @param {String} type - Roughly corresponding to a model, can only be registered once
# per context. The `category` and `tag` types are registered
# for the `topic-composer` context by default in that priority order.
# @param {String} context - The context in which the hashtag lookup or search is happening
# in. For example, the Discourse composer context is `topic-composer`.
# Different contexts may want to have different priority orderings
# for certain types of hashtag result.
# @param {Integer} priority - A number value for ordering type results when hashtag searches
# or lookups occur. Priority is ordered by DESCENDING order.
2022-12-18 22:46:17 -05:00
def register_hashtag_type_priority_for_context ( type , context , priority )
DiscoursePluginRegistry . register_hashtag_autocomplete_contextual_type_priority (
{ type : type , context : context , priority : priority } ,
self ,
)
2022-10-19 00:03:57 -04:00
end
2022-11-28 11:32:57 -05:00
##
# Register a block that will be called when the UserDestroyer runs
# with the :delete_posts opt set to true. It's important to note that the block will
# execute before any other :delete_posts actions, it allows us to manipulate flags
# before agreeing with them. For example, discourse-akismet makes use of this
#
# @param {Block} callback to be called with the user, guardian, and the destroyer opts as arguments
def register_user_destroyer_on_content_deletion_callback ( callback )
DiscoursePluginRegistry . register_user_destroyer_on_content_deletion_callback ( callback , self )
end
2023-03-07 19:39:12 -05:00
##
# Register a class that implements [BaseBookmarkable], which represents another
# [ActiveRecord::Model] that may be bookmarked via the [Bookmark] model's
# polymorphic association. The class handles create and destroy hooks, querying,
# and reminders among other things.
def register_bookmarkable ( klass )
return if Bookmark . registered_bookmarkable_from_type ( klass . model . name ) . present?
DiscoursePluginRegistry . register_bookmarkable ( RegisteredBookmarkable . new ( klass ) , self )
end
2023-06-13 13:21:46 -04:00
##
# Register an object that inherits from [Summarization::Base], which provides a way
# to summarize content. Staff can select which strategy to use
# through the `summarization_strategy` setting.
def register_summarization_strategy ( strategy )
2024-07-02 11:51:47 -04:00
Discourse . deprecate (
2024-07-09 05:46:10 -04:00
" register_summarization_strategy is deprecated. Summarization code is now moved to Discourse AI " ,
2024-07-02 11:51:47 -04:00
)
2023-06-13 13:21:46 -04:00
if ! strategy . class . ancestors . include? ( Summarization :: Base )
raise ArgumentError . new ( " Not a valid summarization strategy " )
end
DiscoursePluginRegistry . register_summarization_strategy ( strategy , self )
end
2023-10-10 13:21:57 -04:00
##
# Register a block that will be called when PostActionCreator is going to notify a
# user of a post action. If any of these handlers returns false the default PostCreator
# call will be skipped.
def register_post_action_notify_user_handler ( handler )
DiscoursePluginRegistry . register_post_action_notify_user_handler ( handler , self )
end
2023-11-08 14:13:25 -05:00
# We strip posts before detecting mentions, oneboxes, attachments etc.
# We strip those elements that shouldn't be detected. For example,
# a mention inside a quote should be ignored, so we strip it off.
# Using this API plugins can register their own post strippers.
def register_post_stripper ( & block )
DiscoursePluginRegistry . register_post_stripper ( { block : block } , self )
end
2024-01-25 11:36:43 -05:00
def register_search_group_query_callback ( callback )
DiscoursePluginRegistry . register_search_groups_set_query_callback ( callback , self )
end
2014-04-10 02:30:22 -04:00
protected
2019-07-15 10:52:54 -04:00
def self . js_path
File . expand_path " #{ Rails . root } /app/assets/javascripts/plugins "
end
2024-02-01 06:48:31 -05:00
def legacy_asset_paths
[
" #{ Plugin :: Instance . js_path } / #{ directory_name } .js.erb " ,
" #{ Plugin :: Instance . js_path } / #{ directory_name } _extra.js.erb " ,
]
2022-08-22 04:56:39 -04:00
end
def extra_js_file_path
2024-02-01 06:48:31 -05:00
@extra_js_file_path || = " #{ Plugin :: Instance . js_path } / #{ directory_name } _extra.js "
end
def write_extra_js!
# No longer used, but we want to make sure the files are no longer present
# so they don't accidently get compiled by Sprockets.
legacy_asset_paths . each do | path |
File . delete ( path )
rescue Errno :: ENOENT
end
contents = javascript_includes . map { | js | File . read ( js ) }
if contents . present?
ensure_directory ( extra_js_file_path )
Discourse :: Utils . atomic_write_file ( extra_js_file_path , contents . join ( " \n ; \n " ) )
else
begin
File . delete ( extra_js_file_path )
rescue Errno :: ENOENT
end
end
2019-07-15 10:52:54 -04:00
end
2014-04-10 02:30:22 -04:00
def register_assets!
2019-08-20 12:39:52 -04:00
assets . each do | asset , opts , plugin_directory_name |
DiscoursePluginRegistry . register_asset ( asset , opts , plugin_directory_name )
2014-04-10 02:30:22 -04:00
end
end
2017-11-22 20:02:01 -05:00
def register_service_workers!
service_workers . each do | asset , opts |
DiscoursePluginRegistry . register_service_worker ( asset , opts )
end
end
2018-01-25 06:09:18 -05:00
def register_locales!
root_path = File . dirname ( @path )
locales . each do | locale , opts |
opts = opts . dup
2020-11-11 10:44:01 -05:00
opts [ :client_locale_file ] = Dir [ " #{ root_path } /config/locales/client*. #{ locale } .yml " ] . first ||
" "
opts [ :server_locale_file ] = Dir [ " #{ root_path } /config/locales/server*. #{ locale } .yml " ] . first ||
" "
2018-01-25 06:09:18 -05:00
opts [ :js_locale_file ] = File . join ( root_path , " assets/locales/ #{ locale } .js.erb " )
locale_chain = opts [ :fallbackLocale ] ? [ locale , opts [ :fallbackLocale ] ] : [ locale ]
lib_locale_path = File . join ( root_path , " lib/javascripts/locale " )
path = File . join ( lib_locale_path , " moment_js " )
opts [ :moment_js ] = find_locale_file ( locale_chain , path )
opts [ :moment_js ] = JsLocaleHelper . find_moment_locale ( locale_chain ) unless opts [ :moment_js ]
2019-02-25 14:40:02 -05:00
path = File . join ( lib_locale_path , " moment_js_timezones " )
opts [ :moment_js_timezones ] = find_locale_file ( locale_chain , path )
opts [ :moment_js_timezones ] = JsLocaleHelper . find_moment_locale (
locale_chain ,
timezone_names : true ,
) unless opts [ :moment_js_timezones ]
2018-01-25 06:09:18 -05:00
if valid_locale? ( opts )
DiscoursePluginRegistry . register_locale ( locale , opts )
Rails . configuration . assets . precompile << " locales/ #{ locale } .js "
2018-04-20 15:29:03 -04:00
else
2018-06-22 10:20:20 -04:00
msg = " Invalid locale! #{ opts . inspect } "
# The logger isn't always present during boot / parsing locales from plugins
if Rails . logger . present?
Rails . logger . error ( msg )
else
puts msg
end
2018-01-25 06:09:18 -05:00
end
end
end
2019-08-29 10:56:46 -04:00
def allow_new_queued_post_payload_attribute ( attribute_name )
reloadable_patch { NewPostManager . add_plugin_payload_attribute ( attribute_name ) }
end
2022-12-12 09:08:13 -05:00
def register_topic_preloader_associations ( fields )
DiscoursePluginRegistry . register_topic_preloader_association ( fields , self )
end
2015-11-06 09:02:40 -05:00
private
2024-01-07 18:57:25 -05:00
def setting_category
return if @enabled_site_setting . blank?
SiteSetting . categories [ enabled_site_setting ]
end
def setting_category_name
return if setting_category . blank? || setting_category == " plugins "
I18n . t ( " admin_js.admin.site_settings.categories. #{ setting_category } " )
end
2021-06-22 14:00:04 -04:00
def validate_directory_column_name ( column_name )
2023-01-20 13:52:49 -05:00
match = / \ A[_a-z]+ \ z / . match ( column_name )
2021-06-22 14:00:04 -04:00
unless match
raise " Invalid directory column name ' #{ column_name } '. Can only contain a-z and underscores "
2023-01-09 07:10:19 -05:00
end
2021-06-22 14:00:04 -04:00
end
2015-11-06 09:02:40 -05:00
def write_asset ( path , contents )
2022-01-05 12:45:08 -05:00
unless File . exist? ( path )
2015-11-06 09:02:40 -05:00
ensure_directory ( path )
File . open ( path , " w " ) { | f | f . write ( contents ) }
end
end
2017-08-09 16:22:18 -04:00
def reloadable_patch ( plugin = self )
2017-08-31 00:06:56 -04:00
if Rails . env . development? && defined? ( ActiveSupport :: Reloader )
ActiveSupport :: Reloader . to_prepare do
2017-08-09 16:22:18 -04:00
# reload the patch
2017-08-09 12:28:32 -04:00
yield plugin
end
end
# apply the patch
yield plugin
end
2018-01-25 06:09:18 -05:00
def valid_locale? ( custom_locale )
File . exist? ( custom_locale [ :client_locale_file ] ) &&
File . exist? ( custom_locale [ :server_locale_file ] ) &&
2024-06-17 12:21:04 -04:00
File . exist? ( custom_locale [ :js_locale_file ] ) && custom_locale [ :moment_js ]
2018-01-25 06:09:18 -05:00
end
def find_locale_file ( locale_chain , path )
locale_chain . each do | locale |
filename = File . join ( path , " #{ locale } .js " )
return locale , filename if File . exist? ( filename )
end
nil
end
2020-09-10 12:18:45 -04:00
def register_permitted_bulk_action_parameter ( name )
DiscoursePluginRegistry . register_permitted_bulk_action_parameter ( name , self )
end
2013-08-23 02:21:52 -04:00
end