Skip to content

A platform for community discussion. Free, open, simple.

DEV: Apply syntax_tree formatting to `lib/*`

David Taylor64171730827c
diff --git a/.streerc b/.streerc
index b43ee5bb6ee..fd138211ec6 100644
--- a/.streerc
+++ b/.streerc
@@ -1,4 +1,3 @@
--print-width=100
--plugins=plugin/trailing_comma,disable_ternary
--ignore-files=app/*
---ignore-files=lib/*
diff --git a/lib/action_dispatch/session/discourse_cookie_store.rb b/lib/action_dispatch/session/discourse_cookie_store.rb
index 91a32f4545a..58da5c8f5d3 100644
--- a/lib/action_dispatch/session/discourse_cookie_store.rb
+++ b/lib/action_dispatch/session/discourse_cookie_store.rb
@@ -9,9 +9,7 @@ class ActionDispatch::Session::DiscourseCookieStore < ActionDispatch::Session::C
def set_cookie(request, session_id, cookie)
if Hash === cookie
- if SiteSetting.force_https
- cookie[:secure] = true
- end
+ cookie[:secure] = true if SiteSetting.force_https
unless SiteSetting.same_site_cookies == "Disabled"
cookie[:same_site] = SiteSetting.same_site_cookies
end
diff --git a/lib/admin_confirmation.rb b/lib/admin_confirmation.rb
index fa73f66de70..06b7bc775cf 100644
--- a/lib/admin_confirmation.rb
+++ b/lib/admin_confirmation.rb
@@ -17,10 +17,7 @@ class AdminConfirmation
@token = SecureRandom.hex
Discourse.redis.setex("admin-confirmation:#{@target_user.id}", 3.hours.to_i, @token)
- payload = {
- target_user_id: @target_user.id,
- performed_by: @performed_by.id
- }
+ payload = { target_user_id: @target_user.id, performed_by: @performed_by.id }
Discourse.redis.setex("admin-confirmation-token:#{@token}", 3.hours.to_i, payload.to_json)
Jobs.enqueue(
@@ -28,7 +25,7 @@ class AdminConfirmation
to_address: @performed_by.email,
target_email: @target_user.email,
target_username: @target_user.username,
- token: @token
+ token: @token,
)
end
@@ -51,8 +48,8 @@ class AdminConfirmation
return nil unless json
parsed = JSON.parse(json)
- target_user = User.find(parsed['target_user_id'].to_i)
- performed_by = User.find(parsed['performed_by'].to_i)
+ target_user = User.find(parsed["target_user_id"].to_i)
+ performed_by = User.find(parsed["performed_by"].to_i)
ac = AdminConfirmation.new(target_user, performed_by)
ac.token = token
diff --git a/lib/admin_constraint.rb b/lib/admin_constraint.rb
index 7146eedfeeb..521cb0c2be9 100644
--- a/lib/admin_constraint.rb
+++ b/lib/admin_constraint.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class AdminConstraint
-
def initialize(options = {})
@require_master = options[:require_master]
end
@@ -19,5 +18,4 @@ class AdminConstraint
def custom_admin_check(request)
true
end
-
end
diff --git a/lib/admin_user_index_query.rb b/lib/admin_user_index_query.rb
index 9ecbb8f19ad..49564110bfc 100644
--- a/lib/admin_user_index_query.rb
+++ b/lib/admin_user_index_query.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class AdminUserIndexQuery
-
def initialize(params = {}, klass = User, trust_levels = TrustLevel.levels)
@params = params
@query = initialize_query_with_order(klass)
@@ -11,24 +10,22 @@ class AdminUserIndexQuery
attr_reader :params, :trust_levels
SORTABLE_MAPPING = {
- 'created' => 'created_at',
- 'last_emailed' => "COALESCE(last_emailed_at, to_date('1970-01-01', 'YYYY-MM-DD'))",
- 'seen' => "COALESCE(last_seen_at, to_date('1970-01-01', 'YYYY-MM-DD'))",
- 'username' => 'username',
- 'email' => 'email',
- 'trust_level' => 'trust_level',
- 'days_visited' => 'user_stats.days_visited',
- 'posts_read' => 'user_stats.posts_read_count',
- 'topics_viewed' => 'user_stats.topics_entered',
- 'posts' => 'user_stats.post_count',
- 'read_time' => 'user_stats.time_read'
+ "created" => "created_at",
+ "last_emailed" => "COALESCE(last_emailed_at, to_date('1970-01-01', 'YYYY-MM-DD'))",
+ "seen" => "COALESCE(last_seen_at, to_date('1970-01-01', 'YYYY-MM-DD'))",
+ "username" => "username",
+ "email" => "email",
+ "trust_level" => "trust_level",
+ "days_visited" => "user_stats.days_visited",
+ "posts_read" => "user_stats.posts_read_count",
+ "topics_viewed" => "user_stats.topics_entered",
+ "posts" => "user_stats.post_count",
+ "read_time" => "user_stats.time_read",
}
def find_users(limit = 100)
page = params[:page].to_i - 1
- if page < 0
- page = 0
- end
+ page = 0 if page < 0
find_users_query.limit(limit).offset(page * limit)
end
@@ -37,7 +34,13 @@ class AdminUserIndexQuery
end
def custom_direction
- Discourse.deprecate(":ascending is deprecated please use :asc instead", output_in_test: true, drop_from: '2.9.0') if params[:ascending]
+ if params[:ascending]
+ Discourse.deprecate(
+ ":ascending is deprecated please use :asc instead",
+ output_in_test: true,
+ drop_from: "2.9.0",
+ )
+ end
asc = params[:asc] || params[:ascending]
asc.present? && asc ? "ASC" : "DESC"
end
@@ -47,7 +50,7 @@ class AdminUserIndexQuery
custom_order = params[:order]
if custom_order.present? &&
- without_dir = SORTABLE_MAPPING[custom_order.downcase.sub(/ (asc|desc)$/, '')]
+ without_dir = SORTABLE_MAPPING[custom_order.downcase.sub(/ (asc|desc)$/, "")]
order << "#{without_dir} #{custom_direction}"
end
@@ -61,13 +64,9 @@ class AdminUserIndexQuery
order << "users.username"
end
- query = klass
- .includes(:totps)
- .order(order.reject(&:blank?).join(","))
+ query = klass.includes(:totps).order(order.reject(&:blank?).join(","))
- unless params[:stats].present? && params[:stats] == false
- query = query.includes(:user_stat)
- end
+ query = query.includes(:user_stat) unless params[:stats].present? && params[:stats] == false
query = query.joins(:primary_email) if params[:show_emails] == "true"
@@ -77,32 +76,44 @@ class AdminUserIndexQuery
def filter_by_trust
levels = trust_levels.map { |key, _| key.to_s }
if levels.include?(params[:query])
- @query.where('trust_level = ?', trust_levels[params[:query].to_sym])
+ @query.where("trust_level = ?", trust_levels[params[:query].to_sym])
end
end
def filter_by_query_classification
case params[:query]
- when 'staff' then @query.where("admin or moderator")
- when 'admins' then @query.where(admin: true)
- when 'moderators' then @query.where(moderator: true)
- when 'silenced' then @query.silenced
- when 'suspended' then @query.suspended
- when 'pending' then @query.not_suspended.where(approved: false, active: true)
- when 'staged' then @query.where(staged: true)
+ when "staff"
+ @query.where("admin or moderator")
+ when "admins"
+ @query.where(admin: true)
+ when "moderators"
+ @query.where(moderator: true)
+ when "silenced"
+ @query.silenced
+ when "suspended"
+ @query.suspended
+ when "pending"
+ @query.not_suspended.where(approved: false, active: true)
+ when "staged"
+ @query.where(staged: true)
end
end
def filter_by_search
if params[:email].present?
- return @query.joins(:primary_email).where('user_emails.email = ?', params[:email].downcase)
+ return @query.joins(:primary_email).where("user_emails.email = ?", params[:email].downcase)
end
filter = params[:filter]
if filter.present?
filter = filter.strip
- if ip = IPAddr.new(filter) rescue nil
- @query.where('ip_address <<= :ip OR registration_ip_address <<= :ip', ip: ip.to_cidr_s)
+ if ip =
+ begin
+ IPAddr.new(filter)
+ rescue StandardError
+ nil
+ end
+ @query.where("ip_address <<= :ip OR registration_ip_address <<= :ip", ip: ip.to_cidr_s)
else
@query.filter_by_username_or_email(filter)
end
@@ -111,14 +122,12 @@ class AdminUserIndexQuery
def filter_by_ip
if params[:ip].present?
- @query.where('ip_address = :ip OR registration_ip_address = :ip', ip: params[:ip].strip)
+ @query.where("ip_address = :ip OR registration_ip_address = :ip", ip: params[:ip].strip)
end
end
def filter_exclude
- if params[:exclude].present?
- @query.where('users.id != ?', params[:exclude])
- end
+ @query.where("users.id != ?", params[:exclude]) if params[:exclude].present?
end
# this might not be needed in rails 4 ?
@@ -134,5 +143,4 @@ class AdminUserIndexQuery
append filter_by_search
@query
end
-
end
diff --git a/lib/age_words.rb b/lib/age_words.rb
index 814cc219e56..c9bfbfec281 100644
--- a/lib/age_words.rb
+++ b/lib/age_words.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module AgeWords
-
def self.age_words(secs)
if secs.blank?
"&mdash;"
@@ -10,5 +9,4 @@ module AgeWords
FreedomPatches::Rails4.distance_of_time_in_words(now, now + secs)
end
end
-
end
diff --git a/lib/archetype.rb b/lib/archetype.rb
index e3fc8e53540..a9380d59d98 100644
--- a/lib/archetype.rb
+++ b/lib/archetype.rb
@@ -11,22 +11,19 @@ class Archetype
end
def attributes
- {
- id: @id,
- options: @options
- }
+ { id: @id, options: @options }
end
def self.default
- 'regular'
+ "regular"
end
def self.private_message
- 'private_message'
+ "private_message"
end
def self.banner
- 'banner'
+ "banner"
end
def self.list
@@ -40,8 +37,7 @@ class Archetype
end
# default archetypes
- register 'regular'
- register 'private_message'
- register 'banner'
-
+ register "regular"
+ register "private_message"
+ register "banner"
end
diff --git a/lib/auth.rb b/lib/auth.rb
index f501d901574..5380c826d0f 100644
--- a/lib/auth.rb
+++ b/lib/auth.rb
@@ -1,13 +1,14 @@
# frozen_string_literal: true
-module Auth; end
+module Auth
+end
-require 'auth/auth_provider'
-require 'auth/result'
-require 'auth/authenticator'
-require 'auth/managed_authenticator'
-require 'auth/facebook_authenticator'
-require 'auth/github_authenticator'
-require 'auth/twitter_authenticator'
-require 'auth/google_oauth2_authenticator'
-require 'auth/discord_authenticator'
+require "auth/auth_provider"
+require "auth/result"
+require "auth/authenticator"
+require "auth/managed_authenticator"
+require "auth/facebook_authenticator"
+require "auth/github_authenticator"
+require "auth/twitter_authenticator"
+require "auth/google_oauth2_authenticator"
+require "auth/discord_authenticator"
diff --git a/lib/auth/auth_provider.rb b/lib/auth/auth_provider.rb
index 09f0f5f39a4..20e0e6cfbcd 100644
--- a/lib/auth/auth_provider.rb
+++ b/lib/auth/auth_provider.rb
@@ -8,32 +8,60 @@ class Auth::AuthProvider
end
def self.auth_attributes
- [:authenticator, :pretty_name, :title, :message, :frame_width, :frame_height,
- :pretty_name_setting, :title_setting, :enabled_setting, :full_screen_login, :full_screen_login_setting,
- :custom_url, :background_color, :icon]
+ %i[
+ authenticator
+ pretty_name
+ title
+ message
+ frame_width
+ frame_height
+ pretty_name_setting
+ title_setting
+ enabled_setting
+ full_screen_login
+ full_screen_login_setting
+ custom_url
+ background_color
+ icon
+ ]
end
attr_accessor(*auth_attributes)
def enabled_setting=(val)
- Discourse.deprecate("(#{authenticator.name}) enabled_setting is deprecated. Please define authenticator.enabled? instead", drop_from: '2.9.0')
+ Discourse.deprecate(
+ "(#{authenticator.name}) enabled_setting is deprecated. Please define authenticator.enabled? instead",
+ drop_from: "2.9.0",
+ )
@enabled_setting = val
end
def background_color=(val)
- Discourse.deprecate("(#{authenticator.name}) background_color is no longer functional. Please use CSS instead", drop_from: '2.9.0')
+ Discourse.deprecate(
+ "(#{authenticator.name}) background_color is no longer functional. Please use CSS instead",
+ drop_from: "2.9.0",
+ )
end
def full_screen_login=(val)
- Discourse.deprecate("(#{authenticator.name}) full_screen_login is now forced. The full_screen_login parameter can be removed from the auth_provider.", drop_from: '2.9.0')
+ Discourse.deprecate(
+ "(#{authenticator.name}) full_screen_login is now forced. The full_screen_login parameter can be removed from the auth_provider.",
+ drop_from: "2.9.0",
+ )
end
def full_screen_login_setting=(val)
- Discourse.deprecate("(#{authenticator.name}) full_screen_login is now forced. The full_screen_login_setting parameter can be removed from the auth_provider.", drop_from: '2.9.0')
+ Discourse.deprecate(
+ "(#{authenticator.name}) full_screen_login is now forced. The full_screen_login_setting parameter can be removed from the auth_provider.",
+ drop_from: "2.9.0",
+ )
end
def message=(val)
- Discourse.deprecate("(#{authenticator.name}) message is no longer used because all logins are full screen. It should be removed from the auth_provider", drop_from: '2.9.0')
+ Discourse.deprecate(
+ "(#{authenticator.name}) message is no longer used because all logins are full screen. It should be removed from the auth_provider",
+ drop_from: "2.9.0",
+ )
end
def name
@@ -47,5 +75,4 @@ class Auth::AuthProvider
def can_revoke
authenticator.can_revoke?
end
-
end
diff --git a/lib/auth/current_user_provider.rb b/lib/auth/current_user_provider.rb
index 31880b6dc63..f12e992de3d 100644
--- a/lib/auth/current_user_provider.rb
+++ b/lib/auth/current_user_provider.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-module Auth; end
+module Auth
+end
class Auth::CurrentUserProvider
-
# do all current user initialization here
def initialize(env)
raise NotImplementedError
diff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rb
index 3318b062da3..91bacb78a77 100644
--- a/lib/auth/default_current_user_provider.rb
+++ b/lib/auth/default_current_user_provider.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-require_relative '../route_matcher'
+require_relative "../route_matcher"
# You may have seen references to v0 and v1 of our auth cookie in the codebase
# and you're not sure how they differ, so here is an explanation:
@@ -23,7 +23,6 @@ require_relative '../route_matcher'
# We'll drop support for v0 after Discourse 2.9 is released.
class Auth::DefaultCurrentUserProvider
-
CURRENT_USER_KEY ||= "_DISCOURSE_CURRENT_USER"
USER_TOKEN_KEY ||= "_DISCOURSE_USER_TOKEN"
API_KEY ||= "api_key"
@@ -37,7 +36,7 @@ class Auth::DefaultCurrentUserProvider
USER_API_CLIENT_ID ||= "HTTP_USER_API_CLIENT_ID"
API_KEY_ENV ||= "_DISCOURSE_API"
USER_API_KEY_ENV ||= "_DISCOURSE_USER_API"
- TOKEN_COOKIE ||= ENV['DISCOURSE_TOKEN_COOKIE'] || "_t"
+ TOKEN_COOKIE ||= ENV["DISCOURSE_TOKEN_COOKIE"] || "_t"
PATH_INFO ||= "PATH_INFO"
COOKIE_ATTEMPTS_PER_MIN ||= 10
BAD_TOKEN ||= "_DISCOURSE_BAD_TOKEN"
@@ -59,30 +58,20 @@ class Auth::DefaultCurrentUserProvider
"badges#show",
"tags#tag_feed",
"tags#show",
- *[:latest, :unread, :new, :read, :posted, :bookmarks].map { |f| "list##{f}_feed" },
- *[:all, :yearly, :quarterly, :monthly, :weekly, :daily].map { |p| "list#top_#{p}_feed" },
- *[:latest, :unread, :new, :read, :posted, :bookmarks].map { |f| "tags#show_#{f}" }
+ *%i[latest unread new read posted bookmarks].map { |f| "list##{f}_feed" },
+ *%i[all yearly quarterly monthly weekly daily].map { |p| "list#top_#{p}_feed" },
+ *%i[latest unread new read posted bookmarks].map { |f| "tags#show_#{f}" },
],
- formats: :rss
- ),
- RouteMatcher.new(
- methods: :get,
- actions: "users#bookmarks",
- formats: :ics
- ),
- RouteMatcher.new(
- methods: :post,
- actions: "admin/email#handle_mail",
- formats: nil
+ formats: :rss,
),
+ RouteMatcher.new(methods: :get, actions: "users#bookmarks", formats: :ics),
+ RouteMatcher.new(methods: :post, actions: "admin/email#handle_mail", formats: nil),
]
def self.find_v0_auth_cookie(request)
cookie = request.cookies[TOKEN_COOKIE]
- if cookie&.valid_encoding? && cookie.present? && cookie.size == TOKEN_SIZE
- cookie
- end
+ cookie if cookie&.valid_encoding? && cookie.present? && cookie.size == TOKEN_SIZE
end
def self.find_v1_auth_cookie(env)
@@ -111,12 +100,10 @@ class Auth::DefaultCurrentUserProvider
return @env[CURRENT_USER_KEY] if @env.key?(CURRENT_USER_KEY)
# bypass if we have the shared session header
- if shared_key = @env['HTTP_X_SHARED_SESSION_KEY']
+ if shared_key = @env["HTTP_X_SHARED_SESSION_KEY"]
uid = Discourse.redis.get("shared_session_key_#{shared_key}")
user = nil
- if uid
- user = User.find_by(id: uid.to_i)
- end
+ user = User.find_by(id: uid.to_i) if uid
@env[CURRENT_USER_KEY] = user
return user
end
@@ -130,28 +117,27 @@ class Auth::DefaultCurrentUserProvider
user_api_key ||= request[PARAMETER_USER_API_KEY]
end
- if [email protected]? && request[API_KEY] && api_parameter_allowed?
- api_key ||= request[API_KEY]
- end
+ api_key ||= request[API_KEY] if [email protected]? && request[API_KEY] && api_parameter_allowed?
auth_token = find_auth_token
current_user = nil
if auth_token
- limiter = RateLimiter.new(nil, "cookie_auth_#{request.ip}", COOKIE_ATTEMPTS_PER_MIN , 60)
+ limiter = RateLimiter.new(nil, "cookie_auth_#{request.ip}", COOKIE_ATTEMPTS_PER_MIN, 60)
if limiter.can_perform?
- @env[USER_TOKEN_KEY] = @user_token = begin
- UserAuthToken.lookup(
- auth_token,
- seen: true,
- user_agent: @env['HTTP_USER_AGENT'],
- path: @env['REQUEST_PATH'],
- client_ip: @request.ip
- )
- rescue ActiveRecord::ReadOnlyError
- nil
- end
+ @env[USER_TOKEN_KEY] = @user_token =
+ begin
+ UserAuthToken.lookup(
+ auth_token,
+ seen: true,
+ user_agent: @env["HTTP_USER_AGENT"],
+ path: @env["REQUEST_PATH"],
+ client_ip: @request.ip,
+ )
+ rescue ActiveRecord::ReadOnlyError
+ nil
+ end
current_user = @user_token.try(:user)
end
@@ -161,14 +147,10 @@ class Auth::DefaultCurrentUserProvider
begin
limiter.performed!
rescue RateLimiter::LimitExceeded
- raise Discourse::InvalidAccess.new(
- 'Invalid Access',
- nil,
- delete_cookie: TOKEN_COOKIE
- )
+ raise Discourse::InvalidAccess.new("Invalid Access", nil, delete_cookie: TOKEN_COOKIE)
end
end
- elsif @env['HTTP_DISCOURSE_LOGGED_IN']
+ elsif @env["HTTP_DISCOURSE_LOGGED_IN"]
@env[BAD_TOKEN] = true
end
@@ -177,10 +159,10 @@ class Auth::DefaultCurrentUserProvider
current_user = lookup_api_user(api_key, request)
if !current_user
raise Discourse::InvalidAccess.new(
- I18n.t('invalid_api_credentials'),
- nil,
- custom_message: "invalid_api_credentials"
- )
+ I18n.t("invalid_api_credentials"),
+ nil,
+ custom_message: "invalid_api_credentials",
+ )
end
raise Discourse::InvalidAccess if current_user.suspended? || !current_user.active
admin_api_key_limiter.performed! if !Rails.env.profile?
@@ -191,12 +173,13 @@ class Auth::DefaultCurrentUserProvider
if user_api_key
@hashed_user_api_key = ApiKey.hash_key(user_api_key)
- user_api_key_obj = UserApiKey
- .active
- .joins(:user)
- .where(key_hash: @hashed_user_api_key)
- .includes(:user, :scopes)
- .first
+ user_api_key_obj =
+ UserApiKey
+ .active
+ .joins(:user)
+ .where(key_hash: @hashed_user_api_key)
+ .includes(:user, :scopes)
+ .first
raise Discourse::InvalidAccess unless user_api_key_obj
@@ -208,18 +191,14 @@ class Auth::DefaultCurrentUserProvider
current_user = user_api_key_obj.user
raise Discourse::InvalidAccess if current_user.suspended? || !current_user.active
- if can_write?
- user_api_key_obj.update_last_used(@env[USER_API_CLIENT_ID])
- end
+ user_api_key_obj.update_last_used(@env[USER_API_CLIENT_ID]) if can_write?
@env[USER_API_KEY_ENV] = true
end
# keep this rule here as a safeguard
# under no conditions to suspended or inactive accounts get current_user
- if current_user && (current_user.suspended? || !current_user.active)
- current_user = nil
- end
+ current_user = nil if current_user && (current_user.suspended? || !current_user.active)
if current_user && should_update_last_seen?
ip = request.ip
@@ -247,31 +226,40 @@ class Auth::DefaultCurrentUserProvider
if !is_user_api? && @user_token && @user_token.user == user
rotated_at = @user_token.rotated_at
- needs_rotation = @user_token.auth_token_seen ? rotated_at < UserAuthToken::ROTATE_TIME.ago : rotated_at < UserAuthToken::URGENT_ROTATE_TIME.ago
+ needs_rotation =
+ (
+ if @user_token.auth_token_seen
+ rotated_at < UserAuthToken::ROTATE_TIME.ago
+ else
+ rotated_at < UserAuthToken::URGENT_ROTATE_TIME.ago
+ end
+ )
if needs_rotation
- if @user_token.rotate!(user_agent: @env['HTTP_USER_AGENT'],
- client_ip: @request.ip,
- path: @env['REQUEST_PATH'])
+ if @user_token.rotate!(
+ user_agent: @env["HTTP_USER_AGENT"],
+ client_ip: @request.ip,
+ path: @env["REQUEST_PATH"],
+ )
set_auth_cookie!(@user_token.unhashed_auth_token, user, cookie_jar)
DiscourseEvent.trigger(:user_session_refreshed, user)
end
end
end
- if !user && cookie_jar.key?(TOKEN_COOKIE)
- cookie_jar.delete(TOKEN_COOKIE)
- end
+ cookie_jar.delete(TOKEN_COOKIE) if !user && cookie_jar.key?(TOKEN_COOKIE)
end
def log_on_user(user, session, cookie_jar, opts = {})
- @env[USER_TOKEN_KEY] = @user_token = UserAuthToken.generate!(
- user_id: user.id,
- user_agent: @env['HTTP_USER_AGENT'],
- path: @env['REQUEST_PATH'],
- client_ip: @request.ip,
- staff: user.staff?,
- impersonate: opts[:impersonate])
+ @env[USER_TOKEN_KEY] = @user_token =
+ UserAuthToken.generate!(
+ user_id: user.id,
+ user_agent: @env["HTTP_USER_AGENT"],
+ path: @env["REQUEST_PATH"],
+ client_ip: @request.ip,
+ staff: user.staff?,
+ impersonate: opts[:impersonate],
+ )
set_auth_cookie!(@user_token.unhashed_auth_token, user, cookie_jar)
user.unstage!
@@ -288,23 +276,19 @@ class Auth::DefaultCurrentUserProvider
token: unhashed_auth_token,
user_id: user.id,
trust_level: user.trust_level,
- issued_at: Time.zone.now.to_i
+ issued_at: Time.zone.now.to_i,
}
- if SiteSetting.persistent_sessions
- expires = SiteSetting.maximum_session_age.hours.from_now
- end
+ expires = SiteSetting.maximum_session_age.hours.from_now if SiteSetting.persistent_sessions
- if SiteSetting.same_site_cookies != "Disabled"
- same_site = SiteSetting.same_site_cookies
- end
+ same_site = SiteSetting.same_site_cookies if SiteSetting.same_site_cookies != "Disabled"
cookie_jar.encrypted[TOKEN_COOKIE] = {
value: data,
httponly: true,
secure: SiteSetting.force_https,
expires: expires,
- same_site: same_site
+ same_site: same_site,
}
end
@@ -313,10 +297,8 @@ class Auth::DefaultCurrentUserProvider
# for signup flow, since all admin emails are stored in
# DISCOURSE_DEVELOPER_EMAILS for self-hosters.
def make_developer_admin(user)
- if user.active? &&
- !user.admin &&
- Rails.configuration.respond_to?(:developer_emails) &&
- Rails.configuration.developer_emails.include?(user.email)
+ if user.active? && !user.admin && Rails.configuration.respond_to?(:developer_emails) &&
+ Rails.configuration.developer_emails.include?(user.email)
user.admin = true
user.save
Group.refresh_automatic_groups!(:staff, :admins)
@@ -347,7 +329,7 @@ class Auth::DefaultCurrentUserProvider
@user_token.destroy
end
- cookie_jar.delete('authentication_data')
+ cookie_jar.delete("authentication_data")
cookie_jar.delete(TOKEN_COOKIE)
end
@@ -384,9 +366,7 @@ class Auth::DefaultCurrentUserProvider
if api_key = ApiKey.active.with_key(api_key_value).includes(:user).first
api_username = header_api_key? ? @env[HEADER_API_USERNAME] : request[API_USERNAME]
- if !api_key.request_allowed?(@env)
- return nil
- end
+ return nil if !api_key.request_allowed?(@env)
user =
if api_key.user
@@ -395,7 +375,8 @@ class Auth::DefaultCurrentUserProvider
User.find_by(username_lower: api_username.downcase)
elsif user_id = header_api_key? ? @env[HEADER_API_USER_ID] : request["api_user_id"]
User.find_by(id: user_id.to_i)
- elsif external_id = header_api_key? ? @env[HEADER_API_USER_EXTERNAL_ID] : request["api_user_external_id"]
+ elsif external_id =
+ header_api_key? ? @env[HEADER_API_USER_EXTERNAL_ID] : request["api_user_external_id"]
SingleSignOnRecord.find_by(external_id: external_id.to_s).try(:user)
end
@@ -435,52 +416,48 @@ class Auth::DefaultCurrentUserProvider
limit = GlobalSetting.max_admin_api_reqs_per_minute.to_i
if GlobalSetting.respond_to?(:max_admin_api_reqs_per_key_per_minute)
- Discourse.deprecate("DISCOURSE_MAX_ADMIN_API_REQS_PER_KEY_PER_MINUTE is deprecated. Please use DISCOURSE_MAX_ADMIN_API_REQS_PER_MINUTE", drop_from: '2.9.0')
- limit = [
- GlobalSetting.max_admin_api_reqs_per_key_per_minute.to_i,
- limit
- ].max
+ Discourse.deprecate(
+ "DISCOURSE_MAX_ADMIN_API_REQS_PER_KEY_PER_MINUTE is deprecated. Please use DISCOURSE_MAX_ADMIN_API_REQS_PER_MINUTE",
+ drop_from: "2.9.0",
+ )
+ limit = [GlobalSetting.max_admin_api_reqs_per_key_per_minute.to_i, limit].max
end
- @admin_api_key_limiter = RateLimiter.new(
- nil,
- "admin_api_min",
- limit,
- 60,
- error_code: "admin_api_key_rate_limit"
- )
+ @admin_api_key_limiter =
+ RateLimiter.new(nil, "admin_api_min", limit, 60, error_code: "admin_api_key_rate_limit")
end
def user_api_key_limiter_60_secs
- @user_api_key_limiter_60_secs ||= RateLimiter.new(
- nil,
- "user_api_min_#{@hashed_user_api_key}",
- GlobalSetting.max_user_api_reqs_per_minute,
- 60,
- error_code: "user_api_key_limiter_60_secs"
- )
+ @user_api_key_limiter_60_secs ||=
+ RateLimiter.new(
+ nil,
+ "user_api_min_#{@hashed_user_api_key}",
+ GlobalSetting.max_user_api_reqs_per_minute,
+ 60,
+ error_code: "user_api_key_limiter_60_secs",
+ )
end
def user_api_key_limiter_1_day
- @user_api_key_limiter_1_day ||= RateLimiter.new(
- nil,
- "user_api_day_#{@hashed_user_api_key}",
- GlobalSetting.max_user_api_reqs_per_day,
- 86400,
- error_code: "user_api_key_limiter_1_day"
- )
+ @user_api_key_limiter_1_day ||=
+ RateLimiter.new(
+ nil,
+ "user_api_day_#{@hashed_user_api_key}",
+ GlobalSetting.max_user_api_reqs_per_day,
+ 86_400,
+ error_code: "user_api_key_limiter_1_day",
+ )
end
def find_auth_token
return @auth_token if defined?(@auth_token)
- @auth_token = begin
- if v0 = self.class.find_v0_auth_cookie(@request)
- v0
- elsif v1 = self.class.find_v1_auth_cookie(@env)
- if v1[:issued_at] >= SiteSetting.maximum_session_age.hours.ago.to_i
- v1[:token]
+ @auth_token =
+ begin
+ if v0 = self.class.find_v0_auth_cookie(@request)
+ v0
+ elsif v1 = self.class.find_v1_auth_cookie(@env)
+ v1[:token] if v1[:issued_at] >= SiteSetting.maximum_session_age.hours.ago.to_i
end
end
- end
end
end
diff --git a/lib/auth/discord_authenticator.rb b/lib/auth/discord_authenticator.rb
index 2629e6d3690..56d8923cd4c 100644
--- a/lib/auth/discord_authenticator.rb
+++ b/lib/auth/discord_authenticator.rb
@@ -2,35 +2,34 @@
class Auth::DiscordAuthenticator < Auth::ManagedAuthenticator
class DiscordStrategy < OmniAuth::Strategies::OAuth2
- option :name, 'discord'
- option :scope, 'identify email guilds'
+ option :name, "discord"
+ option :scope, "identify email guilds"
option :client_options,
- site: 'https://discord.com/api',
- authorize_url: 'oauth2/authorize',
- token_url: 'oauth2/token'
+ site: "https://discord.com/api",
+ authorize_url: "oauth2/authorize",
+ token_url: "oauth2/token"
option :authorize_options, %i[scope permissions]
- uid { raw_info['id'] }
+ uid { raw_info["id"] }
info do
{
- name: raw_info['username'],
- email: raw_info['verified'] ? raw_info['email'] : nil,
- image: "https://cdn.discordapp.com/avatars/#{raw_info['id']}/#{raw_info['avatar']}"
+ name: raw_info["username"],
+ email: raw_info["verified"] ? raw_info["email"] : nil,
+ image: "https://cdn.discordapp.com/avatars/#{raw_info["id"]}/#{raw_info["avatar"]}",
}
end
- extra do
- {
- 'raw_info' => raw_info
- }
- end
+ extra { { "raw_info" => raw_info } }
def raw_info
- @raw_info ||= access_token.get('users/@me').parsed.
- merge(guilds: access_token.get('users/@me/guilds').parsed)
+ @raw_info ||=
+ access_token
+ .get("users/@me")
+ .parsed
+ .merge(guilds: access_token.get("users/@me/guilds").parsed)
end
def callback_url
@@ -39,7 +38,7 @@ class Auth::DiscordAuthenticator < Auth::ManagedAuthenticator
end
def name
- 'discord'
+ "discord"
end
def enabled?
@@ -48,23 +47,26 @@ class Auth::DiscordAuthenticator < Auth::ManagedAuthenticator
def register_middleware(omniauth)
omniauth.provider DiscordStrategy,
- setup: lambda { |env|
- strategy = env["omniauth.strategy"]
- strategy.options[:client_id] = SiteSetting.discord_client_id
- strategy.options[:client_secret] = SiteSetting.discord_secret
- }
- end
+ setup:
+ lambda { |env|
+ strategy = env["omniauth.strategy"]
+ strategy.options[:client_id] = SiteSetting.discord_client_id
+ strategy.options[:client_secret] = SiteSetting.discord_secret
+ }
+ end
def after_authenticate(auth_token, existing_account: nil)
allowed_guild_ids = SiteSetting.discord_trusted_guilds.split("|")
if allowed_guild_ids.length > 0
- user_guild_ids = auth_token.extra[:raw_info][:guilds].map { |g| g['id'] }
+ user_guild_ids = auth_token.extra[:raw_info][:guilds].map { |g| g["id"] }
if (user_guild_ids & allowed_guild_ids).empty? # User is not in any allowed guilds
- return Auth::Result.new.tap do |auth_result|
- auth_result.failed = true
- auth_result.failed_reason = I18n.t("discord.not_in_allowed_guild")
- end
+ return(
+ Auth::Result.new.tap do |auth_result|
+ auth_result.failed = true
+ auth_result.failed_reason = I18n.t("discord.not_in_allowed_guild")
+ end
+ )
end
end
diff --git a/lib/auth/facebook_authenticator.rb b/lib/auth/facebook_authenticator.rb
index 48a57cd9aec..18924c5fc00 100644
--- a/lib/auth/facebook_authenticator.rb
+++ b/lib/auth/facebook_authenticator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class Auth::FacebookAuthenticator < Auth::ManagedAuthenticator
-
AVATAR_SIZE ||= 480
def name
@@ -14,15 +13,19 @@ class Auth::FacebookAuthenticator < Auth::ManagedAuthenticator
def register_middleware(omniauth)
omniauth.provider :facebook,
- setup: lambda { |env|
- strategy = env["omniauth.strategy"]
- strategy.options[:client_id] = SiteSetting.facebook_app_id
- strategy.options[:client_secret] = SiteSetting.facebook_app_secret
- strategy.options[:info_fields] = 'name,first_name,last_name,email'
- strategy.options[:image_size] = { width: AVATAR_SIZE, height: AVATAR_SIZE }
- strategy.options[:secure_image_url] = true
- },
- scope: "email"
+ setup:
+ lambda { |env|
+ strategy = env["omniauth.strategy"]
+ strategy.options[:client_id] = SiteSetting.facebook_app_id
+ strategy.options[:client_secret] = SiteSetting.facebook_app_secret
+ strategy.options[:info_fields] = "name,first_name,last_name,email"
+ strategy.options[:image_size] = {
+ width: AVATAR_SIZE,
+ height: AVATAR_SIZE,
+ }
+ strategy.options[:secure_image_url] = true
+ },
+ scope: "email"
end
# facebook doesn't return unverified email addresses so it's safe to assume
diff --git a/lib/auth/github_authenticator.rb b/lib/auth/github_authenticator.rb
index 865cb21e0c2..03f2913f277 100644
--- a/lib/auth/github_authenticator.rb
+++ b/lib/auth/github_authenticator.rb
@@ -1,9 +1,8 @@
# frozen_string_literal: true
-require 'has_errors'
+require "has_errors"
class Auth::GithubAuthenticator < Auth::ManagedAuthenticator
-
def name
"github"
end
@@ -50,12 +49,13 @@ class Auth::GithubAuthenticator < Auth::ManagedAuthenticator
def register_middleware(omniauth)
omniauth.provider :github,
- setup: lambda { |env|
- strategy = env["omniauth.strategy"]
- strategy.options[:client_id] = SiteSetting.github_client_id
- strategy.options[:client_secret] = SiteSetting.github_client_secret
- },
- scope: "user:email"
+ setup:
+ lambda { |env|
+ strategy = env["omniauth.strategy"]
+ strategy.options[:client_id] = SiteSetting.github_client_id
+ strategy.options[:client_secret] = SiteSetting.github_client_secret
+ },
+ scope: "user:email"
end
# the omniauth-github gem only picks up the primary email if it's verified:
diff --git a/lib/auth/google_oauth2_authenticator.rb b/lib/auth/google_oauth2_authenticator.rb
index ba35b1fecd3..3e7c4c4afb6 100644
--- a/lib/auth/google_oauth2_authenticator.rb
+++ b/lib/auth/google_oauth2_authenticator.rb
@@ -22,47 +22,46 @@ class Auth::GoogleOAuth2Authenticator < Auth::ManagedAuthenticator
def register_middleware(omniauth)
options = {
- setup: lambda { |env|
- strategy = env["omniauth.strategy"]
- strategy.options[:client_id] = SiteSetting.google_oauth2_client_id
- strategy.options[:client_secret] = SiteSetting.google_oauth2_client_secret
-
- if (google_oauth2_hd = SiteSetting.google_oauth2_hd).present?
- strategy.options[:hd] = google_oauth2_hd
- end
-
- if (google_oauth2_prompt = SiteSetting.google_oauth2_prompt).present?
- strategy.options[:prompt] = google_oauth2_prompt.gsub("|", " ")
- end
-
- # All the data we need for the `info` and `credentials` auth hash
- # are obtained via the user info API, not the JWT. Using and verifying
- # the JWT can fail due to clock skew, so let's skip it completely.
- # https://github.com/zquestz/omniauth-google-oauth2/pull/392
- strategy.options[:skip_jwt] = true
- }
+ setup:
+ lambda do |env|
+ strategy = env["omniauth.strategy"]
+ strategy.options[:client_id] = SiteSetting.google_oauth2_client_id
+ strategy.options[:client_secret] = SiteSetting.google_oauth2_client_secret
+
+ if (google_oauth2_hd = SiteSetting.google_oauth2_hd).present?
+ strategy.options[:hd] = google_oauth2_hd
+ end
+
+ if (google_oauth2_prompt = SiteSetting.google_oauth2_prompt).present?
+ strategy.options[:prompt] = google_oauth2_prompt.gsub("|", " ")
+ end
+
+ # All the data we need for the `info` and `credentials` auth hash
+ # are obtained via the user info API, not the JWT. Using and verifying
+ # the JWT can fail due to clock skew, so let's skip it completely.
+ # https://github.com/zquestz/omniauth-google-oauth2/pull/392
+ strategy.options[:skip_jwt] = true
+ end,
}
omniauth.provider :google_oauth2, options
end
def after_authenticate(auth_token, existing_account: nil)
groups = provides_groups? ? raw_groups(auth_token.uid) : nil
- if groups
- auth_token.extra[:raw_groups] = groups
- end
+ auth_token.extra[:raw_groups] = groups if groups
result = super
if groups
- result.associated_groups = groups.map { |group| group.with_indifferent_access.slice(:id, :name) }
+ result.associated_groups =
+ groups.map { |group| group.with_indifferent_access.slice(:id, :name) }
end
result
end
def provides_groups?
- SiteSetting.google_oauth2_hd.present? &&
- SiteSetting.google_oauth2_hd_groups &&
+ SiteSetting.google_oauth2_hd.present? && SiteSetting.google_oauth2_hd_groups &&
SiteSetting.google_oauth2_hd_groups_service_account_admin_email.present? &&
SiteSetting.google_oauth2_hd_groups_service_account_json.present?
end
@@ -77,20 +76,20 @@ class Auth::GoogleOAuth2Authenticator < Auth::ManagedAuthenticator
return if client.nil?
loop do
- params = {
- userKey: uid
- }
+ params = { userKey: uid }
params[:pageToken] = page_token if page_token
response = client.get(groups_url, params: params, raise_errors: false)
if response.status == 200
response = response.parsed
- groups.push(*response['groups'])
- page_token = response['nextPageToken']
+ groups.push(*response["groups"])
+ page_token = response["nextPageToken"]
break if page_token.nil?
else
- Rails.logger.error("[Discourse Google OAuth2] failed to retrieve groups for #{uid} - status #{response.status}")
+ Rails.logger.error(
+ "[Discourse Google OAuth2] failed to retrieve groups for #{uid} - status #{response.status}",
+ )
break
end
end
@@ -107,26 +106,35 @@ class Auth::GoogleOAuth2Authenticator < Auth::ManagedAuthenticator
scope: GROUPS_SCOPE,
iat: Time.now.to_i,
exp: Time.now.to_i + 60,
- sub: SiteSetting.google_oauth2_hd_groups_service_account_admin_email
+ sub: SiteSetting.google_oauth2_hd_groups_service_account_admin_email,
}
headers = { "alg" => "RS256", "typ" => "JWT" }
key = OpenSSL::PKey::RSA.new(service_account_info["private_key"])
- encoded_jwt = ::JWT.encode(payload, key, 'RS256', headers)
-
- client = OAuth2::Client.new(
- SiteSetting.google_oauth2_client_id,
- SiteSetting.google_oauth2_client_secret,
- site: OAUTH2_BASE_URL
- )
-
- token_response = client.request(:post, '/token', body: {
- grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
- assertion: encoded_jwt
- }, raise_errors: false)
+ encoded_jwt = ::JWT.encode(payload, key, "RS256", headers)
+
+ client =
+ OAuth2::Client.new(
+ SiteSetting.google_oauth2_client_id,
+ SiteSetting.google_oauth2_client_secret,
+ site: OAUTH2_BASE_URL,
+ )
+
+ token_response =
+ client.request(
+ :post,
+ "/token",
+ body: {
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
+ assertion: encoded_jwt,
+ },
+ raise_errors: false,
+ )
if token_response.status != 200
- Rails.logger.error("[Discourse Google OAuth2] failed to retrieve group fetch token - status #{token_response.status}")
+ Rails.logger.error(
+ "[Discourse Google OAuth2] failed to retrieve group fetch token - status #{token_response.status}",
+ )
return
end
diff --git a/lib/auth/managed_authenticator.rb b/lib/auth/managed_authenticator.rb
index 41f36a611fc..bb163d1a715 100644
--- a/lib/auth/managed_authenticator.rb
+++ b/lib/auth/managed_authenticator.rb
@@ -56,28 +56,27 @@ class Auth::ManagedAuthenticator < Auth::Authenticator
def after_authenticate(auth_token, existing_account: nil)
# Try and find an association for this account
- association = UserAssociatedAccount.find_or_initialize_by(provider_name: auth_token[:provider], provider_uid: auth_token[:uid])
+ association =
+ UserAssociatedAccount.find_or_initialize_by(
+ provider_name: auth_token[:provider],
+ provider_uid: auth_token[:uid],
+ )
# Reconnecting to existing account
- if can_connect_existing_user? && existing_account && (association.user.nil? || existing_account.id != association.user_id)
+ if can_connect_existing_user? && existing_account &&
+ (association.user.nil? || existing_account.id != association.user_id)
association.user = existing_account
end
# Matching an account by email
- if match_by_email &&
- association.user.nil? &&
- (user = find_user_by_email(auth_token))
-
+ if match_by_email && association.user.nil? && (user = find_user_by_email(auth_token))
UserAssociatedAccount.where(user: user, provider_name: auth_token[:provider]).destroy_all # Destroy existing associations for the new user
association.user = user
end
# Matching an account by username
- if match_by_username &&
- association.user.nil? &&
- SiteSetting.username_change_period.zero? &&
- (user = find_user_by_username(auth_token))
-
+ if match_by_username && association.user.nil? && SiteSetting.username_change_period.zero? &&
+ (user = find_user_by_username(auth_token))
UserAssociatedAccount.where(user: user, provider_name: auth_token[:provider]).destroy_all # Destroy existing associations for the new user
association.user = user
end
@@ -100,7 +99,14 @@ class Auth::ManagedAuthenticator < Auth::Authenticator
result = Auth::Result.new
info = auth_token[:info]
result.email = info[:email]
- result.name = (info[:first_name] && info[:last_name]) ? "#{info[:first_name]} #{info[:last_name]}" : info[:name]
+ result.name =
+ (
+ if (info[:first_name] && info[:last_name])
+ "#{info[:first_name]} #{info[:last_name]}"
+ else
+ info[:name]
+ end
+ )
if result.name.present? && result.name == result.email
# Some IDPs send the email address in the name parameter (e.g. Auth0 with default configuration)
# We add some generic protection here, so that users don't accidently make their email addresses public
@@ -109,10 +115,7 @@ class Auth::ManagedAuthenticator < Auth::Authenticator
result.username = info[:nickname]
result.email_valid = primary_email_verified?(auth_token) if result.email.present?
result.overrides_email = always_update_user_email?
- result.extra_data = {
- provider: auth_token[:provider],
- uid: auth_token[:uid]
- }
+ result.extra_data = { provider: auth_token[:provider], uid: auth_token[:uid] }
result.user = association.user
result
@@ -120,7 +123,11 @@ class Auth::ManagedAuthenticator < Auth::Authenticator
def after_create_account(user, auth_result)
auth_token = auth_result[:extra_data]
- association = UserAssociatedAccount.find_or_initialize_by(provider_name: auth_token[:provider], provider_uid: auth_token[:uid])
+ association =
+ UserAssociatedAccount.find_or_initialize_by(
+ provider_name: auth_token[:provider],
+ provider_uid: auth_token[:uid],
+ )
association.user = user
association.save!
@@ -132,16 +139,12 @@ class Auth::ManagedAuthenticator < Auth::Authenticator
def find_user_by_email(auth_token)
email = auth_token.dig(:info, :email)
- if email && primary_email_verified?(auth_token)
- User.find_by_email(email)
- end
+ User.find_by_email(email) if email && primary_email_verified?(auth_token)
end
def find_user_by_username(auth_token)
username = auth_token.dig(:info, :nickname)
- if username
- User.find_by_username(username)
- end
+ User.find_by_username(username) if username
end
def retrieve_avatar(user, url)
@@ -158,7 +161,7 @@ class Auth::ManagedAuthenticator < Auth::Authenticator
if bio || location
profile = user.user_profile
- profile.bio_raw = bio unless profile.bio_raw.present?
+ profile.bio_raw = bio unless profile.bio_raw.present?
profile.location = location unless profile.location.present?
profile.save
end
diff --git a/lib/auth/result.rb b/lib/auth/result.rb
index 397a373f80e..8e83fea8ba2 100644
--- a/lib/auth/result.rb
+++ b/lib/auth/result.rb
@@ -1,48 +1,48 @@
# frozen_string_literal: true
class Auth::Result
- ATTRIBUTES = [
- :user,
- :name,
- :username,
- :email,
- :email_valid,
- :extra_data,
- :awaiting_activation,
- :awaiting_approval,
- :authenticated,
- :authenticator_name,
- :requires_invite,
- :not_allowed_from_ip_address,
- :admin_not_allowed_from_ip_address,
- :skip_email_validation,
- :destination_url,
- :omniauth_disallow_totp,
- :failed,
- :failed_reason,
- :failed_code,
- :associated_groups,
- :overrides_email,
- :overrides_username,
- :overrides_name,
+ ATTRIBUTES = %i[
+ user
+ name
+ username
+ email
+ email_valid
+ extra_data
+ awaiting_activation
+ awaiting_approval
+ authenticated
+ authenticator_name
+ requires_invite
+ not_allowed_from_ip_address
+ admin_not_allowed_from_ip_address
+ skip_email_validation
+ destination_url
+ omniauth_disallow_totp
+ failed
+ failed_reason
+ failed_code
+ associated_groups
+ overrides_email
+ overrides_username
+ overrides_name
]
attr_accessor *ATTRIBUTES
# These are stored in the session during
# account creation. The user cannot read or modify them
- SESSION_ATTRIBUTES = [
- :email,
- :username,
- :email_valid,
- :name,
- :authenticator_name,
- :extra_data,
- :skip_email_validation,
- :associated_groups,
- :overrides_email,
- :overrides_username,
- :overrides_name,
+ SESSION_ATTRIBUTES = %i[
+ email
+ username
+ email_valid
+ name
+ authenticator_name
+ extra_data
+ skip_email_validation
+ associated_groups
+ overrides_email
+ overrides_username
+ overrides_name
]
def [](key)
@@ -59,9 +59,7 @@ class Auth::Result
end
def email_valid=(val)
- if !val.in? [true, false, nil]
- raise ArgumentError, "email_valid should be boolean or nil"
- end
+ raise ArgumentError, "email_valid should be boolean or nil" if !val.in? [true, false, nil]
@email_valid = !!val
end
@@ -83,14 +81,14 @@ class Auth::Result
def apply_user_attributes!
change_made = false
- if (SiteSetting.auth_overrides_username? || overrides_username) && (resolved_username = resolve_username).present?
+ if (SiteSetting.auth_overrides_username? || overrides_username) &&
+ (resolved_username = resolve_username).present?
change_made = UsernameChanger.override(user, resolved_username)
end
- if (SiteSetting.auth_overrides_email || overrides_email || user&.email&.ends_with?(".invalid")) &&
- email_valid &&
- email.present? &&
- user.email != Email.downcase(email)
+ if (
+ SiteSetting.auth_overrides_email || overrides_email || user&.email&.ends_with?(".invalid")
+ ) && email_valid && email.present? && user.email != Email.downcase(email)
user.email = email
change_made = true
end
@@ -109,11 +107,12 @@ class Auth::Result
associated_groups.uniq.each do |associated_group|
begin
- associated_group = AssociatedGroup.find_or_create_by(
- name: associated_group[:name],
- provider_id: associated_group[:id],
- provider_name: extra_data[:provider]
- )
+ associated_group =
+ AssociatedGroup.find_or_create_by(
+ name: associated_group[:name],
+ provider_id: associated_group[:id],
+ provider_name: extra_data[:provider],
+ )
rescue ActiveRecord::RecordNotUnique
retry
end
@@ -135,22 +134,12 @@ class Auth::Result
end
def to_client_hash
- if requires_invite
- return { requires_invite: true }
- end
+ return { requires_invite: true } if requires_invite
- if user&.suspended?
- return {
- suspended: true,
- suspended_message: user.suspended_message
- }
- end
+ return { suspended: true, suspended_message: user.suspended_message } if user&.suspended?
if omniauth_disallow_totp
- return {
- omniauth_disallow_totp: !!omniauth_disallow_totp,
- email: email
- }
+ return { omniauth_disallow_totp: !!omniauth_disallow_totp, email: email }
end
if user
@@ -159,7 +148,7 @@ class Auth::Result
awaiting_activation: !!awaiting_activation,
awaiting_approval: !!awaiting_approval,
not_allowed_from_ip_address: !!not_allowed_from_ip_address,
- admin_not_allowed_from_ip_address: !!admin_not_allowed_from_ip_address
+ admin_not_allowed_from_ip_address: !!admin_not_allowed_from_ip_address,
}
result[:destination_url] = destination_url if authenticated && destination_url.present?
@@ -173,7 +162,7 @@ class Auth::Result
auth_provider: authenticator_name,
email_valid: !!email_valid,
can_edit_username: can_edit_username,
- can_edit_name: can_edit_name
+ can_edit_name: can_edit_name,
}
result[:destination_url] = destination_url if destination_url.present?
@@ -190,9 +179,7 @@ class Auth::Result
def staged_user
return @staged_user if defined?(@staged_user)
- if email.present? && email_valid
- @staged_user = User.where(staged: true).find_by_email(email)
- end
+ @staged_user = User.where(staged: true).find_by_email(email) if email.present? && email_valid
end
def username_suggester_attributes
diff --git a/lib/auth/twitter_authenticator.rb b/lib/auth/twitter_authenticator.rb
index 35f990bb667..5817f617e35 100644
--- a/lib/auth/twitter_authenticator.rb
+++ b/lib/auth/twitter_authenticator.rb
@@ -17,11 +17,12 @@ class Auth::TwitterAuthenticator < Auth::ManagedAuthenticator
def register_middleware(omniauth)
omniauth.provider :twitter,
- setup: lambda { |env|
- strategy = env["omniauth.strategy"]
- strategy.options[:consumer_key] = SiteSetting.twitter_consumer_key
- strategy.options[:consumer_secret] = SiteSetting.twitter_consumer_secret
- }
+ setup:
+ lambda { |env|
+ strategy = env["omniauth.strategy"]
+ strategy.options[:consumer_key] = SiteSetting.twitter_consumer_key
+ strategy.options[:consumer_secret] = SiteSetting.twitter_consumer_secret
+ }
end
# twitter doesn't return unverfied email addresses in the API
diff --git a/lib/autospec/base_runner.rb b/lib/autospec/base_runner.rb
index bc78371f5c3..4a0128f4ccf 100644
--- a/lib/autospec/base_runner.rb
+++ b/lib/autospec/base_runner.rb
@@ -1,9 +1,7 @@
# frozen_string_literal: true
module Autospec
-
class BaseRunner
-
# used when starting the runner - preloading happens here
def start(opts = {})
end
@@ -32,7 +30,5 @@ module Autospec
# used to stop the runner
def stop
end
-
end
-
end
diff --git a/lib/autospec/formatter.rb b/lib/autospec/formatter.rb
index a6b26aff7ff..5dee7dd42cf 100644
--- a/lib/autospec/formatter.rb
+++ b/lib/autospec/formatter.rb
@@ -3,11 +3,15 @@
require "rspec/core/formatters/base_text_formatter"
require "parallel_tests/rspec/logger_base"
-module Autospec; end
+module Autospec
+end
class Autospec::Formatter < RSpec::Core::Formatters::BaseTextFormatter
-
- RSpec::Core::Formatters.register self, :example_passed, :example_pending, :example_failed, :start_dump
+ RSpec::Core::Formatters.register self,
+ :example_passed,
+ :example_pending,
+ :example_failed,
+ :start_dump
RSPEC_RESULT = "./tmp/rspec_result"
@@ -19,15 +23,15 @@ class Autospec::Formatter < RSpec::Core::Formatters::BaseTextFormatter
end
def example_passed(_notification)
- output.print RSpec::Core::Formatters::ConsoleCodes.wrap('.', :success)
+ output.print RSpec::Core::Formatters::ConsoleCodes.wrap(".", :success)
end
def example_pending(_notification)
- output.print RSpec::Core::Formatters::ConsoleCodes.wrap('*', :pending)
+ output.print RSpec::Core::Formatters::ConsoleCodes.wrap("*", :pending)
end
def example_failed(notification)
- output.print RSpec::Core::Formatters::ConsoleCodes.wrap('F', :failure)
+ output.print RSpec::Core::Formatters::ConsoleCodes.wrap("F", :failure)
@fail_file.puts(notification.example.location + " ")
@fail_file.flush
end
@@ -40,5 +44,4 @@ class Autospec::Formatter < RSpec::Core::Formatters::BaseTextFormatter
@fail_file.close
super(filename)
end
-
end
diff --git a/lib/autospec/manager.rb b/lib/autospec/manager.rb
index e912887d2e2..87dded1963c 100644
--- a/lib/autospec/manager.rb
+++ b/lib/autospec/manager.rb
@@ -7,7 +7,8 @@ require "autospec/reload_css"
require "autospec/base_runner"
require "socket_server"
-module Autospec; end
+module Autospec
+end
class Autospec::Manager
def self.run(opts = {})
@@ -25,7 +26,10 @@ class Autospec::Manager
end
def run
- Signal.trap("HUP") { stop_runners; exit }
+ Signal.trap("HUP") do
+ stop_runners
+ exit
+ end
Signal.trap("INT") do
begin
@@ -47,7 +51,6 @@ class Autospec::Manager
STDIN.gets
process_queue
end
-
rescue => e
fail(e, "failed in run")
ensure
@@ -71,16 +74,16 @@ class Autospec::Manager
@queue.reject! { |_, s, _| s == "spec" }
- if current_runner
- @queue.concat [['spec', 'spec', current_runner]]
- end
+ @queue.concat [["spec", "spec", current_runner]] if current_runner
@runners.each do |runner|
- @queue.concat [['spec', 'spec', runner]] unless @queue.any? { |_, s, r| s == "spec" && r == runner }
+ unless @queue.any? { |_, s, r| s == "spec" && r == runner }
+ @queue.concat [["spec", "spec", runner]]
+ end
end
end
- [:start, :stop, :abort].each do |verb|
+ %i[start stop abort].each do |verb|
define_method("#{verb}_runners") do
puts "@@@@@@@@@@@@ #{verb}_runners" if @debug
@runners.each(&verb)
@@ -89,11 +92,7 @@ class Autospec::Manager
def start_service_queue
puts "@@@@@@@@@@@@ start_service_queue" if @debug
- Thread.new do
- while true
- thread_loop
- end
- end
+ Thread.new { thread_loop while true }
end
# the main loop, will run the specs in the queue till one fails or the queue is empty
@@ -176,9 +175,7 @@ class Autospec::Manager
Dir[root_path + "/plugins/*"].each do |f|
next if !File.directory? f
resolved = File.realpath(f)
- if resolved != f
- map[resolved] = f
- end
+ map[resolved] = f if resolved != f
end
map
end
@@ -188,9 +185,7 @@ class Autospec::Manager
resolved = file
@reverse_map ||= reverse_symlink_map
@reverse_map.each do |location, discourse_location|
- if file.start_with?(location)
- resolved = discourse_location + file[location.length..-1]
- end
+ resolved = discourse_location + file[location.length..-1] if file.start_with?(location)
end
resolved
@@ -199,9 +194,7 @@ class Autospec::Manager
def listen_for_changes
puts "@@@@@@@@@@@@ listen_for_changes" if @debug
- options = {
- ignore: /^lib\/autospec/,
- }
+ options = { ignore: %r{^lib/autospec} }
if @opts[:force_polling]
options[:force_polling] = true
@@ -210,14 +203,14 @@ class Autospec::Manager
path = root_path
- if ENV['VIM_AUTOSPEC']
+ if ENV["VIM_AUTOSPEC"]
STDERR.puts "Using VIM file listener"
socket_path = (Rails.root + "tmp/file_change.sock").to_s
FileUtils.rm_f(socket_path)
server = SocketServer.new(socket_path)
server.start do |line|
- file, line = line.split(' ')
+ file, line = line.split(" ")
file = reverse_symlink(file)
file = file.sub(Rails.root.to_s + "/", "")
# process_change can acquire a mutex and block
@@ -235,20 +228,20 @@ class Autospec::Manager
end
# to speed up boot we use a thread
- ["spec", "lib", "app", "config", "test", "vendor", "plugins"].each do |watch|
-
+ %w[spec lib app config test vendor plugins].each do |watch|
puts "@@@@@@@@@ Listen to #{path}/#{watch} #{options}" if @debug
Thread.new do
begin
- listener = Listen.to("#{path}/#{watch}", options) do |modified, added, _|
- paths = [modified, added].flatten
- paths.compact!
- paths.map! do |long|
- long = reverse_symlink(long)
- long[(path.length + 1)..-1]
+ listener =
+ Listen.to("#{path}/#{watch}", options) do |modified, added, _|
+ paths = [modified, added].flatten
+ paths.compact!
+ paths.map! do |long|
+ long = reverse_symlink(long)
+ long[(path.length + 1)..-1]
+ end
+ process_change(paths)
end
- process_change(paths)
- end
listener.start
sleep
rescue => e
@@ -257,7 +250,6 @@ class Autospec::Manager
end
end
end
-
end
def process_change(files)
@@ -285,13 +277,9 @@ class Autospec::Manager
hit = true
spec = v ? (v.arity == 1 ? v.call(m) : v.call) : file
with_line = spec
- if spec == file && line
- with_line = spec + ":" << line.to_s
- end
+ with_line = spec + ":" << line.to_s if spec == file && line
if File.exist?(spec) || Dir.exist?(spec)
- if with_line != spec
- specs << [file, spec, runner]
- end
+ specs << [file, spec, runner] if with_line != spec
specs << [file, with_line, runner]
end
end
@@ -329,9 +317,7 @@ class Autospec::Manager
focus = @queue.shift
@queue.unshift([file, spec, runner])
unless spec.include?(":") && focus[1].include?(spec.split(":")[0])
- if focus[1].include?(spec) || file != spec
- @queue.unshift(focus)
- end
+ @queue.unshift(focus) if focus[1].include?(spec) || file != spec
end
else
@queue.unshift([file, spec, runner])
diff --git a/lib/autospec/reload_css.rb b/lib/autospec/reload_css.rb
index 8f24cdec984..78258bed17f 100644
--- a/lib/autospec/reload_css.rb
+++ b/lib/autospec/reload_css.rb
@@ -1,9 +1,9 @@
# frozen_string_literal: true
-module Autospec; end
+module Autospec
+end
class Autospec::ReloadCss
-
WATCHERS = {}
def self.watch(pattern, &blk)
WATCHERS[pattern] = blk
@@ -30,7 +30,7 @@ class Autospec::ReloadCss
if paths.any? { |p| p =~ /\.(css|s[ac]ss)/ }
# todo connect to dev instead?
ActiveRecord::Base.establish_connection
- [:desktop, :mobile].each do |style|
+ %i[desktop mobile].each do |style|
s = DiscourseStylesheets.new(style)
s.compile
paths << "public" + s.stylesheet_relpath_no_digest
@@ -44,10 +44,9 @@ class Autospec::ReloadCss
p = p.sub(/\.sass\.erb/, "")
p = p.sub(/\.sass/, "")
p = p.sub(/\.scss/, "")
- p = p.sub(/^app\/assets\/stylesheets/, "assets")
+ p = p.sub(%r{^app/assets/stylesheets}, "assets")
{ name: p, hash: hash || SecureRandom.hex }
end
message_bus.publish "/file-change", paths
end
-
end
diff --git a/lib/autospec/rspec_runner.rb b/lib/autospec/rspec_runner.rb
index b4ebbf3ca2f..408b6fe79e0 100644
--- a/lib/autospec/rspec_runner.rb
+++ b/lib/autospec/rspec_runner.rb
@@ -1,9 +1,7 @@
# frozen_string_literal: true
module Autospec
-
class RspecRunner < BaseRunner
-
WATCHERS = {}
def self.watch(pattern, &blk)
WATCHERS[pattern] = blk
@@ -13,26 +11,28 @@ module Autospec
end
# Discourse specific
- watch(%r{^lib/(.+)\.rb$}) { |m| "spec/components/#{m[1]}_spec.rb" }
+ watch(%r{^lib/(.+)\.rb$}) { |m| "spec/components/#{m[1]}_spec.rb" }
- watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
- watch(%r{^app/(.+)(\.erb|\.haml)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
+ watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
+ watch(%r{^app/(.+)(\.erb|\.haml)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^spec/.+_spec\.rb$})
- watch(%r{^spec/support/.+\.rb$}) { "spec" }
- watch("app/controllers/application_controller.rb") { "spec/requests" }
+ watch(%r{^spec/support/.+\.rb$}) { "spec" }
+ watch("app/controllers/application_controller.rb") { "spec/requests" }
- watch(%r{app/controllers/(.+).rb}) { |m| "spec/requests/#{m[1]}_spec.rb" }
+ watch(%r{app/controllers/(.+).rb}) { |m| "spec/requests/#{m[1]}_spec.rb" }
- watch(%r{^app/views/(.+)/.+\.(erb|haml)$}) { |m| "spec/requests/#{m[1]}_spec.rb" }
+ watch(%r{^app/views/(.+)/.+\.(erb|haml)$}) { |m| "spec/requests/#{m[1]}_spec.rb" }
- watch(%r{^spec/fabricators/.+_fabricator\.rb$}) { "spec" }
+ watch(%r{^spec/fabricators/.+_fabricator\.rb$}) { "spec" }
- watch(%r{^app/assets/javascripts/pretty-text/.*\.js\.es6$}) { "spec/components/pretty_text_spec.rb" }
+ watch(%r{^app/assets/javascripts/pretty-text/.*\.js\.es6$}) do
+ "spec/components/pretty_text_spec.rb"
+ end
watch(%r{^plugins/.*/discourse-markdown/.*\.js\.es6$}) { "spec/components/pretty_text_spec.rb" }
watch(%r{^plugins/.*/spec/.*\.rb})
- watch(%r{^(plugins/.*/)plugin\.rb}) { |m| "#{m[1]}spec" }
- watch(%r{^(plugins/.*)/(lib|app)}) { |m| "#{m[1]}/spec/integration" }
+ watch(%r{^(plugins/.*/)plugin\.rb}) { |m| "#{m[1]}spec" }
+ watch(%r{^(plugins/.*)/(lib|app)}) { |m| "#{m[1]}/spec/integration" }
watch(%r{^(plugins/.*)/lib/(.*)\.rb}) { |m| "#{m[1]}/spec/lib/#{m[2]}_spec.rb" }
RELOADERS = Set.new
@@ -50,11 +50,9 @@ module Autospec
def failed_specs
specs = []
- path = './tmp/rspec_result'
+ path = "./tmp/rspec_result"
specs = File.readlines(path) if File.exist?(path)
specs
end
-
end
-
end
diff --git a/lib/autospec/simple_runner.rb b/lib/autospec/simple_runner.rb
index 62fcbc21a0a..dcf88e44434 100644
--- a/lib/autospec/simple_runner.rb
+++ b/lib/autospec/simple_runner.rb
@@ -3,7 +3,6 @@
require "autospec/rspec_runner"
module Autospec
-
class SimpleRunner < RspecRunner
def initialize
@mutex = Mutex.new
@@ -12,36 +11,29 @@ module Autospec
def run(specs)
puts "Running Rspec: #{specs}"
# kill previous rspec instance
- @mutex.synchronize do
- self.abort
- end
+ @mutex.synchronize { self.abort }
# we use our custom rspec formatter
- args = [
- "-r", "#{File.dirname(__FILE__)}/formatter.rb",
- "-f", "Autospec::Formatter"
- ]
+ args = ["-r", "#{File.dirname(__FILE__)}/formatter.rb", "-f", "Autospec::Formatter"]
- command = begin
- line_specified = specs.split.any? { |s| s =~ /\:/ } # Parallel spec can't run specific line
- multiple_files = specs.split.count > 1 || specs == "spec" # Only parallelize multiple files
- if ENV["PARALLEL_SPEC"] == '1' && multiple_files && !line_specified
- "bin/turbo_rspec #{args.join(" ")} #{specs.split.join(" ")}"
- else
- "bin/rspec #{args.join(" ")} #{specs.split.join(" ")}"
+ command =
+ begin
+ line_specified = specs.split.any? { |s| s =~ /\:/ } # Parallel spec can't run specific line
+ multiple_files = specs.split.count > 1 || specs == "spec" # Only parallelize multiple files
+ if ENV["PARALLEL_SPEC"] == "1" && multiple_files && !line_specified
+ "bin/turbo_rspec #{args.join(" ")} #{specs.split.join(" ")}"
+ else
+ "bin/rspec #{args.join(" ")} #{specs.split.join(" ")}"
+ end
end
- end
# launch rspec
Dir.chdir(Rails.root) do # rubocop:disable Discourse/NoChdir because this is not part of the app
env = { "RAILS_ENV" => "test" }
- if specs.split(' ').any? { |s| s =~ /^(.\/)?plugins/ }
+ if specs.split(" ").any? { |s| s =~ %r{^(./)?plugins} }
env["LOAD_PLUGINS"] = "1"
puts "Loading plugins while running specs"
end
- pid =
- @mutex.synchronize do
- @pid = Process.spawn(env, command)
- end
+ pid = @mutex.synchronize { @pid = Process.spawn(env, command) }
_, status = Process.wait2(pid)
@@ -51,7 +43,11 @@ module Autospec
def abort
if pid = @pid
- Process.kill("TERM", pid) rescue nil
+ begin
+ Process.kill("TERM", pid)
+ rescue StandardError
+ nil
+ end
wait_for_done(pid)
pid = nil
end
@@ -66,16 +62,26 @@ module Autospec
def wait_for_done(pid)
i = 3000
- while (i > 0 && Process.getpgid(pid) rescue nil)
+ while (
+ begin
+ i > 0 && Process.getpgid(pid)
+ rescue StandardError
+ nil
+ end
+ )
sleep 0.001
i -= 1
end
- if (Process.getpgid(pid) rescue nil)
+ if (
+ begin
+ Process.getpgid(pid)
+ rescue StandardError
+ nil
+ end
+ )
STDERR.puts "Terminating rspec #{pid} by force cause it refused graceful termination"
Process.kill("KILL", pid)
end
end
-
end
-
end
diff --git a/lib/backup_restore.rb b/lib/backup_restore.rb
index 291567a6f0a..b8c7fa77843 100644
--- a/lib/backup_restore.rb
+++ b/lib/backup_restore.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
module BackupRestore
-
- class OperationRunningError < RuntimeError; end
+ class OperationRunningError < RuntimeError
+ end
VERSION_PREFIX = "v"
DUMP_FILE = "dump.sql.gz"
@@ -22,9 +22,7 @@ module BackupRestore
def self.rollback!
raise BackupRestore::OperationRunningError if BackupRestore.is_operation_running?
- if can_rollback?
- move_tables_between_schemas("backup", "public")
- end
+ move_tables_between_schemas("backup", "public") if can_rollback?
end
def self.cancel!
@@ -58,7 +56,7 @@ module BackupRestore
{
is_operation_running: is_operation_running?,
can_rollback: can_rollback?,
- allow_restore: Rails.env.development? || SiteSetting.allow_restore
+ allow_restore: Rails.env.development? || SiteSetting.allow_restore,
}
end
@@ -133,7 +131,7 @@ module BackupRestore
config["backup_port"] || config["port"],
config["username"] || username || ENV["USER"] || "postgres",
config["password"] || password,
- config["database"]
+ config["database"],
)
end
@@ -194,7 +192,11 @@ module BackupRestore
end
def self.backup_tables_count
- DB.query_single("SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = 'backup'").first.to_i
+ DB
+ .query_single(
+ "SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = 'backup'",
+ )
+ .first
+ .to_i
end
-
end
diff --git a/lib/backup_restore/backup_file_handler.rb b/lib/backup_restore/backup_file_handler.rb
index 483d6f6473a..645fad9f64d 100644
--- a/lib/backup_restore/backup_file_handler.rb
+++ b/lib/backup_restore/backup_file_handler.rb
@@ -69,15 +69,22 @@ module BackupRestore
path_transformation =
case tar_implementation
when :gnu
- ['--transform', 's|var/www/discourse/public/uploads/|uploads/|']
+ %w[--transform s|var/www/discourse/public/uploads/|uploads/|]
when :bsd
- ['-s', '|var/www/discourse/public/uploads/|uploads/|']
+ %w[-s |var/www/discourse/public/uploads/|uploads/|]
end
log "Unzipping archive, this may take a while..."
Discourse::Utils.execute_command(
- 'tar', '--extract', '--gzip', '--file', @archive_path, '--directory', @tmp_directory,
- *path_transformation, failure_message: "Failed to decompress archive."
+ "tar",
+ "--extract",
+ "--gzip",
+ "--file",
+ @archive_path,
+ "--directory",
+ @tmp_directory,
+ *path_transformation,
+ failure_message: "Failed to decompress archive.",
)
end
@@ -86,15 +93,19 @@ module BackupRestore
if @is_archive
# for compatibility with backups from Discourse v1.5 and below
old_dump_path = File.join(@tmp_directory, OLD_DUMP_FILENAME)
- File.exist?(old_dump_path) ? old_dump_path : File.join(@tmp_directory, BackupRestore::DUMP_FILE)
+ if File.exist?(old_dump_path)
+ old_dump_path
+ else
+ File.join(@tmp_directory, BackupRestore::DUMP_FILE)
+ end
else
File.join(@tmp_directory, @filename)
end
- if File.extname(@db_dump_path) == '.gz'
+ if File.extname(@db_dump_path) == ".gz"
log "Extracting dump file..."
Compression::Gzip.new.decompress(@tmp_directory, @db_dump_path, available_size)
- @db_dump_path.delete_suffix!('.gz')
+ @db_dump_path.delete_suffix!(".gz")
end
@db_dump_path
@@ -105,17 +116,18 @@ module BackupRestore
end
def tar_implementation
- @tar_version ||= begin
- tar_version = Discourse::Utils.execute_command('tar', '--version')
-
- if tar_version.include?("GNU tar")
- :gnu
- elsif tar_version.include?("bsdtar")
- :bsd
- else
- raise "Unknown tar implementation: #{tar_version}"
+ @tar_version ||=
+ begin
+ tar_version = Discourse::Utils.execute_command("tar", "--version")
+
+ if tar_version.include?("GNU tar")
+ :gnu
+ elsif tar_version.include?("bsdtar")
+ :bsd
+ else
+ raise "Unknown tar implementation: #{tar_version}"
+ end
end
- end
end
end
end
diff --git a/lib/backup_restore/backup_store.rb b/lib/backup_restore/backup_store.rb
index 65a3acaa951..5afcec27bfc 100644
--- a/lib/backup_restore/backup_store.rb
+++ b/lib/backup_restore/backup_store.rb
@@ -37,9 +37,7 @@ module BackupRestore
return unless cleanup_allowed?
return if (backup_files = files).size <= SiteSetting.maximum_backups
- backup_files[SiteSetting.maximum_backups..-1].each do |file|
- delete_file(file.filename)
- end
+ backup_files[SiteSetting.maximum_backups..-1].each { |file| delete_file(file.filename) }
reset_cache
end
@@ -74,7 +72,7 @@ module BackupRestore
used_bytes: used_bytes,
free_bytes: free_bytes,
count: files.size,
- last_backup_taken_at: latest_file&.last_modified
+ last_backup_taken_at: latest_file&.last_modified,
}
end
diff --git a/lib/backup_restore/backuper.rb b/lib/backup_restore/backuper.rb
index 83c10911b39..2483f5bb7b9 100644
--- a/lib/backup_restore/backuper.rb
+++ b/lib/backup_restore/backuper.rb
@@ -4,7 +4,6 @@ require "mini_mime"
require "file_store/s3_store"
module BackupRestore
-
class Backuper
attr_reader :success
@@ -84,7 +83,11 @@ module BackupRestore
@dump_filename = File.join(@tmp_directory, BackupRestore::DUMP_FILE)
@archive_directory = BackupRestore::LocalBackupStore.base_directory(db: @current_db)
filename = @filename_override || "#{get_parameterized_title}-#{@timestamp}"
- @archive_basename = File.join(@archive_directory, "#{filename}-#{BackupRestore::VERSION_PREFIX}#{BackupRestore.current_version}")
+ @archive_basename =
+ File.join(
+ @archive_directory,
+ "#{filename}-#{BackupRestore::VERSION_PREFIX}#{BackupRestore.current_version}",
+ )
@backup_filename =
if @with_uploads
@@ -119,9 +122,18 @@ module BackupRestore
BackupMetadata.delete_all
BackupMetadata.create!(name: "base_url", value: Discourse.base_url)
BackupMetadata.create!(name: "cdn_url", value: Discourse.asset_host)
- BackupMetadata.create!(name: "s3_base_url", value: SiteSetting.Upload.enable_s3_uploads ? SiteSetting.Upload.s3_base_url : nil)
- BackupMetadata.create!(name: "s3_cdn_url", value: SiteSetting.Upload.enable_s3_uploads ? SiteSetting.Upload.s3_cdn_url : nil)
- BackupMetadata.create!(name: "db_name", value: RailsMultisite::ConnectionManagement.current_db)
+ BackupMetadata.create!(
+ name: "s3_base_url",
+ value: SiteSetting.Upload.enable_s3_uploads ? SiteSetting.Upload.s3_base_url : nil,
+ )
+ BackupMetadata.create!(
+ name: "s3_cdn_url",
+ value: SiteSetting.Upload.enable_s3_uploads ? SiteSetting.Upload.s3_cdn_url : nil,
+ )
+ BackupMetadata.create!(
+ name: "db_name",
+ value: RailsMultisite::ConnectionManagement.current_db,
+ )
BackupMetadata.create!(name: "multisite", value: Rails.configuration.multisite)
end
@@ -132,7 +144,7 @@ module BackupRestore
pg_dump_running = true
Thread.new do
- RailsMultisite::ConnectionManagement::establish_connection(db: @current_db)
+ RailsMultisite::ConnectionManagement.establish_connection(db: @current_db)
while pg_dump_running
message = logs.pop.strip
log(message) unless message.blank?
@@ -159,23 +171,24 @@ module BackupRestore
db_conf = BackupRestore.database_configuration
password_argument = "PGPASSWORD='#{db_conf.password}'" if db_conf.password.present?
- host_argument = "--host=#{db_conf.host}" if db_conf.host.present?
- port_argument = "--port=#{db_conf.port}" if db_conf.port.present?
+ host_argument = "--host=#{db_conf.host}" if db_conf.host.present?
+ port_argument = "--port=#{db_conf.port}" if db_conf.port.present?
username_argument = "--username=#{db_conf.username}" if db_conf.username.present?
- [ password_argument, # pass the password to pg_dump (if any)
- "pg_dump", # the pg_dump command
- "--schema=public", # only public schema
- "-T public.pg_*", # exclude tables and views whose name starts with "pg_"
+ [
+ password_argument, # pass the password to pg_dump (if any)
+ "pg_dump", # the pg_dump command
+ "--schema=public", # only public schema
+ "-T public.pg_*", # exclude tables and views whose name starts with "pg_"
"--file='#{@dump_filename}'", # output to the dump.sql file
- "--no-owner", # do not output commands to set ownership of objects
- "--no-privileges", # prevent dumping of access privileges
- "--verbose", # specifies verbose mode
- "--compress=4", # Compression level of 4
- host_argument, # the hostname to connect to (if any)
- port_argument, # the port to connect to (if any)
- username_argument, # the username to connect as (if any)
- db_conf.database # the name of the database to dump
+ "--no-owner", # do not output commands to set ownership of objects
+ "--no-privileges", # prevent dumping of access privileges
+ "--verbose", # specifies verbose mode
+ "--compress=4", # Compression level of 4
+ host_argument, # the hostname to connect to (if any)
+ port_argument, # the port to connect to (if any)
+ username_argument, # the username to connect as (if any)
+ db_conf.database, # the name of the database to dump
].join(" ")
end
@@ -185,8 +198,10 @@ module BackupRestore
archive_filename = File.join(@archive_directory, @backup_filename)
Discourse::Utils.execute_command(
- 'mv', @dump_filename, archive_filename,
- failure_message: "Failed to move database dump file."
+ "mv",
+ @dump_filename,
+ archive_filename,
+ failure_message: "Failed to move database dump file.",
)
remove_tmp_directory
@@ -198,17 +213,29 @@ module BackupRestore
tar_filename = "#{@archive_basename}.tar"
log "Making sure archive does not already exist..."
- Discourse::Utils.execute_command('rm', '-f', tar_filename)
- Discourse::Utils.execute_command('rm', '-f', "#{tar_filename}.gz")
+ Discourse::Utils.execute_command("rm", "-f", tar_filename)
+ Discourse::Utils.execute_command("rm", "-f", "#{tar_filename}.gz")
log "Creating empty archive..."
- Discourse::Utils.execute_command('tar', '--create', '--file', tar_filename, '--files-from', '/dev/null')
+ Discourse::Utils.execute_command(
+ "tar",
+ "--create",
+ "--file",
+ tar_filename,
+ "--files-from",
+ "/dev/null",
+ )
log "Archiving data dump..."
Discourse::Utils.execute_command(
- 'tar', '--append', '--dereference', '--file', tar_filename, File.basename(@dump_filename),
+ "tar",
+ "--append",
+ "--dereference",
+ "--file",
+ tar_filename,
+ File.basename(@dump_filename),
failure_message: "Failed to archive data dump.",
- chdir: File.dirname(@dump_filename)
+ chdir: File.dirname(@dump_filename),
)
add_local_uploads_to_archive(tar_filename)
@@ -218,8 +245,10 @@ module BackupRestore
log "Gzipping archive, this may take a while..."
Discourse::Utils.execute_command(
- 'gzip', "-#{SiteSetting.backup_gzip_compression_level_for_uploads}", tar_filename,
- failure_message: "Failed to gzip archive."
+ "gzip",
+ "-#{SiteSetting.backup_gzip_compression_level_for_uploads}",
+ tar_filename,
+ failure_message: "Failed to gzip archive.",
)
end
@@ -244,14 +273,21 @@ module BackupRestore
if SiteSetting.include_thumbnails_in_backups
exclude_optimized = ""
else
- optimized_path = File.join(upload_directory, 'optimized')
+ optimized_path = File.join(upload_directory, "optimized")
exclude_optimized = "--exclude=#{optimized_path}"
end
Discourse::Utils.execute_command(
- 'tar', '--append', '--dereference', exclude_optimized, '--file', tar_filename, upload_directory,
- failure_message: "Failed to archive uploads.", success_status_codes: [0, 1],
- chdir: File.join(Rails.root, "public")
+ "tar",
+ "--append",
+ "--dereference",
+ exclude_optimized,
+ "--file",
+ tar_filename,
+ upload_directory,
+ failure_message: "Failed to archive uploads.",
+ success_status_codes: [0, 1],
+ chdir: File.join(Rails.root, "public"),
)
else
log "No local uploads found. Skipping archiving of local uploads..."
@@ -287,9 +323,14 @@ module BackupRestore
log "Appending uploads to archive..."
Discourse::Utils.execute_command(
- 'tar', '--append', '--file', tar_filename, upload_directory,
- failure_message: "Failed to append uploads to archive.", success_status_codes: [0, 1],
- chdir: @tmp_directory
+ "tar",
+ "--append",
+ "--file",
+ tar_filename,
+ upload_directory,
+ failure_message: "Failed to append uploads to archive.",
+ success_status_codes: [0, 1],
+ chdir: @tmp_directory,
)
log "No uploads found on S3. Skipping archiving of uploads stored on S3..." if count == 0
@@ -327,9 +368,7 @@ module BackupRestore
logs = Discourse::Utils.logs_markdown(@logs, user: @user)
post = SystemMessage.create_from_system_user(@user, status, logs: logs)
- if @user.id == Discourse::SYSTEM_USER_ID
- post.topic.invite_group(@user, Group[:admins])
- end
+ post.topic.invite_group(@user, Group[:admins]) if @user.id == Discourse::SYSTEM_USER_ID
rescue => ex
log "Something went wrong while notifying user.", ex
end
@@ -399,7 +438,12 @@ module BackupRestore
def publish_log(message, timestamp)
return unless @publish_to_message_bus
data = { timestamp: timestamp, operation: "backup", message: message }
- MessageBus.publish(BackupRestore::LOGS_CHANNEL, data, user_ids: [@user_id], client_ids: [@client_id])
+ MessageBus.publish(
+ BackupRestore::LOGS_CHANNEL,
+ data,
+ user_ids: [@user_id],
+ client_ids: [@client_id],
+ )
end
def save_log(message, timestamp)
@@ -416,5 +460,4 @@ module BackupRestore
end
end
end
-
end
diff --git a/lib/backup_restore/database_restorer.rb b/lib/backup_restore/database_restorer.rb
index ae3ac7deaa4..2a3bc6985c7 100644
--- a/lib/backup_restore/database_restorer.rb
+++ b/lib/backup_restore/database_restorer.rb
@@ -46,9 +46,7 @@ module BackupRestore
end
def self.drop_backup_schema
- if backup_schema_dropable?
- ActiveRecord::Base.connection.drop_schema(BACKUP_SCHEMA)
- end
+ ActiveRecord::Base.connection.drop_schema(BACKUP_SCHEMA) if backup_schema_dropable?
end
def self.core_migration_files
@@ -65,13 +63,14 @@ module BackupRestore
last_line = nil
psql_running = true
- log_thread = Thread.new do
- RailsMultisite::ConnectionManagement::establish_connection(db: @current_db)
- while psql_running || !logs.empty?
- message = logs.pop.strip
- log(message) if message.present?
+ log_thread =
+ Thread.new do
+ RailsMultisite::ConnectionManagement.establish_connection(db: @current_db)
+ while psql_running || !logs.empty?
+ message = logs.pop.strip
+ log(message) if message.present?
+ end
end
- end
IO.popen(restore_dump_command) do |pipe|
begin
@@ -89,7 +88,9 @@ module BackupRestore
logs << ""
log_thread.join
- raise DatabaseRestoreError.new("psql failed: #{last_line}") if Process.last_status&.exitstatus != 0
+ if Process.last_status&.exitstatus != 0
+ raise DatabaseRestoreError.new("psql failed: #{last_line}")
+ end
end
# Removes unwanted SQL added by certain versions of pg_dump and modifies
@@ -99,7 +100,7 @@ module BackupRestore
"DROP SCHEMA", # Discourse <= v1.5
"CREATE SCHEMA", # PostgreSQL 11+
"COMMENT ON SCHEMA", # PostgreSQL 11+
- "SET default_table_access_method" # PostgreSQL 12
+ "SET default_table_access_method", # PostgreSQL 12
].join("|")
command = "sed -E '/^(#{unwanted_sql})/d' #{@db_dump_path}"
@@ -117,18 +118,19 @@ module BackupRestore
db_conf = BackupRestore.database_configuration
password_argument = "PGPASSWORD='#{db_conf.password}'" if db_conf.password.present?
- host_argument = "--host=#{db_conf.host}" if db_conf.host.present?
- port_argument = "--port=#{db_conf.port}" if db_conf.port.present?
- username_argument = "--username=#{db_conf.username}" if db_conf.username.present?
+ host_argument = "--host=#{db_conf.host}" if db_conf.host.present?
+ port_argument = "--port=#{db_conf.port}" if db_conf.port.present?
+ username_argument = "--username=#{db_conf.username}" if db_conf.username.present?
- [ password_argument, # pass the password to psql (if any)
- "psql", # the psql command
+ [
+ password_argument, # pass the password to psql (if any)
+ "psql", # the psql command
"--dbname='#{db_conf.database}'", # connect to database *dbname*
- "--single-transaction", # all or nothing (also runs COPY commands faster)
- "--variable=ON_ERROR_STOP=1", # stop on first error
- host_argument, # the hostname to connect to (if any)
- port_argument, # the port to connect to (if any)
- username_argument # the username to connect as (if any)
+ "--single-transaction", # all or nothing (also runs COPY commands faster)
+ "--variable=ON_ERROR_STOP=1", # stop on first error
+ host_argument, # the hostname to connect to (if any)
+ port_argument, # the port to connect to (if any)
+ username_argument, # the username to connect as (if any)
].compact.join(" ")
end
@@ -136,21 +138,22 @@ module BackupRestore
log "Migrating the database..."
log Discourse::Utils.execute_command(
- {
- "SKIP_POST_DEPLOYMENT_MIGRATIONS" => "0",
- "SKIP_OPTIMIZE_ICONS" => "1",
- "DISABLE_TRANSLATION_OVERRIDES" => "1"
- },
- "rake", "db:migrate",
- failure_message: "Failed to migrate database.",
- chdir: Rails.root
- )
+ {
+ "SKIP_POST_DEPLOYMENT_MIGRATIONS" => "0",
+ "SKIP_OPTIMIZE_ICONS" => "1",
+ "DISABLE_TRANSLATION_OVERRIDES" => "1",
+ },
+ "rake",
+ "db:migrate",
+ failure_message: "Failed to migrate database.",
+ chdir: Rails.root,
+ )
end
def reconnect_database
log "Reconnecting to the database..."
- RailsMultisite::ConnectionManagement::reload if RailsMultisite::ConnectionManagement::instance
- RailsMultisite::ConnectionManagement::establish_connection(db: @current_db)
+ RailsMultisite::ConnectionManagement.reload if RailsMultisite::ConnectionManagement.instance
+ RailsMultisite::ConnectionManagement.establish_connection(db: @current_db)
end
def create_missing_discourse_functions
@@ -179,10 +182,12 @@ module BackupRestore
end
end
- existing_function_names = Migration::BaseDropper.existing_discourse_function_names.map { |name| "#{name}()" }
+ existing_function_names =
+ Migration::BaseDropper.existing_discourse_function_names.map { |name| "#{name}()" }
all_readonly_table_columns.each do |table_name, column_name|
- function_name = Migration::BaseDropper.readonly_function_name(table_name, column_name, with_schema: false)
+ function_name =
+ Migration::BaseDropper.readonly_function_name(table_name, column_name, with_schema: false)
if !existing_function_names.include?(function_name)
Migration::BaseDropper.create_readonly_function(table_name, column_name)
diff --git a/lib/backup_restore/local_backup_store.rb b/lib/backup_restore/local_backup_store.rb
index fd7f16b9f63..77ccfcce097 100644
--- a/lib/backup_restore/local_backup_store.rb
+++ b/lib/backup_restore/local_backup_store.rb
@@ -12,7 +12,12 @@ module BackupRestore
end
def self.chunk_path(identifier, filename, chunk_number)
- File.join(LocalBackupStore.base_directory, "tmp", identifier, "#{filename}.part#{chunk_number}")
+ File.join(
+ LocalBackupStore.base_directory,
+ "tmp",
+ identifier,
+ "#{filename}.part#{chunk_number}",
+ )
end
def initialize(opts = {})
@@ -39,7 +44,7 @@ module BackupRestore
def download_file(filename, destination, failure_message = "")
path = path_from_filename(filename)
- Discourse::Utils.execute_command('cp', path, destination, failure_message: failure_message)
+ Discourse::Utils.execute_command("cp", path, destination, failure_message: failure_message)
end
private
@@ -59,7 +64,7 @@ module BackupRestore
filename: File.basename(path),
size: File.size(path),
last_modified: File.mtime(path).utc,
- source: include_download_source ? path : nil
+ source: include_download_source ? path : nil,
)
end
diff --git a/lib/backup_restore/logger.rb b/lib/backup_restore/logger.rb
index fe777d389bc..f9c0eab642e 100644
--- a/lib/backup_restore/logger.rb
+++ b/lib/backup_restore/logger.rb
@@ -32,7 +32,12 @@ module BackupRestore
def publish_log(message, timestamp)
return unless @publish_to_message_bus
data = { timestamp: timestamp, operation: "restore", message: message }
- MessageBus.publish(BackupRestore::LOGS_CHANNEL, data, user_ids: [@user_id], client_ids: [@client_id])
+ MessageBus.publish(
+ BackupRestore::LOGS_CHANNEL,
+ data,
+ user_ids: [@user_id],
+ client_ids: [@client_id],
+ )
end
def save_log(message, timestamp)
diff --git a/lib/backup_restore/meta_data_handler.rb b/lib/backup_restore/meta_data_handler.rb
index 02bc0e98bf0..0996d8866bc 100644
--- a/lib/backup_restore/meta_data_handler.rb
+++ b/lib/backup_restore/meta_data_handler.rb
@@ -28,8 +28,10 @@ module BackupRestore
log " Restored version: #{metadata[:version]}"
if metadata[:version] > @current_version
- raise MigrationRequiredError.new("You're trying to restore a more recent version of the schema. " \
- "You should migrate first!")
+ raise MigrationRequiredError.new(
+ "You're trying to restore a more recent version of the schema. " \
+ "You should migrate first!",
+ )
end
metadata
diff --git a/lib/backup_restore/restorer.rb b/lib/backup_restore/restorer.rb
index 00bedab2410..8caf5dafecd 100644
--- a/lib/backup_restore/restorer.rb
+++ b/lib/backup_restore/restorer.rb
@@ -65,8 +65,8 @@ module BackupRestore
after_restore_hook
rescue Compression::Strategy::ExtractFailed
- log 'ERROR: The uncompressed file is too big. Consider increasing the hidden ' \
- '"decompressed_backup_max_file_size_mb" setting.'
+ log "ERROR: The uncompressed file is too big. Consider increasing the hidden " \
+ '"decompressed_backup_max_file_size_mb" setting.'
@database_restorer.rollback
rescue SystemExit
log "Restore process was cancelled!"
@@ -118,10 +118,10 @@ module BackupRestore
DiscourseEvent.trigger(:site_settings_restored)
- if @disable_emails && SiteSetting.disable_emails == 'no'
+ if @disable_emails && SiteSetting.disable_emails == "no"
log "Disabling outgoing emails for non-staff users..."
user = User.find_by_email(@user_info[:email]) || Discourse.system_user
- SiteSetting.set_and_log(:disable_emails, 'non-staff', user)
+ SiteSetting.set_and_log(:disable_emails, "non-staff", user)
end
end
@@ -152,7 +152,7 @@ module BackupRestore
post = SystemMessage.create_from_system_user(user, status, logs: logs)
else
log "Could not send notification to '#{@user_info[:username]}' " \
- "(#{@user_info[:email]}), because the user does not exist."
+ "(#{@user_info[:email]}), because the user does not exist."
end
rescue => ex
log "Something went wrong while notifying user.", ex
diff --git a/lib/backup_restore/s3_backup_store.rb b/lib/backup_restore/s3_backup_store.rb
index 591eb2ed067..10e2798642a 100644
--- a/lib/backup_restore/s3_backup_store.rb
+++ b/lib/backup_restore/s3_backup_store.rb
@@ -4,8 +4,11 @@ module BackupRestore
class S3BackupStore < BackupStore
UPLOAD_URL_EXPIRES_AFTER_SECONDS ||= 6.hours.to_i
- delegate :abort_multipart, :presign_multipart_part, :list_multipart_parts,
- :complete_multipart, to: :s3_helper
+ delegate :abort_multipart,
+ :presign_multipart_part,
+ :list_multipart_parts,
+ :complete_multipart,
+ to: :s3_helper
def initialize(opts = {})
@s3_options = S3Helper.s3_options(SiteSetting)
@@ -13,7 +16,7 @@ module BackupRestore
end
def s3_helper
- @s3_helper ||= S3Helper.new(s3_bucket_name_with_prefix, '', @s3_options.clone)
+ @s3_helper ||= S3Helper.new(s3_bucket_name_with_prefix, "", @s3_options.clone)
end
def remote?
@@ -57,11 +60,17 @@ module BackupRestore
presigned_url(obj, :put, UPLOAD_URL_EXPIRES_AFTER_SECONDS)
rescue Aws::Errors::ServiceError => e
- Rails.logger.warn("Failed to generate upload URL for S3: #{e.message.presence || e.class.name}")
+ Rails.logger.warn(
+ "Failed to generate upload URL for S3: #{e.message.presence || e.class.name}",
+ )
raise StorageError.new(e.message.presence || e.class.name)
end
- def signed_url_for_temporary_upload(file_name, expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS, metadata: {})
+ def signed_url_for_temporary_upload(
+ file_name,
+ expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS,
+ metadata: {}
+ )
obj = object_from_path(file_name)
raise BackupFileExists.new if obj.exists?
key = temporary_upload_path(file_name)
@@ -71,8 +80,8 @@ module BackupRestore
expires_in: expires_in,
opts: {
metadata: metadata,
- acl: "private"
- }
+ acl: "private",
+ },
)
end
@@ -84,7 +93,7 @@ module BackupRestore
folder_prefix = s3_helper.s3_bucket_folder_path.nil? ? "" : s3_helper.s3_bucket_folder_path
if Rails.env.test?
- folder_prefix = File.join(folder_prefix, "test_#{ENV['TEST_ENV_NUMBER'].presence || '0'}")
+ folder_prefix = File.join(folder_prefix, "test_#{ENV["TEST_ENV_NUMBER"].presence || "0"}")
end
folder_prefix
@@ -105,7 +114,10 @@ module BackupRestore
s3_helper.copy(
existing_external_upload_key,
File.join(s3_helper.s3_bucket_folder_path, original_filename),
- options: { acl: "private", apply_metadata_to_destination: true }
+ options: {
+ acl: "private",
+ apply_metadata_to_destination: true,
+ },
)
s3_helper.delete_object(existing_external_upload_key)
end
@@ -120,9 +132,7 @@ module BackupRestore
objects = []
s3_helper.list.each do |obj|
- if obj.key.match?(file_regex)
- objects << create_file_from_object(obj)
- end
+ objects << create_file_from_object(obj) if obj.key.match?(file_regex)
end
objects
@@ -137,7 +147,7 @@ module BackupRestore
filename: File.basename(obj.key),
size: obj.size,
last_modified: obj.last_modified,
- source: include_download_source ? presigned_url(obj, :get, expires) : nil
+ source: include_download_source ? presigned_url(obj, :get, expires) : nil,
)
end
@@ -154,16 +164,17 @@ module BackupRestore
end
def file_regex
- @file_regex ||= begin
- path = s3_helper.s3_bucket_folder_path || ""
+ @file_regex ||=
+ begin
+ path = s3_helper.s3_bucket_folder_path || ""
- if path.present?
- path = "#{path}/" unless path.end_with?("/")
- path = Regexp.quote(path)
- end
+ if path.present?
+ path = "#{path}/" unless path.end_with?("/")
+ path = Regexp.quote(path)
+ end
- /^#{path}[^\/]*\.t?gz$/i
- end
+ %r{^#{path}[^/]*\.t?gz$}i
+ end
end
def free_bytes
diff --git a/lib/backup_restore/system_interface.rb b/lib/backup_restore/system_interface.rb
index c0d209e5380..31bd4eb944e 100644
--- a/lib/backup_restore/system_interface.rb
+++ b/lib/backup_restore/system_interface.rb
@@ -98,9 +98,7 @@ module BackupRestore
def flush_redis
redis = Discourse.redis
- redis.scan_each(match: "*") do |key|
- redis.del(key) unless key == SidekiqPauser::PAUSED_KEY
- end
+ redis.scan_each(match: "*") { |key| redis.del(key) unless key == SidekiqPauser::PAUSED_KEY }
end
def clear_sidekiq_queues
diff --git a/lib/backup_restore/uploads_restorer.rb b/lib/backup_restore/uploads_restorer.rb
index 7409c38f56c..8b6c13e17d1 100644
--- a/lib/backup_restore/uploads_restorer.rb
+++ b/lib/backup_restore/uploads_restorer.rb
@@ -11,11 +11,12 @@ module BackupRestore
def self.s3_regex_string(s3_base_url)
clean_url = s3_base_url.sub(S3_ENDPOINT_REGEX, ".s3.amazonaws.com")
- regex_string = clean_url
- .split(".s3.amazonaws.com")
- .map { |s| Regexp.escape(s) }
- .insert(1, S3_ENDPOINT_REGEX.source)
- .join("")
+ regex_string =
+ clean_url
+ .split(".s3.amazonaws.com")
+ .map { |s| Regexp.escape(s) }
+ .insert(1, S3_ENDPOINT_REGEX.source)
+ .join("")
[regex_string, clean_url]
end
@@ -25,12 +26,16 @@ module BackupRestore
end
def restore(tmp_directory)
- upload_directories = Dir.glob(File.join(tmp_directory, "uploads", "*"))
- .reject { |path| File.basename(path).start_with?("PaxHeaders") }
+ upload_directories =
+ Dir
+ .glob(File.join(tmp_directory, "uploads", "*"))
+ .reject { |path| File.basename(path).start_with?("PaxHeaders") }
if upload_directories.count > 1
- raise UploadsRestoreError.new("Could not find uploads, because the uploads " \
- "directory contains multiple folders.")
+ raise UploadsRestoreError.new(
+ "Could not find uploads, because the uploads " \
+ "directory contains multiple folders.",
+ )
end
@tmp_uploads_path = upload_directories.first
@@ -55,7 +60,9 @@ module BackupRestore
if !store.respond_to?(:copy_from)
# a FileStore implementation from a plugin might not support this method, so raise a helpful error
store_name = Discourse.store.class.name
- raise UploadsRestoreError.new("The current file store (#{store_name}) does not support restoring uploads.")
+ raise UploadsRestoreError.new(
+ "The current file store (#{store_name}) does not support restoring uploads.",
+ )
end
log "Restoring uploads, this may take a while..."
@@ -89,13 +96,17 @@ module BackupRestore
remap(old_base_url, Discourse.base_url)
end
- current_s3_base_url = SiteSetting::Upload.enable_s3_uploads ? SiteSetting::Upload.s3_base_url : nil
- if (old_s3_base_url = BackupMetadata.value_for("s3_base_url")) && old_s3_base_url != current_s3_base_url
+ current_s3_base_url =
+ SiteSetting::Upload.enable_s3_uploads ? SiteSetting::Upload.s3_base_url : nil
+ if (old_s3_base_url = BackupMetadata.value_for("s3_base_url")) &&
+ old_s3_base_url != current_s3_base_url
remap_s3("#{old_s3_base_url}/", uploads_folder)
end
- current_s3_cdn_url = SiteSetting::Upload.enable_s3_uploads ? SiteSetting::Upload.s3_cdn_url : nil
- if (old_s3_cdn_url = BackupMetadata.value_for("s3_cdn_url")) && old_s3_cdn_url != current_s3_cdn_url
+ current_s3_cdn_url =
+ SiteSetting::Upload.enable_s3_uploads ? SiteSetting::Upload.s3_cdn_url : nil
+ if (old_s3_cdn_url = BackupMetadata.value_for("s3_cdn_url")) &&
+ old_s3_cdn_url != current_s3_cdn_url
base_url = current_s3_cdn_url || Discourse.base_url
remap("#{old_s3_cdn_url}/", UrlHelper.schemaless("#{base_url}#{uploads_folder}"))
@@ -113,10 +124,7 @@ module BackupRestore
remap(old_host, new_host) if old_host != new_host
end
- if @previous_db_name != @current_db_name
- remap("/uploads/#{@previous_db_name}/", upload_path)
- end
-
+ remap("/uploads/#{@previous_db_name}/", upload_path) if @previous_db_name != @current_db_name
rescue => ex
log "Something went wrong while remapping uploads.", ex
end
@@ -130,7 +138,12 @@ module BackupRestore
if old_s3_base_url.include?("amazonaws.com")
from_regex, from_clean_url = self.class.s3_regex_string(old_s3_base_url)
log "Remapping with regex from '#{from_clean_url}' to '#{uploads_folder}'"
- DbHelper.regexp_replace(from_regex, uploads_folder, verbose: true, excluded_tables: ["backup_metadata"])
+ DbHelper.regexp_replace(
+ from_regex,
+ uploads_folder,
+ verbose: true,
+ excluded_tables: ["backup_metadata"],
+ )
else
remap(old_s3_base_url, uploads_folder)
end
@@ -141,13 +154,15 @@ module BackupRestore
DB.exec("TRUNCATE TABLE optimized_images")
SiteIconManager.ensure_optimized!
- User.where("uploaded_avatar_id IS NOT NULL").find_each do |user|
- Jobs.enqueue(:create_avatar_thumbnails, upload_id: user.uploaded_avatar_id)
- end
+ User
+ .where("uploaded_avatar_id IS NOT NULL")
+ .find_each do |user|
+ Jobs.enqueue(:create_avatar_thumbnails, upload_id: user.uploaded_avatar_id)
+ end
end
def rebake_posts_with_uploads
- log 'Posts will be rebaked by a background job in sidekiq. You will see missing images until that has completed.'
+ log "Posts will be rebaked by a background job in sidekiq. You will see missing images until that has completed."
log 'You can expedite the process by manually running "rake posts:rebake_uncooked_posts"'
DB.exec(<<~SQL)
diff --git a/lib/badge_queries.rb b/lib/badge_queries.rb
index 0f8a4c48329..4eda8098739 100644
--- a/lib/badge_queries.rb
+++ b/lib/badge_queries.rb
@@ -173,7 +173,7 @@ module BadgeQueries
<<~SQL
SELECT p.user_id, p.id post_id, current_timestamp granted_at
FROM badge_posts p
- WHERE #{is_topic ? "p.post_number = 1" : "p.post_number > 1" } AND p.like_count >= #{count.to_i} AND
+ WHERE #{is_topic ? "p.post_number = 1" : "p.post_number > 1"} AND p.like_count >= #{count.to_i} AND
(:backfill OR p.id IN (:post_ids) )
SQL
end
@@ -271,5 +271,4 @@ module BadgeQueries
WHERE "rank" = 1
SQL
end
-
end
diff --git a/lib/bookmark_query.rb b/lib/bookmark_query.rb
index f62ce591fac..3a54a195807 100644
--- a/lib/bookmark_query.rb
+++ b/lib/bookmark_query.rb
@@ -11,9 +11,7 @@ class BookmarkQuery
def self.preload(bookmarks, object)
preload_polymorphic_associations(bookmarks, object.guardian)
- if @preload
- @preload.each { |preload| preload.call(bookmarks, object) }
- end
+ @preload.each { |preload| preload.call(bookmarks, object) } if @preload
end
# These polymorphic associations are loaded to make the UserBookmarkListSerializer's
@@ -42,24 +40,27 @@ class BookmarkQuery
ts_query = search_term.present? ? Search.ts_query(term: search_term) : nil
search_term_wildcard = search_term.present? ? "%#{search_term}%" : nil
- queries = Bookmark.registered_bookmarkables.map do |bookmarkable|
- interim_results = bookmarkable.perform_list_query(@user, @guardian)
+ queries =
+ Bookmark
+ .registered_bookmarkables
+ .map do |bookmarkable|
+ interim_results = bookmarkable.perform_list_query(@user, @guardian)
- # this could occur if there is some security reason that the user cannot
- # access the bookmarkables that they have bookmarked, e.g. if they had 1 bookmark
- # on a topic and that topic was moved into a private category
- next if interim_results.blank?
+ # this could occur if there is some security reason that the user cannot
+ # access the bookmarkables that they have bookmarked, e.g. if they had 1 bookmark
+ # on a topic and that topic was moved into a private category
+ next if interim_results.blank?
- if search_term.present?
- interim_results = bookmarkable.perform_search_query(
- interim_results, search_term_wildcard, ts_query
- )
- end
+ if search_term.present?
+ interim_results =
+ bookmarkable.perform_search_query(interim_results, search_term_wildcard, ts_query)
+ end
- # this is purely to make the query easy to read and debug, otherwise it's
- # all mashed up into a massive ball in MiniProfiler :)
- "---- #{bookmarkable.model.to_s} bookmarkable ---\n\n #{interim_results.to_sql}"
- end.compact
+ # this is purely to make the query easy to read and debug, otherwise it's
+ # all mashed up into a massive ball in MiniProfiler :)
+ "---- #{bookmarkable.model.to_s} bookmarkable ---\n\n #{interim_results.to_sql}"
+ end
+ .compact
# same for interim results being blank, the user might have been locked out
# from all their various bookmarks, in which case they will see nothing and
@@ -68,17 +69,16 @@ class BookmarkQuery
union_sql = queries.join("\n\nUNION\n\n")
results = Bookmark.select("bookmarks.*").from("(\n\n#{union_sql}\n\n) as bookmarks")
- results = results.order(
- "(CASE WHEN bookmarks.pinned THEN 0 ELSE 1 END),
+ results =
+ results.order(
+ "(CASE WHEN bookmarks.pinned THEN 0 ELSE 1 END),
bookmarks.reminder_at ASC,
- bookmarks.updated_at DESC"
- )
+ bookmarks.updated_at DESC",
+ )
@count = results.count
- if @page.positive?
- results = results.offset(@page * @params[:per_page])
- end
+ results = results.offset(@page * @params[:per_page]) if @page.positive?
if updated_results = blk&.call(results)
results = updated_results
diff --git a/lib/bookmark_reminder_notification_handler.rb b/lib/bookmark_reminder_notification_handler.rb
index 13f5b2966e1..247cc4637db 100644
--- a/lib/bookmark_reminder_notification_handler.rb
+++ b/lib/bookmark_reminder_notification_handler.rb
@@ -28,12 +28,10 @@ class BookmarkReminderNotificationHandler
def clear_reminder
Rails.logger.debug(
- "Clearing bookmark reminder for bookmark_id #{bookmark.id}. reminder at: #{bookmark.reminder_at}"
+ "Clearing bookmark reminder for bookmark_id #{bookmark.id}. reminder at: #{bookmark.reminder_at}",
)
- if bookmark.auto_clear_reminder_when_reminder_sent?
- bookmark.reminder_at = nil
- end
+ bookmark.reminder_at = nil if bookmark.auto_clear_reminder_when_reminder_sent?
bookmark.clear_reminder!
end
diff --git a/lib/browser_detection.rb b/lib/browser_detection.rb
index e2f8d46a88a..7cfbaffe3be 100644
--- a/lib/browser_detection.rb
+++ b/lib/browser_detection.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module BrowserDetection
-
def self.browser(user_agent)
case user_agent
when /Edg/i
@@ -66,5 +65,4 @@ module BrowserDetection
:unknown
end
end
-
end
diff --git a/lib/cache.rb b/lib/cache.rb
index ca814c9e2bb..296519b17ed 100644
--- a/lib/cache.rb
+++ b/lib/cache.rb
@@ -15,12 +15,11 @@
# this makes it harder to reason about the API
class Cache
-
# nothing is cached for longer than 1 day EVER
# there is no reason to have data older than this clogging redis
# it is dangerous cause if we rename keys we will be stuck with
# pointless data
- MAX_CACHE_AGE = 1.day unless defined? MAX_CACHE_AGE
+ MAX_CACHE_AGE = 1.day unless defined?(MAX_CACHE_AGE)
attr_reader :namespace
@@ -47,9 +46,7 @@ class Cache
end
def clear
- keys.each do |k|
- redis.del(k)
- end
+ keys.each { |k| redis.del(k) }
end
def normalize_key(key)
@@ -80,9 +77,7 @@ class Cache
key = normalize_key(name)
raw = nil
- if !force
- raw = redis.get(key)
- end
+ raw = redis.get(key) if !force
if raw
begin
@@ -96,7 +91,8 @@ class Cache
val
end
elsif force
- raise ArgumentError, "Missing block: Calling `Cache#fetch` with `force: true` requires a block."
+ raise ArgumentError,
+ "Missing block: Calling `Cache#fetch` with `force: true` requires a block."
else
read(name)
end
@@ -105,7 +101,7 @@ class Cache
protected
def log_first_exception(e)
- if !defined? @logged_a_warning
+ if !defined?(@logged_a_warning)
@logged_a_warning = true
Discourse.warn_exception(e, "Corrupt cache... skipping entry for key #{key}")
end
@@ -129,5 +125,4 @@ class Cache
redis.setex(key, expiry, dumped)
true
end
-
end
diff --git a/lib/canonical_url.rb b/lib/canonical_url.rb
index df66c37a6c7..bc9b6e2d108 100644
--- a/lib/canonical_url.rb
+++ b/lib/canonical_url.rb
@@ -2,7 +2,7 @@
module CanonicalURL
module ControllerExtensions
- ALLOWED_CANONICAL_PARAMS = %w(page)
+ ALLOWED_CANONICAL_PARAMS = %w[page]
def canonical_url(url_for_options = {})
case url_for_options
@@ -14,14 +14,15 @@ module CanonicalURL
end
def default_canonical
- @default_canonical ||= begin
- canonical = +"#{Discourse.base_url_no_prefix}#{request.path}"
- allowed_params = params.select { |key| ALLOWED_CANONICAL_PARAMS.include?(key) }
- if allowed_params.present?
- canonical << "?#{allowed_params.keys.zip(allowed_params.values).map { |key, value| "#{key}=#{value}" }.join("&")}"
+ @default_canonical ||=
+ begin
+ canonical = +"#{Discourse.base_url_no_prefix}#{request.path}"
+ allowed_params = params.select { |key| ALLOWED_CANONICAL_PARAMS.include?(key) }
+ if allowed_params.present?
+ canonical << "?#{allowed_params.keys.zip(allowed_params.values).map { |key, value| "#{key}=#{value}" }.join("&")}"
+ end
+ canonical
end
- canonical
- end
end
def self.included(base)
@@ -31,7 +32,7 @@ module CanonicalURL
module Helpers
def canonical_link_tag(url = nil)
- tag('link', rel: 'canonical', href: url || @canonical_url || default_canonical)
+ tag("link", rel: "canonical", href: url || @canonical_url || default_canonical)
end
end
end
diff --git a/lib/category_badge.rb b/lib/category_badge.rb
index fdfd8035c51..9cf422e5880 100644
--- a/lib/category_badge.rb
+++ b/lib/category_badge.rb
@@ -1,23 +1,26 @@
# frozen_string_literal: true
module CategoryBadge
-
def self.category_stripe(color, classes)
- style = color ? "style='background-color: ##{color};'" : ''
+ style = color ? "style='background-color: ##{color};'" : ""
"<span class='#{classes}' #{style}></span>"
end
- def self.inline_category_stripe(color, styles = '', insert_blank = false)
- "<span style='background-color: ##{color};#{styles}'>#{insert_blank ? '&nbsp;' : ''}</span>"
+ def self.inline_category_stripe(color, styles = "", insert_blank = false)
+ "<span style='background-color: ##{color};#{styles}'>#{insert_blank ? "&nbsp;" : ""}</span>"
end
def self.inline_badge_wrapper_style(category)
style =
case (SiteSetting.category_style || :box).to_sym
- when :bar then 'line-height: 1.25; margin-right: 5px;'
- when :box then "background-color:##{category.color}; line-height: 1.5; margin-top: 5px; margin-right: 5px;"
- when :bullet then 'line-height: 1; margin-right: 10px;'
- when :none then ''
+ when :bar
+ "line-height: 1.25; margin-right: 5px;"
+ when :box
+ "background-color:##{category.color}; line-height: 1.5; margin-top: 5px; margin-right: 5px;"
+ when :bullet
+ "line-height: 1; margin-right: 10px;"
+ when :none
+ ""
end
" style='font-size: 0.857em; white-space: nowrap; display: inline-block; position: relative; #{style}'"
@@ -34,73 +37,88 @@ module CategoryBadge
extra_classes = "#{opts[:extra_classes]} #{SiteSetting.category_style}"
- result = +''
+ result = +""
# parent span
unless category.parent_category_id.nil? || opts[:hide_parent]
parent_category = Category.find_by(id: category.parent_category_id)
- result <<
- if opts[:inline_style]
- case (SiteSetting.category_style || :box).to_sym
- when :bar
- inline_category_stripe(parent_category.color, 'display: inline-block; padding: 1px;', true)
- when :box
- inline_category_stripe(parent_category.color, 'display: inline-block; padding: 0 1px;', true)
- when :bullet
- inline_category_stripe(parent_category.color, 'display: inline-block; width: 5px; height: 10px; line-height: 1;')
- when :none
- ''
- end
- else
- category_stripe(parent_category.color, 'badge-category-parent-bg')
- end
- end
-
- # sub parent or main category span
- result <<
- if opts[:inline_style]
+ result << if opts[:inline_style]
case (SiteSetting.category_style || :box).to_sym
when :bar
- inline_category_stripe(category.color, 'display: inline-block; padding: 1px;', true)
+ inline_category_stripe(
+ parent_category.color,
+ "display: inline-block; padding: 1px;",
+ true,
+ )
when :box
- ''
+ inline_category_stripe(
+ parent_category.color,
+ "display: inline-block; padding: 0 1px;",
+ true,
+ )
when :bullet
- inline_category_stripe(category.color, "display: inline-block; width: #{category.parent_category_id.nil? ? 10 : 5}px; height: 10px;")
+ inline_category_stripe(
+ parent_category.color,
+ "display: inline-block; width: 5px; height: 10px; line-height: 1;",
+ )
when :none
- ''
+ ""
end
else
- category_stripe(category.color, 'badge-category-bg')
+ category_stripe(parent_category.color, "badge-category-parent-bg")
end
+ end
+
+ # sub parent or main category span
+ result << if opts[:inline_style]
+ case (SiteSetting.category_style || :box).to_sym
+ when :bar
+ inline_category_stripe(category.color, "display: inline-block; padding: 1px;", true)
+ when :box
+ ""
+ when :bullet
+ inline_category_stripe(
+ category.color,
+ "display: inline-block; width: #{category.parent_category_id.nil? ? 10 : 5}px; height: 10px;",
+ )
+ when :none
+ ""
+ end
+ else
+ category_stripe(category.color, "badge-category-bg")
+ end
# category name
- class_names = 'badge-category clear-badge'
- description = category.description_text ? "title='#{category.description_text}'" : ''
- category_url = opts[:absolute_url] ? "#{Discourse.base_url_no_prefix}#{category.url}" : category.url
+ class_names = "badge-category clear-badge"
+ description = category.description_text ? "title='#{category.description_text}'" : ""
+ category_url =
+ opts[:absolute_url] ? "#{Discourse.base_url_no_prefix}#{category.url}" : category.url
extra_span_classes =
if opts[:inline_style]
case (SiteSetting.category_style || :box).to_sym
when :bar
- 'color: #222222; padding: 3px; vertical-align: text-top; margin-top: -3px; display: inline-block;'
+ "color: #222222; padding: 3px; vertical-align: text-top; margin-top: -3px; display: inline-block;"
when :box
"color: ##{category.text_color}; padding: 0 5px;"
when :bullet
- 'color: #222222; vertical-align: text-top; line-height: 1; margin-left: 4px; padding-left: 2px; display: inline;'
+ "color: #222222; vertical-align: text-top; line-height: 1; margin-left: 4px; padding-left: 2px; display: inline;"
when :none
- ''
- end + 'max-width: 150px; overflow: hidden; text-overflow: ellipsis;'
+ ""
+ end + "max-width: 150px; overflow: hidden; text-overflow: ellipsis;"
elsif (SiteSetting.category_style).to_sym == :box
"color: ##{category.text_color}"
else
- ''
+ ""
end
result << "<span style='#{extra_span_classes}' data-drop-close='true' class='#{class_names}'
#{description}>"
- result << ERB::Util.html_escape(category.name) << '</span>'
+ result << ERB::Util.html_escape(category.name) << "</span>"
- result = "<a class='badge-wrapper #{extra_classes}' href='#{category_url}'" + (opts[:inline_style] ? inline_badge_wrapper_style(category) : '') + ">#{result}</a>"
+ result =
+ "<a class='badge-wrapper #{extra_classes}' href='#{category_url}'" +
+ (opts[:inline_style] ? inline_badge_wrapper_style(category) : "") + ">#{result}</a>"
result.html_safe
end
diff --git a/lib/chrome_installed_checker.rb b/lib/chrome_installed_checker.rb
index 0576eb74016..2f8c2824cc9 100644
--- a/lib/chrome_installed_checker.rb
+++ b/lib/chrome_installed_checker.rb
@@ -3,13 +3,17 @@
require "rbconfig"
class ChromeInstalledChecker
- class ChromeError < StandardError; end
- class ChromeVersionError < ChromeError; end
- class ChromeNotInstalled < ChromeError; end
- class ChromeVersionTooLow < ChromeError; end
+ class ChromeError < StandardError
+ end
+ class ChromeVersionError < ChromeError
+ end
+ class ChromeNotInstalled < ChromeError
+ end
+ class ChromeVersionTooLow < ChromeError
+ end
def self.run
- if RbConfig::CONFIG['host_os'][/darwin|mac os/]
+ if RbConfig::CONFIG["host_os"][/darwin|mac os/]
binary = "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
elsif system("command -v google-chrome-stable >/dev/null;")
binary = "google-chrome-stable"
@@ -18,15 +22,15 @@ class ChromeInstalledChecker
binary ||= "chromium" if system("command -v chromium >/dev/null;")
if !binary
- raise ChromeNotInstalled.new("Chrome is not installed. Download from https://www.google.com/chrome/browser/desktop/index.html")
+ raise ChromeNotInstalled.new(
+ "Chrome is not installed. Download from https://www.google.com/chrome/browser/desktop/index.html",
+ )
end
version = `\"#{binary}\" --version`
version_match = version.match(/[\d\.]+/)
- if !version_match
- raise ChromeError.new("Can't get the #{binary} version")
- end
+ raise ChromeError.new("Can't get the #{binary} version") if !version_match
if Gem::Version.new(version_match[0]) < Gem::Version.new("59")
raise ChromeVersionTooLow.new("Chrome 59 or higher is required")
diff --git a/lib/comment_migration.rb b/lib/comment_migration.rb
index bcfcdfd10ec..94062378c23 100644
--- a/lib/comment_migration.rb
+++ b/lib/comment_migration.rb
@@ -28,24 +28,27 @@ class CommentMigration < ActiveRecord::Migration[4.2]
end
def down
- replace_nils(comments_up).deep_merge(comments_down).each do |table|
- table[1].each do |column|
- table_name = table[0]
- column_name = column[0]
- comment = column[1]
+ replace_nils(comments_up)
+ .deep_merge(comments_down)
+ .each do |table|
+ table[1].each do |column|
+ table_name = table[0]
+ column_name = column[0]
+ comment = column[1]
- if column_name == :_table
- DB.exec "COMMENT ON TABLE #{table_name} IS ?", comment
- puts " COMMENT ON TABLE #{table_name}"
- else
- DB.exec "COMMENT ON COLUMN #{table_name}.#{column_name} IS ?", comment
- puts " COMMENT ON COLUMN #{table_name}.#{column_name}"
+ if column_name == :_table
+ DB.exec "COMMENT ON TABLE #{table_name} IS ?", comment
+ puts " COMMENT ON TABLE #{table_name}"
+ else
+ DB.exec "COMMENT ON COLUMN #{table_name}.#{column_name} IS ?", comment
+ puts " COMMENT ON COLUMN #{table_name}.#{column_name}"
+ end
end
end
- end
end
private
+
def replace_nils(hash)
hash.each do |key, value|
if Hash === value
diff --git a/lib/common_passwords.rb b/lib/common_passwords.rb
index 901a007b01b..5b4aec28e85 100644
--- a/lib/common_passwords.rb
+++ b/lib/common_passwords.rb
@@ -12,9 +12,8 @@
# Discourse.redis.without_namespace.del CommonPasswords::LIST_KEY
class CommonPasswords
-
- PASSWORD_FILE = File.join(Rails.root, 'lib', 'common_passwords', '10-char-common-passwords.txt')
- LIST_KEY = 'discourse-common-passwords'
+ PASSWORD_FILE = File.join(Rails.root, "lib", "common_passwords", "10-char-common-passwords.txt")
+ LIST_KEY = "discourse-common-passwords"
@mutex = Mutex.new
@@ -32,9 +31,7 @@ class CommonPasswords
end
def self.password_list
- @mutex.synchronize do
- load_passwords unless redis.scard(LIST_KEY) > 0
- end
+ @mutex.synchronize { load_passwords unless redis.scard(LIST_KEY) > 0 }
RedisPasswordList.new
end
@@ -49,5 +46,4 @@ class CommonPasswords
# tolerate this so we don't block signups
Rails.logger.error "Common passwords file #{PASSWORD_FILE} is not found! Common password checking is skipped."
end
-
end
diff --git a/lib/composer_messages_finder.rb b/lib/composer_messages_finder.rb
index 510048d1db4..878727f20c9 100644
--- a/lib/composer_messages_finder.rb
+++ b/lib/composer_messages_finder.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class ComposerMessagesFinder
-
def initialize(user, details)
@user = user
@details = details
@@ -29,26 +28,30 @@ class ComposerMessagesFinder
if creating_topic?
count = @user.created_topic_count
- education_key = 'education.new-topic'
+ education_key = "education.new-topic"
else
count = @user.post_count
- education_key = 'education.new-reply'
+ education_key = "education.new-reply"
end
if count < SiteSetting.educate_until_posts
- return {
- id: 'education',
- templateName: 'education',
- wait_for_typing: true,
- body: PrettyText.cook(
- I18n.t(
- education_key,
- education_posts_text: I18n.t('education.until_posts', count: SiteSetting.educate_until_posts),
- site_name: SiteSetting.title,
- base_path: Discourse.base_path
- )
- )
- }
+ return(
+ {
+ id: "education",
+ templateName: "education",
+ wait_for_typing: true,
+ body:
+ PrettyText.cook(
+ I18n.t(
+ education_key,
+ education_posts_text:
+ I18n.t("education.until_posts", count: SiteSetting.educate_until_posts),
+ site_name: SiteSetting.title,
+ base_path: Discourse.base_path,
+ ),
+ ),
+ }
+ )
end
nil
@@ -59,35 +62,55 @@ class ComposerMessagesFinder
return unless replying? && @user.posted_too_much_in_topic?(@details[:topic_id])
{
- id: 'too_many_replies',
- templateName: 'education',
- body: PrettyText.cook(I18n.t('education.too_many_replies', newuser_max_replies_per_topic: SiteSetting.newuser_max_replies_per_topic))
+ id: "too_many_replies",
+ templateName: "education",
+ body:
+ PrettyText.cook(
+ I18n.t(
+ "education.too_many_replies",
+ newuser_max_replies_per_topic: SiteSetting.newuser_max_replies_per_topic,
+ ),
+ ),
}
end
# Should a user be contacted to update their avatar?
def check_avatar_notification
-
# A user has to be basic at least to be considered for an avatar notification
return unless @user.has_trust_level?(TrustLevel[1])
# We don't notify users who have avatars or who have been notified already.
- return if @user.uploaded_avatar_id || UserHistory.exists_for_user?(@user, :notified_about_avatar)
+ if @user.uploaded_avatar_id || UserHistory.exists_for_user?(@user, :notified_about_avatar)
+ return
+ end
# Do not notify user if any of the following is true:
# - "disable avatar education message" is enabled
# - "sso overrides avatar" is enabled
# - "allow uploaded avatars" is disabled
- return if SiteSetting.disable_avatar_education_message || SiteSetting.discourse_connect_overrides_avatar || !TrustLevelAndStaffAndDisabledSetting.matches?(SiteSetting.allow_uploaded_avatars, @user)
+ if SiteSetting.disable_avatar_education_message ||
+ SiteSetting.discourse_connect_overrides_avatar ||
+ !TrustLevelAndStaffAndDisabledSetting.matches?(SiteSetting.allow_uploaded_avatars, @user)
+ return
+ end
# If we got this far, log that we've nagged them about the avatar
- UserHistory.create!(action: UserHistory.actions[:notified_about_avatar], target_user_id: @user.id)
+ UserHistory.create!(
+ action: UserHistory.actions[:notified_about_avatar],
+ target_user_id: @user.id,
+ )
# Return the message
{
- id: 'avatar',
- templateName: 'education',
- body: PrettyText.cook(I18n.t('education.avatar', profile_path: "/u/#{@user.username_lower}/preferences/account#profile-picture"))
+ id: "avatar",
+ templateName: "education",
+ body:
+ PrettyText.cook(
+ I18n.t(
+ "education.avatar",
+ profile_path: "/u/#{@user.username_lower}/preferences/account#profile-picture",
+ ),
+ ),
}
end
@@ -96,39 +119,45 @@ class ComposerMessagesFinder
return unless educate_reply?(:notified_about_sequential_replies)
# Count the posts made by this user in the last day
- recent_posts_user_ids = Post.where(topic_id: @details[:topic_id])
- .where("created_at > ?", 1.day.ago)
- .where(post_type: Post.types[:regular])
- .order('created_at desc')
- .limit(SiteSetting.sequential_replies_threshold)
- .pluck(:user_id)
+ recent_posts_user_ids =
+ Post
+ .where(topic_id: @details[:topic_id])
+ .where("created_at > ?", 1.day.ago)
+ .where(post_type: Post.types[:regular])
+ .order("created_at desc")
+ .limit(SiteSetting.sequential_replies_threshold)
+ .pluck(:user_id)
# Did we get back as many posts as we asked for, and are they all by the current user?
- return if recent_posts_user_ids.size != SiteSetting.sequential_replies_threshold ||
- recent_posts_user_ids.detect { |u| u != @user.id }
+ if recent_posts_user_ids.size != SiteSetting.sequential_replies_threshold ||
+ recent_posts_user_ids.detect { |u| u != @user.id }
+ return
+ end
# If we got this far, log that we've nagged them about the sequential replies
- UserHistory.create!(action: UserHistory.actions[:notified_about_sequential_replies],
- target_user_id: @user.id,
- topic_id: @details[:topic_id])
+ UserHistory.create!(
+ action: UserHistory.actions[:notified_about_sequential_replies],
+ target_user_id: @user.id,
+ topic_id: @details[:topic_id],
+ )
{
- id: 'sequential_replies',
- templateName: 'education',
+ id: "sequential_replies",
+ templateName: "education",
wait_for_typing: true,
- extraClass: 'education-message',
+ extraClass: "education-message",
hide_if_whisper: true,
- body: PrettyText.cook(I18n.t('education.sequential_replies'))
+ body: PrettyText.cook(I18n.t("education.sequential_replies")),
}
end
def check_dominating_topic
return unless educate_reply?(:notified_about_dominating_topic)
- return if @topic.blank? ||
- @topic.user_id == @user.id ||
- @topic.posts_count < SiteSetting.summary_posts_required ||
- @topic.private_message?
+ if @topic.blank? || @topic.user_id == @user.id ||
+ @topic.posts_count < SiteSetting.summary_posts_required || @topic.private_message?
+ return
+ end
posts_by_user = @user.posts.where(topic_id: @topic.id).count
@@ -136,16 +165,18 @@ class ComposerMessagesFinder
return if ratio < (SiteSetting.dominating_topic_minimum_percent.to_f / 100.0)
# Log the topic notification
- UserHistory.create!(action: UserHistory.actions[:notified_about_dominating_topic],
- target_user_id: @user.id,
- topic_id: @details[:topic_id])
+ UserHistory.create!(
+ action: UserHistory.actions[:notified_about_dominating_topic],
+ target_user_id: @user.id,
+ topic_id: @details[:topic_id],
+ )
{
- id: 'dominating_topic',
- templateName: 'dominating-topic',
+ id: "dominating_topic",
+ templateName: "dominating-topic",
wait_for_typing: true,
- extraClass: 'education-message dominating-topic-message',
- body: PrettyText.cook(I18n.t('education.dominating_topic'))
+ extraClass: "education-message dominating-topic-message",
+ body: PrettyText.cook(I18n.t("education.dominating_topic")),
}
end
@@ -157,73 +188,85 @@ class ComposerMessagesFinder
reply_to_user_id = Post.where(id: @details[:post_id]).pluck(:user_id)[0]
# Users's last x posts in the topic
- last_x_replies = @topic.
- posts.
- where(user_id: @user.id).
- order('created_at desc').
- limit(SiteSetting.get_a_room_threshold).
- pluck(:reply_to_user_id).
- find_all { |uid| uid != @user.id && uid == reply_to_user_id }
+ last_x_replies =
+ @topic
+ .posts
+ .where(user_id: @user.id)
+ .order("created_at desc")
+ .limit(SiteSetting.get_a_room_threshold)
+ .pluck(:reply_to_user_id)
+ .find_all { |uid| uid != @user.id && uid == reply_to_user_id }
return unless last_x_replies.size == SiteSetting.get_a_room_threshold
- return unless @topic.posts.count('distinct user_id') >= min_users_posted
+ return unless @topic.posts.count("distinct user_id") >= min_users_posted
- UserHistory.create!(action: UserHistory.actions[:notified_about_get_a_room],
- target_user_id: @user.id,
- topic_id: @details[:topic_id])
+ UserHistory.create!(
+ action: UserHistory.actions[:notified_about_get_a_room],
+ target_user_id: @user.id,
+ topic_id: @details[:topic_id],
+ )
reply_username = User.where(id: last_x_replies[0]).pluck_first(:username)
{
- id: 'get_a_room',
- templateName: 'get-a-room',
+ id: "get_a_room",
+ templateName: "get-a-room",
wait_for_typing: true,
reply_username: reply_username,
- extraClass: 'education-message get-a-room',
- body: PrettyText.cook(
- I18n.t(
- 'education.get_a_room',
- count: SiteSetting.get_a_room_threshold,
- reply_username: reply_username,
- base_path: Discourse.base_path
- )
- )
+ extraClass: "education-message get-a-room",
+ body:
+ PrettyText.cook(
+ I18n.t(
+ "education.get_a_room",
+ count: SiteSetting.get_a_room_threshold,
+ reply_username: reply_username,
+ base_path: Discourse.base_path,
+ ),
+ ),
}
end
def check_reviving_old_topic
return unless replying?
- return if @topic.nil? ||
- SiteSetting.warn_reviving_old_topic_age < 1 ||
- @topic.last_posted_at.nil? ||
- @topic.last_posted_at > SiteSetting.warn_reviving_old_topic_age.days.ago
+ if @topic.nil? || SiteSetting.warn_reviving_old_topic_age < 1 || @topic.last_posted_at.nil? ||
+ @topic.last_posted_at > SiteSetting.warn_reviving_old_topic_age.days.ago
+ return
+ end
{
- id: 'reviving_old',
- templateName: 'education',
+ id: "reviving_old",
+ templateName: "education",
wait_for_typing: false,
- extraClass: 'education-message',
- body: PrettyText.cook(
- I18n.t(
- 'education.reviving_old_topic',
- time_ago: FreedomPatches::Rails4.time_ago_in_words(@topic.last_posted_at, false, scope: :'datetime.distance_in_words_verbose')
- )
- )
+ extraClass: "education-message",
+ body:
+ PrettyText.cook(
+ I18n.t(
+ "education.reviving_old_topic",
+ time_ago:
+ FreedomPatches::Rails4.time_ago_in_words(
+ @topic.last_posted_at,
+ false,
+ scope: :"datetime.distance_in_words_verbose",
+ ),
+ ),
+ ),
}
end
def self.user_not_seen_in_a_while(usernames)
- User.where(username_lower: usernames).where("last_seen_at < ?", SiteSetting.pm_warn_user_last_seen_months_ago.months.ago).pluck(:username).sort
+ User
+ .where(username_lower: usernames)
+ .where("last_seen_at < ?", SiteSetting.pm_warn_user_last_seen_months_ago.months.ago)
+ .pluck(:username)
+ .sort
end
private
def educate_reply?(type)
- replying? &&
- @details[:topic_id] &&
- (@topic.present? && [email protected]_message?) &&
- (@user.post_count >= SiteSetting.educate_until_posts) &&
- !UserHistory.exists_for_user?(@user, type, topic_id: @details[:topic_id])
+ replying? && @details[:topic_id] && (@topic.present? && [email protected]_message?) &&
+ (@user.post_count >= SiteSetting.educate_until_posts) &&
+ !UserHistory.exists_for_user?(@user, type, topic_id: @details[:topic_id])
end
def creating_topic?
@@ -237,5 +280,4 @@ class ComposerMessagesFinder
def editing_post?
@details[:composer_action] == "edit"
end
-
end
diff --git a/lib/compression/engine.rb b/lib/compression/engine.rb
index c098c0b6687..732164639dc 100644
--- a/lib/compression/engine.rb
+++ b/lib/compression/engine.rb
@@ -9,12 +9,13 @@ module Compression
Compression::Zip.new,
Compression::Pipeline.new([Compression::Tar.new, Compression::Gzip.new]),
Compression::Gzip.new,
- Compression::Tar.new
+ Compression::Tar.new,
]
end
def self.engine_for(filename, strategies: default_strategies)
- strategy = strategies.detect(-> { raise UnsupportedFileExtension }) { |e| e.can_handle?(filename) }
+ strategy =
+ strategies.detect(-> { raise UnsupportedFileExtension }) { |e| e.can_handle?(filename) }
new(strategy)
end
diff --git a/lib/compression/gzip.rb b/lib/compression/gzip.rb
index 4d0b7c51e15..c668b088f72 100644
--- a/lib/compression/gzip.rb
+++ b/lib/compression/gzip.rb
@@ -3,12 +3,17 @@
module Compression
class Gzip < Strategy
def extension
- '.gz'
+ ".gz"
end
def compress(path, target_name)
gzip_target = sanitize_path("#{path}/#{target_name}")
- Discourse::Utils.execute_command('gzip', '-5', gzip_target, failure_message: "Failed to gzip file.")
+ Discourse::Utils.execute_command(
+ "gzip",
+ "-5",
+ gzip_target,
+ failure_message: "Failed to gzip file.",
+ )
"#{gzip_target}.gz"
end
@@ -23,7 +28,8 @@ module Compression
true
end
- def extract_folder(_entry, _entry_path); end
+ def extract_folder(_entry, _entry_path)
+ end
def get_compressed_file_stream(compressed_file_path)
gzip = Zlib::GzipReader.open(compressed_file_path)
@@ -32,7 +38,7 @@ module Compression
def build_entry_path(dest_path, _, compressed_file_path)
basename = File.basename(compressed_file_path)
- basename.gsub!(/#{Regexp.escape(extension)}$/, '')
+ basename.gsub!(/#{Regexp.escape(extension)}$/, "")
File.join(dest_path, basename)
end
@@ -44,12 +50,11 @@ module Compression
remaining_size = available_size
if ::File.exist?(entry_path)
- raise ::Zip::DestinationFileExistsError,
- "Destination '#{entry_path}' already exists"
+ raise ::Zip::DestinationFileExistsError, "Destination '#{entry_path}' already exists"
end # Change this later.
- ::File.open(entry_path, 'wb') do |os|
- buf = ''.dup
+ ::File.open(entry_path, "wb") do |os|
+ buf = "".dup
while (buf = entry.read(chunk_size))
remaining_size -= chunk_size
raise ExtractFailed if remaining_size.negative?
diff --git a/lib/compression/pipeline.rb b/lib/compression/pipeline.rb
index 1ea9f17ddb2..39a03f9cdae 100644
--- a/lib/compression/pipeline.rb
+++ b/lib/compression/pipeline.rb
@@ -7,25 +7,27 @@ module Compression
end
def extension
- @strategies.reduce('') { |ext, strategy| ext += strategy.extension }
+ @strategies.reduce("") { |ext, strategy| ext += strategy.extension }
end
def compress(path, target_name)
current_target = target_name
- @strategies.reduce('') do |compressed_path, strategy|
+ @strategies.reduce("") do |compressed_path, strategy|
compressed_path = strategy.compress(path, current_target)
- current_target = compressed_path.split('/').last
+ current_target = compressed_path.split("/").last
compressed_path
end
end
def decompress(dest_path, compressed_file_path, max_size)
- @strategies.reverse.reduce(compressed_file_path) do |to_decompress, strategy|
- next_compressed_file = strategy.decompress(dest_path, to_decompress, max_size)
- FileUtils.rm_rf(to_decompress)
- next_compressed_file
- end
+ @strategies
+ .reverse
+ .reduce(compressed_file_path) do |to_decompress, strategy|
+ next_compressed_file = strategy.decompress(dest_path, to_decompress, max_size)
+ FileUtils.rm_rf(to_decompress)
+ next_compressed_file
+ end
end
end
end
diff --git a/lib/compression/strategy.rb b/lib/compression/strategy.rb
index 8bb54f87d4f..d4a05a578c9 100644
--- a/lib/compression/strategy.rb
+++ b/lib/compression/strategy.rb
@@ -18,9 +18,7 @@ module Compression
entries_of(compressed_file).each do |entry|
entry_path = build_entry_path(sanitized_dest_path, entry, sanitized_compressed_file_path)
- if !is_safe_path_for_extraction?(entry_path, sanitized_dest_path)
- next
- end
+ next if !is_safe_path_for_extraction?(entry_path, sanitized_dest_path)
FileUtils.mkdir_p(File.dirname(entry_path))
if is_file?(entry)
@@ -45,10 +43,10 @@ module Compression
filename.strip.tap do |name|
# NOTE: File.basename doesn't work right with Windows paths on Unix
# get only the filename, not the whole path
- name.sub! /\A.*(\\|\/)/, ''
+ name.sub! %r{\A.*(\\|/)}, ""
# Finally, replace all non alphanumeric, underscore
# or periods with underscore
- name.gsub! /[^\w\.\-]/, '_'
+ name.gsub! /[^\w\.\-]/, "_"
end
end
@@ -75,7 +73,7 @@ module Compression
raise DestinationFileExistsError, "Destination '#{entry_path}' already exists"
end
- ::File.open(entry_path, 'wb') do |os|
+ ::File.open(entry_path, "wb") do |os|
while (buf = entry.read(chunk_size))
remaining_size -= buf.size
raise ExtractFailed if remaining_size.negative?
diff --git a/lib/compression/tar.rb b/lib/compression/tar.rb
index 580a8ebdd5d..3346d1e764a 100644
--- a/lib/compression/tar.rb
+++ b/lib/compression/tar.rb
@@ -1,23 +1,31 @@
# frozen_string_literal: true
-require 'rubygems/package'
+require "rubygems/package"
module Compression
class Tar < Strategy
def extension
- '.tar'
+ ".tar"
end
def compress(path, target_name)
tar_filename = sanitize_filename("#{target_name}.tar")
- Discourse::Utils.execute_command('tar', '--create', '--file', tar_filename, target_name, failure_message: "Failed to tar file.")
+ Discourse::Utils.execute_command(
+ "tar",
+ "--create",
+ "--file",
+ tar_filename,
+ target_name,
+ failure_message: "Failed to tar file.",
+ )
sanitize_path("#{path}/#{tar_filename}")
end
private
- def extract_folder(_entry, _entry_path); end
+ def extract_folder(_entry, _entry_path)
+ end
def get_compressed_file_stream(compressed_file_path)
file_stream = IO.new(IO.sysopen(compressed_file_path))
diff --git a/lib/compression/zip.rb b/lib/compression/zip.rb
index 63c6b927299..dbf132bf880 100644
--- a/lib/compression/zip.rb
+++ b/lib/compression/zip.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-require 'zip'
+require "zip"
module Compression
class Zip < Strategy
def extension
- '.zip'
+ ".zip"
end
def compress(path, target_name)
@@ -15,7 +15,7 @@ module Compression
::Zip::File.open(zip_filename, ::Zip::File::CREATE) do |zipfile|
if File.directory?(absolute_path)
entries = Dir.entries(absolute_path) - %w[. ..]
- write_entries(entries, absolute_path, '', zipfile)
+ write_entries(entries, absolute_path, "", zipfile)
else
put_into_archive(absolute_path, zipfile, target_name)
end
@@ -47,15 +47,14 @@ module Compression
remaining_size = available_size
if ::File.exist?(entry_path)
- raise ::Zip::DestinationFileExistsError,
- "Destination '#{entry_path}' already exists"
+ raise ::Zip::DestinationFileExistsError, "Destination '#{entry_path}' already exists"
end
- ::File.open(entry_path, 'wb') do |os|
+ ::File.open(entry_path, "wb") do |os|
entry.get_input_stream do |is|
entry.set_extra_attributes_on_path(entry_path)
- buf = ''.dup
+ buf = "".dup
while (buf = is.sysread(chunk_size, buf))
remaining_size -= chunk_size
raise ExtractFailed if remaining_size.negative?
@@ -70,7 +69,7 @@ module Compression
# A helper method to make the recursion work.
def write_entries(entries, base_path, path, zipfile)
entries.each do |e|
- zipfile_path = path == '' ? e : File.join(path, e)
+ zipfile_path = path == "" ? e : File.join(path, e)
disk_file_path = File.join(base_path, zipfile_path)
if File.directory? disk_file_path
diff --git a/lib/configurable_urls.rb b/lib/configurable_urls.rb
index f20321ff6dc..c196b74b12f 100644
--- a/lib/configurable_urls.rb
+++ b/lib/configurable_urls.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module ConfigurableUrls
-
def faq_path
SiteSetting.faq_url.blank? ? "#{Discourse.base_path}/faq" : SiteSetting.faq_url
end
@@ -11,7 +10,10 @@ module ConfigurableUrls
end
def privacy_path
- SiteSetting.privacy_policy_url.blank? ? "#{Discourse.base_path}/privacy" : SiteSetting.privacy_policy_url
+ if SiteSetting.privacy_policy_url.blank?
+ "#{Discourse.base_path}/privacy"
+ else
+ SiteSetting.privacy_policy_url
+ end
end
-
end
diff --git a/lib/content_buffer.rb b/lib/content_buffer.rb
index 997b57d795e..6d6895811f0 100644
--- a/lib/content_buffer.rb
+++ b/lib/content_buffer.rb
@@ -3,7 +3,6 @@
# this class is used to track changes to an arbitrary buffer
class ContentBuffer
-
def initialize(initial_content)
@initial_content = initial_content
@lines = @initial_content.split("\n")
@@ -17,7 +16,6 @@ class ContentBuffer
text = transform[:text]
if transform[:operation] == :delete
-
# fix first line
l = @lines[start_row]
@@ -32,16 +30,13 @@ class ContentBuffer
@lines[start_row] = l
# remove middle lines
- (finish_row - start_row).times do
- l = @lines.delete_at start_row + 1
- end
+ (finish_row - start_row).times { l = @lines.delete_at start_row + 1 }
# fix last line
@lines[start_row] << @lines[finish_row][finish_col - 1..-1]
end
if transform[:operation] == :insert
-
@lines[start_row].insert(start_col, text)
split = @lines[start_row].split("\n")
@@ -56,7 +51,6 @@ class ContentBuffer
@lines.insert(i, "") unless @lines.length > i
@lines[i] = split[-1] + @lines[i]
end
-
end
end
diff --git a/lib/content_security_policy.rb b/lib/content_security_policy.rb
index 0cfd309a4bc..107dc0437df 100644
--- a/lib/content_security_policy.rb
+++ b/lib/content_security_policy.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'content_security_policy/builder'
-require 'content_security_policy/extension'
+require "content_security_policy/builder"
+require "content_security_policy/extension"
class ContentSecurityPolicy
class << self
diff --git a/lib/content_security_policy/builder.rb b/lib/content_security_policy/builder.rb
index 4f5dbfb9133..e23f55111e2 100644
--- a/lib/content_security_policy/builder.rb
+++ b/lib/content_security_policy/builder.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-require 'content_security_policy/default'
+require "content_security_policy/default"
class ContentSecurityPolicy
class Builder
@@ -33,7 +33,9 @@ class ContentSecurityPolicy
def <<(extension)
return unless valid_extension?(extension)
- extension.each { |directive, sources| extend_directive(normalize_directive(directive), sources) }
+ extension.each do |directive, sources|
+ extend_directive(normalize_directive(directive), sources)
+ end
end
def build
@@ -53,7 +55,7 @@ class ContentSecurityPolicy
private
def normalize_directive(directive)
- directive.to_s.gsub('-', '_').to_sym
+ directive.to_s.gsub("-", "_").to_sym
end
def normalize_source(source)
diff --git a/lib/content_security_policy/default.rb b/lib/content_security_policy/default.rb
index ef67672b059..6b147079c70 100644
--- a/lib/content_security_policy/default.rb
+++ b/lib/content_security_policy/default.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-require 'content_security_policy'
+require "content_security_policy"
class ContentSecurityPolicy
class Default
@@ -7,16 +7,19 @@ class ContentSecurityPolicy
def initialize(base_url:)
@base_url = base_url
- @directives = {}.tap do |directives|
- directives[:upgrade_insecure_requests] = [] if SiteSetting.force_https
- directives[:base_uri] = [:self]
- directives[:object_src] = [:none]
- directives[:script_src] = script_src
- directives[:worker_src] = worker_src
- directives[:report_uri] = report_uri if SiteSetting.content_security_policy_collect_reports
- directives[:frame_ancestors] = frame_ancestors if restrict_embed?
- directives[:manifest_src] = ["'self'"]
- end
+ @directives =
+ {}.tap do |directives|
+ directives[:upgrade_insecure_requests] = [] if SiteSetting.force_https
+ directives[:base_uri] = [:self]
+ directives[:object_src] = [:none]
+ directives[:script_src] = script_src
+ directives[:worker_src] = worker_src
+ directives[
+ :report_uri
+ ] = report_uri if SiteSetting.content_security_policy_collect_reports
+ directives[:frame_ancestors] = frame_ancestors if restrict_embed?
+ directives[:manifest_src] = ["'self'"]
+ end
end
private
@@ -27,27 +30,34 @@ class ContentSecurityPolicy
SCRIPT_ASSET_DIRECTORIES = [
# [dir, can_use_s3_cdn, can_use_cdn, for_worker]
- ['/assets/', true, true, true],
- ['/brotli_asset/', true, true, true],
- ['/extra-locales/', false, false, false],
- ['/highlight-js/', false, true, false],
- ['/javascripts/', false, true, true],
- ['/plugins/', false, true, true],
- ['/theme-javascripts/', false, true, false],
- ['/svg-sprite/', false, true, false],
+ ["/assets/", true, true, true],
+ ["/brotli_asset/", true, true, true],
+ ["/extra-locales/", false, false, false],
+ ["/highlight-js/", false, true, false],
+ ["/javascripts/", false, true, true],
+ ["/plugins/", false, true, true],
+ ["/theme-javascripts/", false, true, false],
+ ["/svg-sprite/", false, true, false],
]
- def script_assets(base = base_url, s3_cdn = GlobalSetting.s3_asset_cdn_url.presence || GlobalSetting.s3_cdn_url, cdn = GlobalSetting.cdn_url, worker: false)
- SCRIPT_ASSET_DIRECTORIES.map do |dir, can_use_s3_cdn, can_use_cdn, for_worker|
- next if worker && !for_worker
- if can_use_s3_cdn && s3_cdn
- s3_cdn + dir
- elsif can_use_cdn && cdn
- cdn + Discourse.base_path + dir
- else
- base + dir
+ def script_assets(
+ base = base_url,
+ s3_cdn = GlobalSetting.s3_asset_cdn_url.presence || GlobalSetting.s3_cdn_url,
+ cdn = GlobalSetting.cdn_url,
+ worker: false
+ )
+ SCRIPT_ASSET_DIRECTORIES
+ .map do |dir, can_use_s3_cdn, can_use_cdn, for_worker|
+ next if worker && !for_worker
+ if can_use_s3_cdn && s3_cdn
+ s3_cdn + dir
+ elsif can_use_cdn && cdn
+ cdn + Discourse.base_path + dir
+ else
+ base + dir
+ end
end
- end.compact
+ .compact
end
def script_src
@@ -55,7 +65,7 @@ class ContentSecurityPolicy
"#{base_url}/logs/",
"#{base_url}/sidekiq/",
"#{base_url}/mini-profiler-resources/",
- *script_assets
+ *script_assets,
].tap do |sources|
sources << :report_sample if SiteSetting.content_security_policy_collect_reports
sources << :unsafe_eval if Rails.env.development? # TODO remove this once we have proper source maps in dev
@@ -67,23 +77,25 @@ class ContentSecurityPolicy
end
# we need analytics.js still as gtag/js is a script wrapper for it
- sources << 'https://www.google-analytics.com/analytics.js' if SiteSetting.ga_universal_tracking_code.present?
- sources << 'https://www.googletagmanager.com/gtag/js' if SiteSetting.ga_universal_tracking_code.present? && SiteSetting.ga_version == "v4_gtag"
+ if SiteSetting.ga_universal_tracking_code.present?
+ sources << "https://www.google-analytics.com/analytics.js"
+ end
+ if SiteSetting.ga_universal_tracking_code.present? && SiteSetting.ga_version == "v4_gtag"
+ sources << "https://www.googletagmanager.com/gtag/js"
+ end
if SiteSetting.gtm_container_id.present?
- sources << 'https://www.googletagmanager.com/gtm.js'
+ sources << "https://www.googletagmanager.com/gtm.js"
sources << "'nonce-#{ApplicationHelper.google_tag_manager_nonce}'"
end
- if SiteSetting.splash_screen
- sources << "'#{SplashScreenHelper.fingerprint}'"
- end
+ sources << "'#{SplashScreenHelper.fingerprint}'" if SiteSetting.splash_screen
end
end
def worker_src
[
"'self'", # For service worker
- *script_assets(worker: true)
+ *script_assets(worker: true),
]
end
@@ -92,15 +104,11 @@ class ContentSecurityPolicy
end
def frame_ancestors
- [
- "'self'",
- *EmbeddableHost.pluck(:host).map { |host| "https://#{host}" }
- ]
+ ["'self'", *EmbeddableHost.pluck(:host).map { |host| "https://#{host}" }]
end
def restrict_embed?
- SiteSetting.content_security_policy_frame_ancestors &&
- !SiteSetting.embed_any_origin
+ SiteSetting.content_security_policy_frame_ancestors && !SiteSetting.embed_any_origin
end
end
end
diff --git a/lib/content_security_policy/extension.rb b/lib/content_security_policy/extension.rb
index 51b59acda31..150e0048622 100644
--- a/lib/content_security_policy/extension.rb
+++ b/lib/content_security_policy/extension.rb
@@ -4,12 +4,12 @@ class ContentSecurityPolicy
extend self
def site_setting_extension
- { script_src: SiteSetting.content_security_policy_script_src.split('|') }
+ { script_src: SiteSetting.content_security_policy_script_src.split("|") }
end
def path_specific_extension(path_info)
{}.tap do |obj|
- for_qunit_route = !Rails.env.production? && ["/qunit", "/wizard/qunit"].include?(path_info)
+ for_qunit_route = !Rails.env.production? && %w[/qunit /wizard/qunit].include?(path_info)
for_qunit_route ||= "/theme-qunit" == path_info
obj[:script_src] = :unsafe_eval if for_qunit_route
end
@@ -23,7 +23,7 @@ class ContentSecurityPolicy
end
end
- THEME_SETTING = 'extend_content_security_policy'
+ THEME_SETTING = "extend_content_security_policy"
def theme_extensions(theme_id)
key = "theme_extensions_#{theme_id}"
@@ -37,47 +37,55 @@ class ContentSecurityPolicy
private
def cache
- @cache ||= DistributedCache.new('csp_extensions')
+ @cache ||= DistributedCache.new("csp_extensions")
end
def find_theme_extensions(theme_id)
extensions = []
theme_ids = Theme.transform_ids(theme_id)
- Theme.where(id: theme_ids).find_each do |theme|
- theme.cached_settings.each do |setting, value|
- extensions << build_theme_extension(value.split("|")) if setting.to_s == THEME_SETTING
+ Theme
+ .where(id: theme_ids)
+ .find_each do |theme|
+ theme.cached_settings.each do |setting, value|
+ extensions << build_theme_extension(value.split("|")) if setting.to_s == THEME_SETTING
+ end
end
- end
-
- extensions << build_theme_extension(ThemeModifierHelper.new(theme_ids: theme_ids).csp_extensions)
- html_fields = ThemeField.where(
- theme_id: theme_ids,
- target_id: ThemeField.basic_targets.map { |target| Theme.targets[target.to_sym] },
- name: ThemeField.html_fields
+ extensions << build_theme_extension(
+ ThemeModifierHelper.new(theme_ids: theme_ids).csp_extensions,
)
+ html_fields =
+ ThemeField.where(
+ theme_id: theme_ids,
+ target_id: ThemeField.basic_targets.map { |target| Theme.targets[target.to_sym] },
+ name: ThemeField.html_fields,
+ )
+
auto_script_src_extension = { script_src: [] }
html_fields.each(&:ensure_baked!)
doc = html_fields.map(&:value_baked).join("\n")
- Nokogiri::HTML5.fragment(doc).css('script[src]').each do |node|
- src = node['src']
- uri = URI(src)
+ Nokogiri::HTML5
+ .fragment(doc)
+ .css("script[src]")
+ .each do |node|
+ src = node["src"]
+ uri = URI(src)
- next if GlobalSetting.cdn_url && src.starts_with?(GlobalSetting.cdn_url) # Ignore CDN urls (theme-javascripts)
- next if uri.host.nil? # Ignore same-domain scripts (theme-javascripts)
- next if uri.path.nil? # Ignore raw hosts
+ next if GlobalSetting.cdn_url && src.starts_with?(GlobalSetting.cdn_url) # Ignore CDN urls (theme-javascripts)
+ next if uri.host.nil? # Ignore same-domain scripts (theme-javascripts)
+ next if uri.path.nil? # Ignore raw hosts
- uri.query = nil # CSP should not include query part of url
+ uri.query = nil # CSP should not include query part of url
- uri_string = uri.to_s.sub(/^\/\//, '') # Protocol-less CSP should not have // at beginning of URL
+ uri_string = uri.to_s.sub(%r{^//}, "") # Protocol-less CSP should not have // at beginning of URL
- auto_script_src_extension[:script_src] << uri_string
- rescue URI::Error
- # Ignore invalid URI
- end
+ auto_script_src_extension[:script_src] << uri_string
+ rescue URI::Error
+ # Ignore invalid URI
+ end
extensions << auto_script_src_extension
@@ -87,7 +95,7 @@ class ContentSecurityPolicy
def build_theme_extension(entries)
{}.tap do |extension|
entries.each do |entry|
- directive, source = entry.split(':', 2).map(&:strip)
+ directive, source = entry.split(":", 2).map(&:strip)
extension[directive] ||= []
extension[directive] << source
diff --git a/lib/content_security_policy/middleware.rb b/lib/content_security_policy/middleware.rb
index 54ec0f5a656..79ec0834275 100644
--- a/lib/content_security_policy/middleware.rb
+++ b/lib/content_security_policy/middleware.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-require 'content_security_policy'
+require "content_security_policy"
class ContentSecurityPolicy
class Middleware
@@ -19,8 +19,16 @@ class ContentSecurityPolicy
theme_id = env[:resolved_theme_id]
- headers['Content-Security-Policy'] = policy(theme_id, base_url: base_url, path_info: env["PATH_INFO"]) if SiteSetting.content_security_policy
- headers['Content-Security-Policy-Report-Only'] = policy(theme_id, base_url: base_url, path_info: env["PATH_INFO"]) if SiteSetting.content_security_policy_report_only
+ headers["Content-Security-Policy"] = policy(
+ theme_id,
+ base_url: base_url,
+ path_info: env["PATH_INFO"],
+ ) if SiteSetting.content_security_policy
+ headers["Content-Security-Policy-Report-Only"] = policy(
+ theme_id,
+ base_url: base_url,
+ path_info: env["PATH_INFO"],
+ ) if SiteSetting.content_security_policy_report_only
response
end
@@ -30,7 +38,7 @@ class ContentSecurityPolicy
delegate :policy, to: :ContentSecurityPolicy
def html_response?(headers)
- headers['Content-Type'] && headers['Content-Type'] =~ /html/
+ headers["Content-Type"] && headers["Content-Type"] =~ /html/
end
end
end
diff --git a/lib/cooked_post_processor.rb b/lib/cooked_post_processor.rb
index 4d8df118e6a..01463bb7761 100644
--- a/lib/cooked_post_processor.rb
+++ b/lib/cooked_post_processor.rb
@@ -7,7 +7,7 @@ class CookedPostProcessor
include CookedProcessorMixin
LIGHTBOX_WRAPPER_CSS_CLASS = "lightbox-wrapper"
- GIF_SOURCES_REGEXP = /(giphy|tenor)\.com\//
+ GIF_SOURCES_REGEXP = %r{(giphy|tenor)\.com/}
attr_reader :cooking_options, :doc
@@ -61,25 +61,27 @@ class CookedPostProcessor
return if @post.user.blank? || !Guardian.new.can_see?(@post)
BadgeGranter.grant(Badge.find(Badge::FirstEmoji), @post.user, post_id: @post.id) if has_emoji?
- BadgeGranter.grant(Badge.find(Badge::FirstOnebox), @post.user, post_id: @post.id) if @has_oneboxes
- BadgeGranter.grant(Badge.find(Badge::FirstReplyByEmail), @post.user, post_id: @post.id) if @post.is_reply_by_email?
+ if @has_oneboxes
+ BadgeGranter.grant(Badge.find(Badge::FirstOnebox), @post.user, post_id: @post.id)
+ end
+ if @post.is_reply_by_email?
+ BadgeGranter.grant(Badge.find(Badge::FirstReplyByEmail), @post.user, post_id: @post.id)
+ end
end
def post_process_quotes
- @doc.css("aside.quote").each do |q|
- post_number = q['data-post']
- topic_id = q['data-topic']
- if topic_id && post_number
- comparer = QuoteComparer.new(
- topic_id.to_i,
- post_number.to_i,
- q.css('blockquote').text
- )
-
- q['class'] = ((q['class'] || '') + " quote-post-not-found").strip if comparer.missing?
- q['class'] = ((q['class'] || '') + " quote-modified").strip if comparer.modified?
+ @doc
+ .css("aside.quote")
+ .each do |q|
+ post_number = q["data-post"]
+ topic_id = q["data-topic"]
+ if topic_id && post_number
+ comparer = QuoteComparer.new(topic_id.to_i, post_number.to_i, q.css("blockquote").text)
+
+ q["class"] = ((q["class"] || "") + " quote-post-not-found").strip if comparer.missing?
+ q["class"] = ((q["class"] || "") + " quote-modified").strip if comparer.modified?
+ end
end
- end
end
def remove_full_quote_on_direct_reply
@@ -87,66 +89,68 @@ class CookedPostProcessor
return if @post.post_number == 1
return if @doc.xpath("aside[contains(@class, 'quote')]").size != 1
- previous = Post
- .where("post_number < ? AND topic_id = ? AND post_type = ? AND NOT hidden", @post.post_number, @post.topic_id, Post.types[:regular])
- .order("post_number DESC")
- .limit(1)
- .pluck(:cooked)
- .first
+ previous =
+ Post
+ .where(
+ "post_number < ? AND topic_id = ? AND post_type = ? AND NOT hidden",
+ @post.post_number,
+ @post.topic_id,
+ Post.types[:regular],
+ )
+ .order("post_number DESC")
+ .limit(1)
+ .pluck(:cooked)
+ .first
return if previous.blank?
- previous_text = Nokogiri::HTML5::fragment(previous).text.strip
+ previous_text = Nokogiri::HTML5.fragment(previous).text.strip
quoted_text = @doc.css("aside.quote:first-child blockquote").first&.text&.strip || ""
return if previous_text.gsub(/(\s){2,}/, '\1') != quoted_text.gsub(/(\s){2,}/, '\1')
- quote_regexp = /\A\s*\[quote.+\[\/quote\]/im
+ quote_regexp = %r{\A\s*\[quote.+\[/quote\]}im
quoteless_raw = @post.raw.sub(quote_regexp, "").strip
return if @post.raw.strip == quoteless_raw
PostRevisor.new(@post).revise!(
Discourse.system_user,
- {
- raw: quoteless_raw,
- edit_reason: I18n.t(:removed_direct_reply_full_quotes)
- },
+ { raw: quoteless_raw, edit_reason: I18n.t(:removed_direct_reply_full_quotes) },
skip_validations: true,
- bypass_bump: true
+ bypass_bump: true,
)
end
def extract_images
# all images with a src attribute
@doc.css("img[src], img[#{PrettyText::BLOCKED_HOTLINKED_SRC_ATTR}]") -
- # minus data images
- @doc.css("img[src^='data']") -
- # minus emojis
- @doc.css("img.emoji")
+ # minus data images
+ @doc.css("img[src^='data']") -
+ # minus emojis
+ @doc.css("img.emoji")
end
def extract_images_for_post
# all images with a src attribute
@doc.css("img[src]") -
- # minus emojis
- @doc.css("img.emoji") -
- # minus images inside quotes
- @doc.css(".quote img") -
- # minus onebox site icons
- @doc.css("img.site-icon") -
- # minus onebox avatars
- @doc.css("img.onebox-avatar") -
- @doc.css("img.onebox-avatar-inline") -
- # minus github onebox profile images
- @doc.css(".onebox.githubfolder img")
+ # minus emojis
+ @doc.css("img.emoji") -
+ # minus images inside quotes
+ @doc.css(".quote img") -
+ # minus onebox site icons
+ @doc.css("img.site-icon") -
+ # minus onebox avatars
+ @doc.css("img.onebox-avatar") - @doc.css("img.onebox-avatar-inline") -
+ # minus github onebox profile images
+ @doc.css(".onebox.githubfolder img")
end
def convert_to_link!(img)
w, h = img["width"].to_i, img["height"].to_i
- user_width, user_height = (w > 0 && h > 0 && [w, h]) ||
- get_size_from_attributes(img) ||
- get_size_from_image_sizes(img["src"], @opts[:image_sizes])
+ user_width, user_height =
+ (w > 0 && h > 0 && [w, h]) || get_size_from_attributes(img) ||
+ get_size_from_image_sizes(img["src"], @opts[:image_sizes])
limit_size!(img)
@@ -155,7 +159,7 @@ class CookedPostProcessor
upload = Upload.get_from_url(src)
- original_width, original_height = nil
+ original_width, original_height = nil
if (upload.present?)
original_width = upload.width || 0
@@ -172,12 +176,17 @@ class CookedPostProcessor
img.add_class("animated")
end
- return if original_width <= SiteSetting.max_image_width && original_height <= SiteSetting.max_image_height
+ if original_width <= SiteSetting.max_image_width &&
+ original_height <= SiteSetting.max_image_height
+ return
+ end
- user_width, user_height = [original_width, original_height] if user_width.to_i <= 0 && user_height.to_i <= 0
+ user_width, user_height = [original_width, original_height] if user_width.to_i <= 0 &&
+ user_height.to_i <= 0
width, height = user_width, user_height
- crop = SiteSetting.min_ratio_to_crop > 0 && width.to_f / height.to_f < SiteSetting.min_ratio_to_crop
+ crop =
+ SiteSetting.min_ratio_to_crop > 0 && width.to_f / height.to_f < SiteSetting.min_ratio_to_crop
if crop
width, height = ImageSizer.crop(width, height)
@@ -200,7 +209,7 @@ class CookedPostProcessor
return if upload.animated?
- if img.ancestors('.onebox, .onebox-body, .quote').blank? && !img.classes.include?("onebox")
+ if img.ancestors(".onebox, .onebox-body, .quote").blank? && !img.classes.include?("onebox")
add_lightbox!(img, original_width, original_height, upload, cropped: crop)
end
@@ -211,7 +220,7 @@ class CookedPostProcessor
def each_responsive_ratio
SiteSetting
.responsive_post_image_sizes
- .split('|')
+ .split("|")
.map(&:to_f)
.sort
.each { |r| yield r if r > 1 }
@@ -239,13 +248,16 @@ class CookedPostProcessor
srcset << ", #{cooked_url} #{ratio.to_s.sub(/\.0$/, "")}x"
end
- img["srcset"] = "#{UrlHelper.cook_url(img["src"], secure: @post.with_secure_uploads?)}#{srcset}" if srcset.present?
+ img[
+ "srcset"
+ ] = "#{UrlHelper.cook_url(img["src"], secure: @post.with_secure_uploads?)}#{srcset}" if srcset.present?
end
else
img["src"] = upload.url
end
- if !@disable_dominant_color && (color = upload.dominant_color(calculate_if_missing: true).presence)
+ if !@disable_dominant_color &&
+ (color = upload.dominant_color(calculate_if_missing: true).presence)
img["data-dominant-color"] = color
end
end
@@ -261,9 +273,7 @@ class CookedPostProcessor
a = create_link_node("lightbox", src)
img.add_next_sibling(a)
- if upload
- a["data-download-href"] = Discourse.store.download_url(upload)
- end
+ a["data-download-href"] = Discourse.store.download_url(upload) if upload
a.add_child(img)
@@ -309,48 +319,55 @@ class CookedPostProcessor
@post.update_column(:image_upload_id, upload.id) # post
if @post.is_first_post? # topic
@post.topic.update_column(:image_upload_id, upload.id)
- extra_sizes = ThemeModifierHelper.new(theme_ids: Theme.user_selectable.pluck(:id)).topic_thumbnail_sizes
+ extra_sizes =
+ ThemeModifierHelper.new(theme_ids: Theme.user_selectable.pluck(:id)).topic_thumbnail_sizes
@post.topic.generate_thumbnails!(extra_sizes: extra_sizes)
end
else
@post.update_column(:image_upload_id, nil) if @post.image_upload_id
- @post.topic.update_column(:image_upload_id, nil) if @post.topic.image_upload_id && @post.is_first_post?
+ if @post.topic.image_upload_id && @post.is_first_post?
+ @post.topic.update_column(:image_upload_id, nil)
+ end
nil
end
end
def optimize_urls
- %w{href data-download-href}.each do |selector|
- @doc.css("a[#{selector}]").each do |a|
- a[selector] = UrlHelper.cook_url(a[selector].to_s)
- end
+ %w[href data-download-href].each do |selector|
+ @doc.css("a[#{selector}]").each { |a| a[selector] = UrlHelper.cook_url(a[selector].to_s) }
end
- %w{src}.each do |selector|
- @doc.css("img[#{selector}]").each do |img|
- custom_emoji = img["class"]&.include?("emoji-custom") && Emoji.custom?(img["title"])
- img[selector] = UrlHelper.cook_url(
- img[selector].to_s, secure: @post.with_secure_uploads? && !custom_emoji
- )
- end
+ %w[src].each do |selector|
+ @doc
+ .css("img[#{selector}]")
+ .each do |img|
+ custom_emoji = img["class"]&.include?("emoji-custom") && Emoji.custom?(img["title"])
+ img[selector] = UrlHelper.cook_url(
+ img[selector].to_s,
+ secure: @post.with_secure_uploads? && !custom_emoji,
+ )
+ end
end
end
def remove_user_ids
- @doc.css("a[href]").each do |a|
- uri = begin
- URI(a["href"])
- rescue URI::Error
- next
+ @doc
+ .css("a[href]")
+ .each do |a|
+ uri =
+ begin
+ URI(a["href"])
+ rescue URI::Error
+ next
+ end
+ next if uri.hostname != Discourse.current_hostname
+
+ query = Rack::Utils.parse_nested_query(uri.query)
+ next if !query.delete("u")
+
+ uri.query = query.map { |k, v| "#{k}=#{v}" }.join("&").presence
+ a["href"] = uri.to_s
end
- next if uri.hostname != Discourse.current_hostname
-
- query = Rack::Utils.parse_nested_query(uri.query)
- next if !query.delete("u")
-
- uri.query = query.map { |k, v| "#{k}=#{v}" }.join("&").presence
- a["href"] = uri.to_s
- end
end
def enforce_nofollow
@@ -369,13 +386,14 @@ class CookedPostProcessor
def process_hotlinked_image(img)
@hotlinked_map ||= @post.post_hotlinked_media.preload(:upload).map { |r| [r.url, r] }.to_h
- normalized_src = PostHotlinkedMedia.normalize_src(img["src"] || img[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR])
+ normalized_src =
+ PostHotlinkedMedia.normalize_src(img["src"] || img[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR])
info = @hotlinked_map[normalized_src]
still_an_image = true
if info&.too_large?
- if img.ancestors('.onebox, .onebox-body').blank?
+ if img.ancestors(".onebox, .onebox-body").blank?
add_large_image_placeholder!(img)
else
img.remove
@@ -383,7 +401,7 @@ class CookedPostProcessor
still_an_image = false
elsif info&.download_failed?
- if img.ancestors('.onebox, .onebox-body').blank?
+ if img.ancestors(".onebox, .onebox-body").blank?
add_broken_image_placeholder!(img)
else
img.remove
@@ -399,28 +417,29 @@ class CookedPostProcessor
end
def add_blocked_hotlinked_media_placeholders
- @doc.css([
- "[#{PrettyText::BLOCKED_HOTLINKED_SRC_ATTR}]",
- "[#{PrettyText::BLOCKED_HOTLINKED_SRCSET_ATTR}]",
- ].join(',')).each do |el|
- src = el[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR] ||
- el[PrettyText::BLOCKED_HOTLINKED_SRCSET_ATTR]&.split(',')&.first&.split(' ')&.first
-
- if el.name == "img"
- add_blocked_hotlinked_image_placeholder!(el)
- next
- end
+ @doc
+ .css(
+ [
+ "[#{PrettyText::BLOCKED_HOTLINKED_SRC_ATTR}]",
+ "[#{PrettyText::BLOCKED_HOTLINKED_SRCSET_ATTR}]",
+ ].join(","),
+ )
+ .each do |el|
+ src =
+ el[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR] ||
+ el[PrettyText::BLOCKED_HOTLINKED_SRCSET_ATTR]&.split(",")&.first&.split(" ")&.first
+
+ if el.name == "img"
+ add_blocked_hotlinked_image_placeholder!(el)
+ next
+ end
- if ["video", "audio"].include?(el.parent.name)
- el = el.parent
- end
+ el = el.parent if %w[video audio].include?(el.parent.name)
- if el.parent.classes.include?("video-container")
- el = el.parent
- end
+ el = el.parent if el.parent.classes.include?("video-container")
- add_blocked_hotlinked_media_placeholder!(el, src)
- end
+ add_blocked_hotlinked_media_placeholder!(el, src)
+ end
end
def is_svg?(img)
@@ -431,6 +450,6 @@ class CookedPostProcessor
nil
end
- File.extname(path) == '.svg' if path
+ File.extname(path) == ".svg" if path
end
end
diff --git a/lib/cooked_processor_mixin.rb b/lib/cooked_processor_mixin.rb
index 68add8893fa..4c2fba4c17a 100644
--- a/lib/cooked_processor_mixin.rb
+++ b/lib/cooked_processor_mixin.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module CookedProcessorMixin
-
def post_process_oneboxes
limit = SiteSetting.max_oneboxes_per_post - @doc.css("aside.onebox, a.inline-onebox").size
oneboxes = {}
@@ -14,7 +13,7 @@ module CookedProcessorMixin
if skip_onebox
if is_onebox
- element.remove_class('onebox')
+ element.remove_class("onebox")
else
remove_inline_onebox_loading_class(element)
end
@@ -26,11 +25,13 @@ module CookedProcessorMixin
map[url] = true
if is_onebox
- onebox = Oneboxer.onebox(url,
- invalidate_oneboxes: !!@opts[:invalidate_oneboxes],
- user_id: @model&.user_id,
- category_id: @category_id
- )
+ onebox =
+ Oneboxer.onebox(
+ url,
+ invalidate_oneboxes: !!@opts[:invalidate_oneboxes],
+ user_id: @model&.user_id,
+ category_id: @category_id,
+ )
@has_oneboxes = true if onebox.present?
onebox
@@ -56,7 +57,7 @@ module CookedProcessorMixin
# and wrap in a div
limit_size!(img)
- next if img["class"]&.include?('onebox-avatar')
+ next if img["class"]&.include?("onebox-avatar")
parent = parent&.parent if parent&.name == "a"
parent_class = parent && parent["class"]
@@ -84,12 +85,18 @@ module CookedProcessorMixin
if width < 64 && height < 64
img["class"] = img["class"].to_s + " onebox-full-image"
else
- img.delete('width')
- img.delete('height')
- new_parent = img.add_next_sibling("<div class='aspect-image' style='--aspect-ratio:#{width}/#{height};'/>")
+ img.delete("width")
+ img.delete("height")
+ new_parent =
+ img.add_next_sibling(
+ "<div class='aspect-image' style='--aspect-ratio:#{width}/#{height};'/>",
+ )
new_parent.first.add_child(img)
end
- elsif (parent_class&.include?("instagram-images") || parent_class&.include?("tweet-images") || parent_class&.include?("scale-images")) && width > 0 && height > 0
+ elsif (
+ parent_class&.include?("instagram-images") || parent_class&.include?("tweet-images") ||
+ parent_class&.include?("scale-images")
+ ) && width > 0 && height > 0
img.remove_attribute("width")
img.remove_attribute("height")
parent["class"] = "aspect-image-full-size"
@@ -98,16 +105,18 @@ module CookedProcessorMixin
end
if @omit_nofollow || !SiteSetting.add_rel_nofollow_to_user_content
- @doc.css(".onebox-body a[rel], .onebox a[rel]").each do |a|
- rel_values = a['rel'].split(' ').map(&:downcase)
- rel_values.delete('nofollow')
- rel_values.delete('ugc')
- if rel_values.blank?
- a.remove_attribute("rel")
- else
- a["rel"] = rel_values.join(' ')
+ @doc
+ .css(".onebox-body a[rel], .onebox a[rel]")
+ .each do |a|
+ rel_values = a["rel"].split(" ").map(&:downcase)
+ rel_values.delete("nofollow")
+ rel_values.delete("ugc")
+ if rel_values.blank?
+ a.remove_attribute("rel")
+ else
+ a["rel"] = rel_values.join(" ")
+ end
end
- end
end
end
@@ -116,9 +125,9 @@ module CookedProcessorMixin
# 1) the width/height attributes
# 2) the dimension from the preview (image_sizes)
# 3) the dimension of the original image (HTTP request)
- w, h = get_size_from_attributes(img) ||
- get_size_from_image_sizes(img["src"], @opts[:image_sizes]) ||
- get_size(img["src"])
+ w, h =
+ get_size_from_attributes(img) || get_size_from_image_sizes(img["src"], @opts[:image_sizes]) ||
+ get_size(img["src"])
# limit the size of the thumbnail
img["width"], img["height"] = ImageSizer.resize(w, h)
@@ -126,7 +135,7 @@ module CookedProcessorMixin
def get_size_from_attributes(img)
w, h = img["width"].to_i, img["height"].to_i
- return [w, h] unless w <= 0 || h <= 0
+ return w, h unless w <= 0 || h <= 0
# if only width or height are specified attempt to scale image
if w > 0 || h > 0
w = w.to_f
@@ -149,9 +158,9 @@ module CookedProcessorMixin
return unless image_sizes.present?
image_sizes.each do |image_size|
url, size = image_size[0], image_size[1]
- if url && src && url.include?(src) &&
- size && size["width"].to_i > 0 && size["height"].to_i > 0
- return [size["width"], size["height"]]
+ if url && src && url.include?(src) && size && size["width"].to_i > 0 &&
+ size["height"].to_i > 0
+ return size["width"], size["height"]
end
end
nil
@@ -165,7 +174,7 @@ module CookedProcessorMixin
return @size_cache[url] if @size_cache.has_key?(url)
absolute_url = url
- absolute_url = Discourse.base_url_no_prefix + absolute_url if absolute_url =~ /^\/[^\/]/
+ absolute_url = Discourse.base_url_no_prefix + absolute_url if absolute_url =~ %r{^/[^/]}
return unless absolute_url
@@ -186,14 +195,13 @@ module CookedProcessorMixin
else
@size_cache[url] = FastImage.size(absolute_url)
end
-
rescue Zlib::BufError, URI::Error, OpenSSL::SSL::SSLError
# FastImage.size raises BufError for some gifs, leave it.
end
def is_valid_image_url?(url)
uri = URI.parse(url)
- %w(http https).include? uri.scheme
+ %w[http https].include? uri.scheme
rescue URI::Error
end
@@ -217,9 +225,12 @@ module CookedProcessorMixin
"help",
I18n.t(
"upload.placeholders.too_large_humanized",
- max_size: ActiveSupport::NumberHelper.number_to_human_size(SiteSetting.max_image_size_kb.kilobytes)
- )
- )
+ max_size:
+ ActiveSupport::NumberHelper.number_to_human_size(
+ SiteSetting.max_image_size_kb.kilobytes,
+ ),
+ ),
+ ),
)
# Only if the image is already linked
@@ -227,7 +238,7 @@ module CookedProcessorMixin
parent = placeholder.parent
parent.add_next_sibling(placeholder)
- if parent.name == 'a' && parent["href"].present?
+ if parent.name == "a" && parent["href"].present?
if url == parent["href"]
parent.remove
else
@@ -295,12 +306,13 @@ module CookedProcessorMixin
end
def process_inline_onebox(element)
- inline_onebox = InlineOneboxer.lookup(
- element.attributes["href"].value,
- invalidate: !!@opts[:invalidate_oneboxes],
- user_id: @model&.user_id,
- category_id: @category_id
- )
+ inline_onebox =
+ InlineOneboxer.lookup(
+ element.attributes["href"].value,
+ invalidate: !!@opts[:invalidate_oneboxes],
+ user_id: @model&.user_id,
+ category_id: @category_id,
+ )
if title = inline_onebox&.dig(:title)
element.children = CGI.escapeHTML(title)
diff --git a/lib/crawler_detection.rb b/lib/crawler_detection.rb
index 0b90dc0acb6..f926d3455df 100644
--- a/lib/crawler_detection.rb
+++ b/lib/crawler_detection.rb
@@ -4,7 +4,7 @@ module CrawlerDetection
WAYBACK_MACHINE_URL = "archive.org"
def self.to_matcher(string, type: nil)
- escaped = string.split('|').map { |agent| Regexp.escape(agent) }.join('|')
+ escaped = string.split("|").map { |agent| Regexp.escape(agent) }.join("|")
if type == :real && Rails.env == "test"
# we need this bypass so we properly render views
@@ -15,18 +15,33 @@ module CrawlerDetection
end
def self.crawler?(user_agent, via_header = nil)
- return true if user_agent.nil? || user_agent&.include?(WAYBACK_MACHINE_URL) || via_header&.include?(WAYBACK_MACHINE_URL)
+ if user_agent.nil? || user_agent&.include?(WAYBACK_MACHINE_URL) ||
+ via_header&.include?(WAYBACK_MACHINE_URL)
+ return true
+ end
# this is done to avoid regenerating regexes
@non_crawler_matchers ||= {}
@matchers ||= {}
- possibly_real = (@non_crawler_matchers[SiteSetting.non_crawler_user_agents] ||= to_matcher(SiteSetting.non_crawler_user_agents, type: :real))
+ possibly_real =
+ (
+ @non_crawler_matchers[SiteSetting.non_crawler_user_agents] ||= to_matcher(
+ SiteSetting.non_crawler_user_agents,
+ type: :real,
+ )
+ )
if user_agent.match?(possibly_real)
- known_bots = (@matchers[SiteSetting.crawler_user_agents] ||= to_matcher(SiteSetting.crawler_user_agents))
+ known_bots =
+ (@matchers[SiteSetting.crawler_user_agents] ||= to_matcher(SiteSetting.crawler_user_agents))
if user_agent.match?(known_bots)
- bypass = (@matchers[SiteSetting.crawler_check_bypass_agents] ||= to_matcher(SiteSetting.crawler_check_bypass_agents))
+ bypass =
+ (
+ @matchers[SiteSetting.crawler_check_bypass_agents] ||= to_matcher(
+ SiteSetting.crawler_check_bypass_agents,
+ )
+ )
!user_agent.match?(bypass)
else
false
@@ -34,30 +49,40 @@ module CrawlerDetection
else
true
end
-
end
def self.show_browser_update?(user_agent)
return false if SiteSetting.browser_update_user_agents.blank?
@browser_update_matchers ||= {}
- matcher = @browser_update_matchers[SiteSetting.browser_update_user_agents] ||= to_matcher(SiteSetting.browser_update_user_agents)
+ matcher =
+ @browser_update_matchers[SiteSetting.browser_update_user_agents] ||= to_matcher(
+ SiteSetting.browser_update_user_agents,
+ )
user_agent.match?(matcher)
end
# Given a user_agent that returns true from crawler?, should its request be allowed?
def self.allow_crawler?(user_agent)
- return true if SiteSetting.allowed_crawler_user_agents.blank? &&
- SiteSetting.blocked_crawler_user_agents.blank?
+ if SiteSetting.allowed_crawler_user_agents.blank? &&
+ SiteSetting.blocked_crawler_user_agents.blank?
+ return true
+ end
@allowlisted_matchers ||= {}
@blocklisted_matchers ||= {}
if SiteSetting.allowed_crawler_user_agents.present?
- allowlisted = @allowlisted_matchers[SiteSetting.allowed_crawler_user_agents] ||= to_matcher(SiteSetting.allowed_crawler_user_agents)
+ allowlisted =
+ @allowlisted_matchers[SiteSetting.allowed_crawler_user_agents] ||= to_matcher(
+ SiteSetting.allowed_crawler_user_agents,
+ )
!user_agent.nil? && user_agent.match?(allowlisted)
else
- blocklisted = @blocklisted_matchers[SiteSetting.blocked_crawler_user_agents] ||= to_matcher(SiteSetting.blocked_crawler_user_agents)
+ blocklisted =
+ @blocklisted_matchers[SiteSetting.blocked_crawler_user_agents] ||= to_matcher(
+ SiteSetting.blocked_crawler_user_agents,
+ )
user_agent.nil? || !user_agent.match?(blocklisted)
end
end
diff --git a/lib/csrf_token_verifier.rb b/lib/csrf_token_verifier.rb
index 56ed911a7f0..8736b749df1 100644
--- a/lib/csrf_token_verifier.rb
+++ b/lib/csrf_token_verifier.rb
@@ -2,7 +2,8 @@
# Provides a way to check a CSRF token outside of a controller
class CSRFTokenVerifier
- class InvalidCSRFToken < StandardError; end
+ class InvalidCSRFToken < StandardError
+ end
include ActiveSupport::Configurable
include ActionController::RequestForgeryProtection
@@ -18,9 +19,7 @@ class CSRFTokenVerifier
def call(env)
@request = ActionDispatch::Request.new(env.dup)
- unless verified_request?
- raise InvalidCSRFToken
- end
+ raise InvalidCSRFToken unless verified_request?
end
public :form_authenticity_token
diff --git a/lib/current_user.rb b/lib/current_user.rb
index cf84adfb278..fdf78431981 100644
--- a/lib/current_user.rb
+++ b/lib/current_user.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module CurrentUser
-
def self.has_auth_cookie?(env)
Discourse.current_user_provider.new(env).has_auth_cookie?
end
@@ -45,5 +44,4 @@ module CurrentUser
def current_user_provider
@current_user_provider ||= Discourse.current_user_provider.new(request.env)
end
-
end
diff --git a/lib/db_helper.rb b/lib/db_helper.rb
index 6bc79b044ef..29117934d86 100644
--- a/lib/db_helper.rb
+++ b/lib/db_helper.rb
@@ -3,7 +3,6 @@
require "migration/base_dropper"
class DbHelper
-
REMAP_SQL ||= <<~SQL
SELECT table_name::text, column_name::text, character_maximum_length
FROM information_schema.columns
@@ -19,24 +18,33 @@ class DbHelper
WHERE trigger_name LIKE '%_readonly'
SQL
- TRUNCATABLE_COLUMNS ||= [
- 'topic_links.url'
- ]
-
- def self.remap(from, to, anchor_left: false, anchor_right: false, excluded_tables: [], verbose: false)
- like = "#{anchor_left ? '' : "%"}#{from}#{anchor_right ? '' : "%"}"
+ TRUNCATABLE_COLUMNS ||= ["topic_links.url"]
+
+ def self.remap(
+ from,
+ to,
+ anchor_left: false,
+ anchor_right: false,
+ excluded_tables: [],
+ verbose: false
+ )
+ like = "#{anchor_left ? "" : "%"}#{from}#{anchor_right ? "" : "%"}"
text_columns = find_text_columns(excluded_tables)
text_columns.each do |table, columns|
- set = columns.map do |column|
- replace = "REPLACE(\"#{column[:name]}\", :from, :to)"
- replace = truncate(replace, table, column)
- "\"#{column[:name]}\" = #{replace}"
- end.join(", ")
-
- where = columns.map do |column|
- "\"#{column[:name]}\" IS NOT NULL AND \"#{column[:name]}\" LIKE :like"
- end.join(" OR ")
+ set =
+ columns
+ .map do |column|
+ replace = "REPLACE(\"#{column[:name]}\", :from, :to)"
+ replace = truncate(replace, table, column)
+ "\"#{column[:name]}\" = #{replace}"
+ end
+ .join(", ")
+
+ where =
+ columns
+ .map { |column| "\"#{column[:name]}\" IS NOT NULL AND \"#{column[:name]}\" LIKE :like" }
+ .join(" OR ")
rows = DB.exec(<<~SQL, from: from, to: to, like: like)
UPDATE \"#{table}\"
@@ -50,19 +58,32 @@ class DbHelper
finish!
end
- def self.regexp_replace(pattern, replacement, flags: "gi", match: "~*", excluded_tables: [], verbose: false)
+ def self.regexp_replace(
+ pattern,
+ replacement,
+ flags: "gi",
+ match: "~*",
+ excluded_tables: [],
+ verbose: false
+ )
text_columns = find_text_columns(excluded_tables)
text_columns.each do |table, columns|
- set = columns.map do |column|
- replace = "REGEXP_REPLACE(\"#{column[:name]}\", :pattern, :replacement, :flags)"
- replace = truncate(replace, table, column)
- "\"#{column[:name]}\" = #{replace}"
- end.join(", ")
-
- where = columns.map do |column|
- "\"#{column[:name]}\" IS NOT NULL AND \"#{column[:name]}\" #{match} :pattern"
- end.join(" OR ")
+ set =
+ columns
+ .map do |column|
+ replace = "REGEXP_REPLACE(\"#{column[:name]}\", :pattern, :replacement, :flags)"
+ replace = truncate(replace, table, column)
+ "\"#{column[:name]}\" = #{replace}"
+ end
+ .join(", ")
+
+ where =
+ columns
+ .map do |column|
+ "\"#{column[:name]}\" IS NOT NULL AND \"#{column[:name]}\" #{match} :pattern"
+ end
+ .join(" OR ")
rows = DB.exec(<<~SQL, pattern: pattern, replacement: replacement, flags: flags, match: match)
UPDATE \"#{table}\"
@@ -78,23 +99,25 @@ class DbHelper
def self.find(needle, anchor_left: false, anchor_right: false, excluded_tables: [])
found = {}
- like = "#{anchor_left ? '' : "%"}#{needle}#{anchor_right ? '' : "%"}"
+ like = "#{anchor_left ? "" : "%"}#{needle}#{anchor_right ? "" : "%"}"
- DB.query(REMAP_SQL).each do |r|
- next if excluded_tables.include?(r.table_name)
+ DB
+ .query(REMAP_SQL)
+ .each do |r|
+ next if excluded_tables.include?(r.table_name)
- rows = DB.query(<<~SQL, like: like)
+ rows = DB.query(<<~SQL, like: like)
SELECT \"#{r.column_name}\"
FROM \"#{r.table_name}\"
WHERE \""#{r.column_name}"\" LIKE :like
SQL
- if rows.size > 0
- found["#{r.table_name}.#{r.column_name}"] = rows.map do |row|
- row.public_send(r.column_name)
+ if rows.size > 0
+ found["#{r.table_name}.#{r.column_name}"] = rows.map do |row|
+ row.public_send(r.column_name)
+ end
end
end
- end
found
end
@@ -112,16 +135,21 @@ class DbHelper
triggers = DB.query(TRIGGERS_SQL).map(&:trigger_name).to_set
text_columns = Hash.new { |h, k| h[k] = [] }
- DB.query(REMAP_SQL).each do |r|
- next if excluded_tables.include?(r.table_name) ||
- triggers.include?(Migration::BaseDropper.readonly_trigger_name(r.table_name, r.column_name)) ||
- triggers.include?(Migration::BaseDropper.readonly_trigger_name(r.table_name))
+ DB
+ .query(REMAP_SQL)
+ .each do |r|
+ if excluded_tables.include?(r.table_name) ||
+ triggers.include?(
+ Migration::BaseDropper.readonly_trigger_name(r.table_name, r.column_name),
+ ) || triggers.include?(Migration::BaseDropper.readonly_trigger_name(r.table_name))
+ next
+ end
- text_columns[r.table_name] << {
- name: r.column_name,
- max_length: r.character_maximum_length
- }
- end
+ text_columns[r.table_name] << {
+ name: r.column_name,
+ max_length: r.character_maximum_length,
+ }
+ end
text_columns
end
diff --git a/lib/demon/base.rb b/lib/demon/base.rb
index 397fb5d0b08..c49265a4cfb 100644
--- a/lib/demon/base.rb
+++ b/lib/demon/base.rb
@@ -1,26 +1,22 @@
# frozen_string_literal: true
-module Demon; end
+module Demon
+end
# intelligent fork based demonizer
class Demon::Base
-
def self.demons
@demons
end
def self.start(count = 1, verbose: false)
@demons ||= {}
- count.times do |i|
- (@demons["#{prefix}_#{i}"] ||= new(i, verbose: verbose)).start
- end
+ count.times { |i| (@demons["#{prefix}_#{i}"] ||= new(i, verbose: verbose)).start }
end
def self.stop
return unless @demons
- @demons.values.each do |demon|
- demon.stop
- end
+ @demons.values.each { |demon| demon.stop }
end
def self.restart
@@ -32,16 +28,12 @@ class Demon::Base
end
def self.ensure_running
- @demons.values.each do |demon|
- demon.ensure_running
- end
+ @demons.values.each { |demon| demon.ensure_running }
end
def self.kill(signal)
return unless @demons
- @demons.values.each do |demon|
- demon.kill(signal)
- end
+ @demons.values.each { |demon| demon.kill(signal) }
end
attr_reader :pid, :parent_pid, :started, :index
@@ -83,18 +75,27 @@ class Demon::Base
if @pid
Process.kill(stop_signal, @pid)
- wait_for_stop = lambda {
- timeout = @stop_timeout
+ wait_for_stop =
+ lambda do
+ timeout = @stop_timeout
+
+ while alive? && timeout > 0
+ timeout -= (@stop_timeout / 10.0)
+ sleep(@stop_timeout / 10.0)
+ begin
+ Process.waitpid(@pid, Process::WNOHANG)
+ rescue StandardError
+ -1
+ end
+ end
- while alive? && timeout > 0
- timeout -= (@stop_timeout / 10.0)
- sleep(@stop_timeout / 10.0)
- Process.waitpid(@pid, Process::WNOHANG) rescue -1
+ begin
+ Process.waitpid(@pid, Process::WNOHANG)
+ rescue StandardError
+ -1
+ end
end
- Process.waitpid(@pid, Process::WNOHANG) rescue -1
- }
-
wait_for_stop.call
if alive?
@@ -118,7 +119,12 @@ class Demon::Base
return
end
- dead = Process.waitpid(@pid, Process::WNOHANG) rescue -1
+ dead =
+ begin
+ Process.waitpid(@pid, Process::WNOHANG)
+ rescue StandardError
+ -1
+ end
if dead
STDERR.puts "Detected dead worker #{@pid}, restarting..."
@pid = nil
@@ -141,21 +147,20 @@ class Demon::Base
end
def run
- @pid = fork do
- Process.setproctitle("discourse #{self.class.prefix}")
- monitor_parent
- establish_app
- after_fork
- end
+ @pid =
+ fork do
+ Process.setproctitle("discourse #{self.class.prefix}")
+ monitor_parent
+ establish_app
+ after_fork
+ end
write_pid_file
end
def already_running?
if File.exist? pid_file
pid = File.read(pid_file).to_i
- if Demon::Base.alive?(pid)
- return pid
- end
+ return pid if Demon::Base.alive?(pid)
end
nil
@@ -164,24 +169,20 @@ class Demon::Base
def self.alive?(pid)
Process.kill(0, pid)
true
- rescue
+ rescue StandardError
false
end
private
def verbose(msg)
- if @verbose
- puts msg
- end
+ puts msg if @verbose
end
def write_pid_file
verbose("writing pid file #{pid_file} for #{@pid}")
FileUtils.mkdir_p(@rails_root + "tmp/pids")
- File.open(pid_file, 'w') do |f|
- f.write(@pid)
- end
+ File.open(pid_file, "w") { |f| f.write(@pid) }
end
def delete_pid_file
diff --git a/lib/demon/email_sync.rb b/lib/demon/email_sync.rb
index 12fedc5724d..93a627c0330 100644
--- a/lib/demon/email_sync.rb
+++ b/lib/demon/email_sync.rb
@@ -36,15 +36,20 @@ class Demon::EmailSync < ::Demon::Base
status = nil
idle = false
- while @running && group.reload.imap_mailbox_name.present? do
+ while @running && group.reload.imap_mailbox_name.present?
ImapSyncLog.debug("Processing mailbox for group #{group.name} in db #{db}", group)
- status = syncer.process(
- idle: syncer.can_idle? && status && status[:remaining] == 0,
- old_emails_limit: status && status[:remaining] > 0 ? 0 : nil,
- )
+ status =
+ syncer.process(
+ idle: syncer.can_idle? && status && status[:remaining] == 0,
+ old_emails_limit: status && status[:remaining] > 0 ? 0 : nil,
+ )
if !syncer.can_idle? && status[:remaining] == 0
- ImapSyncLog.debug("Going to sleep for group #{group.name} in db #{db} to wait for new emails", group, db: false)
+ ImapSyncLog.debug(
+ "Going to sleep for group #{group.name} in db #{db} to wait for new emails",
+ group,
+ db: false,
+ )
# Thread goes into sleep for a bit so it is better to return any
# connection back to the pool.
@@ -66,11 +71,7 @@ class Demon::EmailSync < ::Demon::Base
# synchronization primitives available anyway).
@running = false
- @sync_data.each do |db, sync_data|
- sync_data.each do |_, data|
- kill_and_disconnect!(data)
- end
- end
+ @sync_data.each { |db, sync_data| sync_data.each { |_, data| kill_and_disconnect!(data) } }
exit 0
end
@@ -89,9 +90,9 @@ class Demon::EmailSync < ::Demon::Base
@sync_data = {}
@sync_lock = Mutex.new
- trap('INT') { kill_threads }
- trap('TERM') { kill_threads }
- trap('HUP') { kill_threads }
+ trap("INT") { kill_threads }
+ trap("TERM") { kill_threads }
+ trap("HUP") { kill_threads }
while @running
Discourse.redis.set(HEARTBEAT_KEY, Time.now.to_i, ex: HEARTBEAT_INTERVAL)
@@ -101,9 +102,7 @@ class Demon::EmailSync < ::Demon::Base
@sync_data.filter! do |db, sync_data|
next true if all_dbs.include?(db)
- sync_data.each do |_, data|
- kill_and_disconnect!(data)
- end
+ sync_data.each { |_, data| kill_and_disconnect!(data) }
false
end
@@ -121,7 +120,10 @@ class Demon::EmailSync < ::Demon::Base
next true if groups[group_id] && data[:thread]&.alive? && !data[:syncer]&.disconnected?
if !groups[group_id]
- ImapSyncLog.warn("Killing thread for group because mailbox is no longer synced", group_id)
+ ImapSyncLog.warn(
+ "Killing thread for group because mailbox is no longer synced",
+ group_id,
+ )
else
ImapSyncLog.warn("Thread for group is dead", group_id)
end
@@ -133,12 +135,13 @@ class Demon::EmailSync < ::Demon::Base
# Spawn new threads for groups that are now synchronized.
groups.each do |group_id, group|
if !@sync_data[db][group_id]
- ImapSyncLog.debug("Starting thread for group #{group.name} mailbox #{group.imap_mailbox_name}", group, db: false)
+ ImapSyncLog.debug(
+ "Starting thread for group #{group.name} mailbox #{group.imap_mailbox_name}",
+ group,
+ db: false,
+ )
- @sync_data[db][group_id] = {
- thread: start_thread(db, group),
- syncer: nil
- }
+ @sync_data[db][group_id] = { thread: start_thread(db, group), syncer: nil }
end
end
end
diff --git a/lib/demon/rails_autospec.rb b/lib/demon/rails_autospec.rb
index babf5a5e7e1..78f0782046a 100644
--- a/lib/demon/rails_autospec.rb
+++ b/lib/demon/rails_autospec.rb
@@ -3,7 +3,6 @@
require "demon/base"
class Demon::RailsAutospec < Demon::Base
-
def self.prefix
"rails-autospec"
end
@@ -17,15 +16,10 @@ class Demon::RailsAutospec < Demon::Base
def after_fork
require "rack"
ENV["RAILS_ENV"] = "test"
- Rack::Server.start(
- config: "config.ru",
- AccessLog: [],
- Port: ENV["TEST_SERVER_PORT"] || 60099,
- )
+ Rack::Server.start(config: "config.ru", AccessLog: [], Port: ENV["TEST_SERVER_PORT"] || 60_099)
rescue => e
STDERR.puts e.message
STDERR.puts e.backtrace.join("\n")
exit 1
end
-
end
diff --git a/lib/demon/sidekiq.rb b/lib/demon/sidekiq.rb
index ed7556d299d..1c1776d80ca 100644
--- a/lib/demon/sidekiq.rb
+++ b/lib/demon/sidekiq.rb
@@ -3,7 +3,6 @@
require "demon/base"
class Demon::Sidekiq < ::Demon::Base
-
def self.prefix
"sidekiq"
end
@@ -26,7 +25,7 @@ class Demon::Sidekiq < ::Demon::Base
Demon::Sidekiq.after_fork&.call
puts "Loading Sidekiq in process id #{Process.pid}"
- require 'sidekiq/cli'
+ require "sidekiq/cli"
cli = Sidekiq::CLI.instance
# Unicorn uses USR1 to indicate that log files have been rotated
@@ -38,10 +37,10 @@ class Demon::Sidekiq < ::Demon::Base
options = ["-c", GlobalSetting.sidekiq_workers.to_s]
- [['critical', 8], ['default', 4], ['low', 2], ['ultra_low', 1]].each do |queue_name, weight|
+ [["critical", 8], ["default", 4], ["low", 2], ["ultra_low", 1]].each do |queue_name, weight|
custom_queue_hostname = ENV["UNICORN_SIDEKIQ_#{queue_name.upcase}_QUEUE_HOSTNAME"]
- if !custom_queue_hostname || custom_queue_hostname.split(',').include?(Discourse.os_hostname)
+ if !custom_queue_hostname || custom_queue_hostname.split(",").include?(Discourse.os_hostname)
options << "-q"
options << "#{queue_name},#{weight}"
end
@@ -49,7 +48,7 @@ class Demon::Sidekiq < ::Demon::Base
# Sidekiq not as high priority as web, in this environment it is forked so a web is very
# likely running
- Discourse::Utils.execute_command('renice', '-n', '5', '-p', Process.pid.to_s)
+ Discourse::Utils.execute_command("renice", "-n", "5", "-p", Process.pid.to_s)
cli.parse(options)
load Rails.root + "config/initializers/100-sidekiq.rb"
@@ -59,5 +58,4 @@ class Demon::Sidekiq < ::Demon::Base
STDERR.puts e.backtrace.join("\n")
exit 1
end
-
end
diff --git a/lib/directory_helper.rb b/lib/directory_helper.rb
index a41b117a397..80b2865a85a 100644
--- a/lib/directory_helper.rb
+++ b/lib/directory_helper.rb
@@ -1,24 +1,23 @@
# frozen_string_literal: true
module DirectoryHelper
-
def tmp_directory(prefix)
directory_cache[prefix] ||= begin
- f = File.join(Rails.root, 'tmp', Time.now.strftime("#{prefix}%Y%m%d%H%M%S"))
+ f = File.join(Rails.root, "tmp", Time.now.strftime("#{prefix}%Y%m%d%H%M%S"))
FileUtils.mkdir_p(f) unless Dir[f].present?
f
end
end
def remove_tmp_directory(prefix)
- tmp_directory_name = directory_cache[prefix] || ''
+ tmp_directory_name = directory_cache[prefix] || ""
directory_cache.delete(prefix)
FileUtils.rm_rf(tmp_directory_name) if Dir[tmp_directory_name].present?
end
private
+
def directory_cache
@directory_cache ||= {}
end
-
end
diff --git a/lib/discourse.rb b/lib/discourse.rb
index 68c2e6f2104..caba3ba4cef 100644
--- a/lib/discourse.rb
+++ b/lib/discourse.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
-require 'cache'
-require 'open3'
-require 'plugin/instance'
-require 'version'
+require "cache"
+require "open3"
+require "plugin/instance"
+require "version"
module Discourse
DB_POST_MIGRATE_PATH ||= "db/post_migrate"
REQUESTED_HOSTNAME ||= "REQUESTED_HOSTNAME"
class Utils
- URI_REGEXP ||= URI.regexp(%w{http https})
+ URI_REGEXP ||= URI.regexp(%w[http https])
# Usage:
# Discourse::Utils.execute_command("pwd", chdir: 'mydirectory')
@@ -22,7 +22,9 @@ module Discourse
runner = CommandRunner.new(**args)
if block_given?
- raise RuntimeError.new("Cannot pass command and block to execute_command") if command.present?
+ if command.present?
+ raise RuntimeError.new("Cannot pass command and block to execute_command")
+ end
yield runner
else
runner.exec(*command)
@@ -33,33 +35,32 @@ module Discourse
logs.join("\n")
end
- def self.logs_markdown(logs, user:, filename: 'log.txt')
+ def self.logs_markdown(logs, user:, filename: "log.txt")
# Reserve 250 characters for the rest of the text
max_logs_length = SiteSetting.max_post_length - 250
pretty_logs = Discourse::Utils.pretty_logs(logs)
# If logs are short, try to inline them
- if pretty_logs.size < max_logs_length
- return <<~TEXT
+ return <<~TEXT if pretty_logs.size < max_logs_length
```text
#{pretty_logs}
```
TEXT
- end
# Try to create an upload for the logs
- upload = Dir.mktmpdir do |dir|
- File.write(File.join(dir, filename), pretty_logs)
- zipfile = Compression::Zip.new.compress(dir, filename)
- File.open(zipfile) do |file|
- UploadCreator.new(
- file,
- File.basename(zipfile),
- type: 'backup_logs',
- for_export: 'true'
- ).create_for(user.id)
+ upload =
+ Dir.mktmpdir do |dir|
+ File.write(File.join(dir, filename), pretty_logs)
+ zipfile = Compression::Zip.new.compress(dir, filename)
+ File.open(zipfile) do |file|
+ UploadCreator.new(
+ file,
+ File.basename(zipfile),
+ type: "backup_logs",
+ for_export: "true",
+ ).create_for(user.id)
+ end
end
- end
if upload.persisted?
return UploadMarkdown.new(upload).attachment_markdown
@@ -82,8 +83,8 @@ module Discourse
rescue Errno::ENOENT
end
- FileUtils.mkdir_p(File.join(Rails.root, 'tmp'))
- temp_destination = File.join(Rails.root, 'tmp', SecureRandom.hex)
+ FileUtils.mkdir_p(File.join(Rails.root, "tmp"))
+ temp_destination = File.join(Rails.root, "tmp", SecureRandom.hex)
File.open(temp_destination, "w") do |fd|
fd.write(contents)
@@ -101,9 +102,9 @@ module Discourse
rescue Errno::ENOENT, Errno::EINVAL
end
- FileUtils.mkdir_p(File.join(Rails.root, 'tmp'))
- temp_destination = File.join(Rails.root, 'tmp', SecureRandom.hex)
- execute_command('ln', '-s', source, temp_destination)
+ FileUtils.mkdir_p(File.join(Rails.root, "tmp"))
+ temp_destination = File.join(Rails.root, "tmp", SecureRandom.hex)
+ execute_command("ln", "-s", source, temp_destination)
FileUtils.mv(temp_destination, destination)
nil
@@ -127,13 +128,22 @@ module Discourse
end
def exec(*command, **exec_params)
- raise RuntimeError.new("Cannot specify same parameters at block and command level") if (@init_params.keys & exec_params.keys).present?
+ if (@init_params.keys & exec_params.keys).present?
+ raise RuntimeError.new("Cannot specify same parameters at block and command level")
+ end
execute_command(*command, **@init_params.merge(exec_params))
end
private
- def execute_command(*command, timeout: nil, failure_message: "", success_status_codes: [0], chdir: ".", unsafe_shell: false)
+ def execute_command(
+ *command,
+ timeout: nil,
+ failure_message: "",
+ success_status_codes: [0],
+ chdir: ".",
+ unsafe_shell: false
+ )
env = nil
env = command.shift if command[0].is_a?(Hash)
@@ -156,11 +166,11 @@ module Discourse
if !status.exited? || !success_status_codes.include?(status.exitstatus)
failure_message = "#{failure_message}\n" if !failure_message.blank?
raise CommandError.new(
- "#{caller[0]}: #{failure_message}#{stderr}",
- stdout: stdout,
- stderr: stderr,
- status: status
- )
+ "#{caller[0]}: #{failure_message}#{stderr}",
+ stdout: stdout,
+ stderr: stderr,
+ status: status,
+ )
end
stdout
@@ -195,33 +205,32 @@ module Discourse
# mini_scheduler direct reporting
if Hash === job
job_class = job["class"]
- if job_class
- job_exception_stats[job_class] += 1
- end
+ job_exception_stats[job_class] += 1 if job_class
end
# internal reporting
- if job.class == Class && ::Jobs::Base > job
- job_exception_stats[job] += 1
- end
+ job_exception_stats[job] += 1 if job.class == Class && ::Jobs::Base > job
cm = RailsMultisite::ConnectionManagement
- parent_logger.handle_exception(ex, {
- current_db: cm.current_db,
- current_hostname: cm.current_hostname
- }.merge(context))
+ parent_logger.handle_exception(
+ ex,
+ { current_db: cm.current_db, current_hostname: cm.current_hostname }.merge(context),
+ )
raise ex if Rails.env.test?
end
# Expected less matches than what we got in a find
- class TooManyMatches < StandardError; end
+ class TooManyMatches < StandardError
+ end
# When they try to do something they should be logged in for
- class NotLoggedIn < StandardError; end
+ class NotLoggedIn < StandardError
+ end
# When the input is somehow bad
- class InvalidParameters < StandardError; end
+ class InvalidParameters < StandardError
+ end
# When they don't have permission to do something
class InvalidAccess < StandardError
@@ -249,7 +258,13 @@ module Discourse
attr_reader :original_path
attr_reader :custom_message
- def initialize(msg = nil, status: 404, check_permalinks: false, original_path: nil, custom_message: nil)
+ def initialize(
+ msg = nil,
+ status: 404,
+ check_permalinks: false,
+ original_path: nil,
+ custom_message: nil
+ )
super(msg)
@status = status
@@ -260,27 +275,33 @@ module Discourse
end
# When a setting is missing
- class SiteSettingMissing < StandardError; end
+ class SiteSettingMissing < StandardError
+ end
# When ImageMagick is missing
- class ImageMagickMissing < StandardError; end
+ class ImageMagickMissing < StandardError
+ end
# When read-only mode is enabled
- class ReadOnly < StandardError; end
+ class ReadOnly < StandardError
+ end
# Cross site request forgery
- class CSRF < StandardError; end
+ class CSRF < StandardError
+ end
- class Deprecation < StandardError; end
+ class Deprecation < StandardError
+ end
- class ScssError < StandardError; end
+ class ScssError < StandardError
+ end
def self.filters
- @filters ||= [:latest, :unread, :new, :unseen, :top, :read, :posted, :bookmarks]
+ @filters ||= %i[latest unread new unseen top read posted bookmarks]
end
def self.anonymous_filters
- @anonymous_filters ||= [:latest, :top, :categories]
+ @anonymous_filters ||= %i[latest top categories]
end
def self.top_menu_items
@@ -288,7 +309,7 @@ module Discourse
end
def self.anonymous_top_menu_items
- @anonymous_top_menu_items ||= Discourse.anonymous_filters + [:categories, :top]
+ @anonymous_top_menu_items ||= Discourse.anonymous_filters + %i[categories top]
end
PIXEL_RATIOS ||= [1, 1.5, 2, 3]
@@ -297,26 +318,28 @@ module Discourse
# TODO: should cache these when we get a notification system for site settings
set = Set.new
- SiteSetting.avatar_sizes.split("|").map(&:to_i).each do |size|
- PIXEL_RATIOS.each do |pixel_ratio|
- set << (size * pixel_ratio).to_i
- end
- end
+ SiteSetting
+ .avatar_sizes
+ .split("|")
+ .map(&:to_i)
+ .each { |size| PIXEL_RATIOS.each { |pixel_ratio| set << (size * pixel_ratio).to_i } }
set
end
def self.activate_plugins!
@plugins = []
- Plugin::Instance.find_all("#{Rails.root}/plugins").each do |p|
- v = p.metadata.required_version || Discourse::VERSION::STRING
- if Discourse.has_needed_version?(Discourse::VERSION::STRING, v)
- p.activate!
- @plugins << p
- else
- STDERR.puts "Could not activate #{p.metadata.name}, discourse does not meet required version (#{v})"
+ Plugin::Instance
+ .find_all("#{Rails.root}/plugins")
+ .each do |p|
+ v = p.metadata.required_version || Discourse::VERSION::STRING
+ if Discourse.has_needed_version?(Discourse::VERSION::STRING, v)
+ p.activate!
+ @plugins << p
+ else
+ STDERR.puts "Could not activate #{p.metadata.name}, discourse does not meet required version (#{v})"
+ end
end
- end
DiscourseEvent.trigger(:after_plugin_activation)
end
@@ -360,9 +383,7 @@ module Discourse
def self.apply_asset_filters(plugins, type, request)
filter_opts = asset_filter_options(type, request)
- plugins.select do |plugin|
- plugin.asset_filters.all? { |b| b.call(type, request, filter_opts) }
- end
+ plugins.select { |plugin| plugin.asset_filters.all? { |b| b.call(type, request, filter_opts) } }
end
def self.asset_filter_options(type, request)
@@ -385,20 +406,24 @@ module Discourse
targets << :desktop if args[:desktop_view]
targets.each do |target|
- assets += plugins.find_all do |plugin|
- plugin.css_asset_exists?(target)
- end.map do |plugin|
- target.nil? ? plugin.directory_name : "#{plugin.directory_name}_#{target}"
- end
+ assets +=
+ plugins
+ .find_all { |plugin| plugin.css_asset_exists?(target) }
+ .map do |plugin|
+ target.nil? ? plugin.directory_name : "#{plugin.directory_name}_#{target}"
+ end
end
assets
end
def self.find_plugin_js_assets(args)
- plugins = self.find_plugins(args).select do |plugin|
- plugin.js_asset_exists? || plugin.extra_js_asset_exists? || plugin.admin_js_asset_exists?
- end
+ plugins =
+ self
+ .find_plugins(args)
+ .select do |plugin|
+ plugin.js_asset_exists? || plugin.extra_js_asset_exists? || plugin.admin_js_asset_exists?
+ end
plugins = apply_asset_filters(plugins, :js, args[:request])
@@ -413,25 +438,33 @@ module Discourse
end
def self.assets_digest
- @assets_digest ||= begin
- digest = Digest::MD5.hexdigest(ActionView::Base.assets_manifest.assets.values.sort.join)
+ @assets_digest ||=
+ begin
+ digest = Digest::MD5.hexdigest(ActionView::Base.assets_manifest.assets.values.sort.join)
- channel = "/global/asset-version"
- message = MessageBus.last_message(channel)
+ channel = "/global/asset-version"
+ message = MessageBus.last_message(channel)
- unless message && message.data == digest
- MessageBus.publish channel, digest
+ MessageBus.publish channel, digest unless message && message.data == digest
+ digest
end
- digest
- end
end
BUILTIN_AUTH ||= [
- Auth::AuthProvider.new(authenticator: Auth::FacebookAuthenticator.new, frame_width: 580, frame_height: 400, icon: "fab-facebook"),
- Auth::AuthProvider.new(authenticator: Auth::GoogleOAuth2Authenticator.new, frame_width: 850, frame_height: 500), # Custom icon implemented in client
+ Auth::AuthProvider.new(
+ authenticator: Auth::FacebookAuthenticator.new,
+ frame_width: 580,
+ frame_height: 400,
+ icon: "fab-facebook",
+ ),
+ Auth::AuthProvider.new(
+ authenticator: Auth::GoogleOAuth2Authenticator.new,
+ frame_width: 850,
+ frame_height: 500,
+ ), # Custom icon implemented in client
Auth::AuthProvider.new(authenticator: Auth::GithubAuthenticator.new, icon: "fab-github"),
Auth::AuthProvider.new(authenticator: Auth::TwitterAuthenticator.new, icon: "fab-twitter"),
- Auth::AuthProvider.new(authenticator: Auth::DiscordAuthenticator.new, icon: "fab-discord")
+ Auth::AuthProvider.new(authenticator: Auth::DiscordAuthenticator.new, icon: "fab-discord"),
]
def self.auth_providers
@@ -439,7 +472,7 @@ module Discourse
end
def self.enabled_auth_providers
- auth_providers.select { |provider| provider.authenticator.enabled? }
+ auth_providers.select { |provider| provider.authenticator.enabled? }
end
def self.authenticators
@@ -449,17 +482,18 @@ module Discourse
end
def self.enabled_authenticators
- authenticators.select { |authenticator| authenticator.enabled? }
+ authenticators.select { |authenticator| authenticator.enabled? }
end
def self.cache
- @cache ||= begin
- if GlobalSetting.skip_redis?
- ActiveSupport::Cache::MemoryStore.new
- else
- Cache.new
+ @cache ||=
+ begin
+ if GlobalSetting.skip_redis?
+ ActiveSupport::Cache::MemoryStore.new
+ else
+ Cache.new
+ end
end
- end
end
# hostname of the server, operating system level
@@ -467,15 +501,15 @@ module Discourse
def self.os_hostname
@os_hostname ||=
begin
- require 'socket'
+ require "socket"
Socket.gethostname
rescue => e
- warn_exception(e, message: 'Socket.gethostname is not working')
+ warn_exception(e, message: "Socket.gethostname is not working")
begin
`hostname`.strip
rescue => e
- warn_exception(e, message: 'hostname command is not working')
- 'unknown_host'
+ warn_exception(e, message: "hostname command is not working")
+ "unknown_host"
end
end
end
@@ -501,12 +535,12 @@ module Discourse
def self.current_hostname_with_port
default_port = SiteSetting.force_https? ? 443 : 80
result = +"#{current_hostname}"
- result << ":#{SiteSetting.port}" if SiteSetting.port.to_i > 0 && SiteSetting.port.to_i != default_port
-
- if Rails.env.development? && SiteSetting.port.blank?
- result << ":#{ENV["UNICORN_PORT"] || 3000}"
+ if SiteSetting.port.to_i > 0 && SiteSetting.port.to_i != default_port
+ result << ":#{SiteSetting.port}"
end
+ result << ":#{ENV["UNICORN_PORT"] || 3000}" if Rails.env.development? && SiteSetting.port.blank?
+
result
end
@@ -520,16 +554,18 @@ module Discourse
def self.route_for(uri)
unless uri.is_a?(URI)
- uri = begin
- URI(uri)
- rescue ArgumentError, URI::Error
- end
+ uri =
+ begin
+ URI(uri)
+ rescue ArgumentError, URI::Error
+ end
end
return unless uri
path = +(uri.path || "")
- if !uri.host || (uri.host == Discourse.current_hostname && path.start_with?(Discourse.base_path))
+ if !uri.host ||
+ (uri.host == Discourse.current_hostname && path.start_with?(Discourse.base_path))
path.slice!(Discourse.base_path)
return Rails.application.routes.recognize_path(path)
end
@@ -543,21 +579,21 @@ module Discourse
alias_method :base_url_no_path, :base_url_no_prefix
end
- READONLY_MODE_KEY_TTL ||= 60
- READONLY_MODE_KEY ||= 'readonly_mode'
- PG_READONLY_MODE_KEY ||= 'readonly_mode:postgres'
- PG_READONLY_MODE_KEY_TTL ||= 300
- USER_READONLY_MODE_KEY ||= 'readonly_mode:user'
- PG_FORCE_READONLY_MODE_KEY ||= 'readonly_mode:postgres_force'
+ READONLY_MODE_KEY_TTL ||= 60
+ READONLY_MODE_KEY ||= "readonly_mode"
+ PG_READONLY_MODE_KEY ||= "readonly_mode:postgres"
+ PG_READONLY_MODE_KEY_TTL ||= 300
+ USER_READONLY_MODE_KEY ||= "readonly_mode:user"
+ PG_FORCE_READONLY_MODE_KEY ||= "readonly_mode:postgres_force"
# Psuedo readonly mode, where staff can still write
- STAFF_WRITES_ONLY_MODE_KEY ||= 'readonly_mode:staff_writes_only'
+ STAFF_WRITES_ONLY_MODE_KEY ||= "readonly_mode:staff_writes_only"
READONLY_KEYS ||= [
READONLY_MODE_KEY,
PG_READONLY_MODE_KEY,
USER_READONLY_MODE_KEY,
- PG_FORCE_READONLY_MODE_KEY
+ PG_FORCE_READONLY_MODE_KEY,
]
def self.enable_readonly_mode(key = READONLY_MODE_KEY)
@@ -565,7 +601,9 @@ module Discourse
Sidekiq.pause!("pg_failover") if !Sidekiq.paused?
end
- if [USER_READONLY_MODE_KEY, PG_FORCE_READONLY_MODE_KEY, STAFF_WRITES_ONLY_MODE_KEY].include?(key)
+ if [USER_READONLY_MODE_KEY, PG_FORCE_READONLY_MODE_KEY, STAFF_WRITES_ONLY_MODE_KEY].include?(
+ key,
+ )
Discourse.redis.set(key, 1)
else
ttl =
@@ -595,15 +633,13 @@ module Discourse
unless @threads[key]&.alive?
@threads[key] = Thread.new do
- while @dbs.size > 0 do
+ while @dbs.size > 0
sleep ttl / 2
@mutex.synchronize do
@dbs.each do |db|
RailsMultisite::ConnectionManagement.with_connection(db) do
- if !Discourse.redis.expire(key, ttl)
- @dbs.delete(db)
- end
+ @dbs.delete(db) if !Discourse.redis.expire(key, ttl)
end
end
end
@@ -653,7 +689,7 @@ module Discourse
# Shared between processes
def self.postgres_last_read_only
- @postgres_last_read_only ||= DistributedCache.new('postgres_last_read_only', namespace: false)
+ @postgres_last_read_only ||= DistributedCache.new("postgres_last_read_only", namespace: false)
end
# Per-process
@@ -698,39 +734,43 @@ module Discourse
# This is better than `MessageBus.publish "/file-change", ["refresh"]` because
# it spreads the refreshes out over a time period
if user_ids
- MessageBus.publish("/refresh_client", 'clobber', user_ids: user_ids)
+ MessageBus.publish("/refresh_client", "clobber", user_ids: user_ids)
else
- MessageBus.publish('/global/asset-version', 'clobber')
+ MessageBus.publish("/global/asset-version", "clobber")
end
end
def self.git_version
- @git_version ||= begin
- git_cmd = 'git rev-parse HEAD'
- self.try_git(git_cmd, Discourse::VERSION::STRING)
- end
+ @git_version ||=
+ begin
+ git_cmd = "git rev-parse HEAD"
+ self.try_git(git_cmd, Discourse::VERSION::STRING)
+ end
end
def self.git_branch
- @git_branch ||= begin
- git_cmd = 'git rev-parse --abbrev-ref HEAD'
- self.try_git(git_cmd, 'unknown')
- end
+ @git_branch ||=
+ begin
+ git_cmd = "git rev-parse --abbrev-ref HEAD"
+ self.try_git(git_cmd, "unknown")
+ end
end
def self.full_version
- @full_version ||= begin
- git_cmd = 'git describe --dirty --match "v[0-9]*" 2> /dev/null'
- self.try_git(git_cmd, 'unknown')
- end
+ @full_version ||=
+ begin
+ git_cmd = 'git describe --dirty --match "v[0-9]*" 2> /dev/null'
+ self.try_git(git_cmd, "unknown")
+ end
end
def self.last_commit_date
- @last_commit_date ||= begin
- git_cmd = 'git log -1 --format="%ct"'
- seconds = self.try_git(git_cmd, nil)
- seconds.nil? ? nil : DateTime.strptime(seconds, '%s')
- end
+ @last_commit_date ||=
+ begin
+ git_cmd = 'git log -1 --format="%ct"'
+ seconds = self.try_git(git_cmd, nil)
+ seconds.nil? ? nil : DateTime.strptime(seconds, "%s")
+ end
end
def self.try_git(git_cmd, default_value)
@@ -738,20 +778,21 @@ module Discourse
begin
version_value = `#{git_cmd}`.strip
- rescue
+ rescue StandardError
version_value = default_value
end
- if version_value.empty?
- version_value = default_value
- end
+ version_value = default_value if version_value.empty?
version_value
end
# Either returns the site_contact_username user or the first admin.
def self.site_contact_user
- user = User.find_by(username_lower: SiteSetting.site_contact_username.downcase) if SiteSetting.site_contact_username.present?
+ user =
+ User.find_by(
+ username_lower: SiteSetting.site_contact_username.downcase,
+ ) if SiteSetting.site_contact_username.present?
user ||= (system_user || User.admins.real.order(:id).first)
end
@@ -765,10 +806,10 @@ module Discourse
def self.store
if SiteSetting.Upload.enable_s3_uploads
- @s3_store_loaded ||= require 'file_store/s3_store'
+ @s3_store_loaded ||= require "file_store/s3_store"
FileStore::S3Store.new
else
- @local_store_loaded ||= require 'file_store/local_store'
+ @local_store_loaded ||= require "file_store/local_store"
FileStore::LocalStore.new
end
end
@@ -805,15 +846,15 @@ module Discourse
Discourse.cache.reconnect
Logster.store.redis.reconnect
# shuts down all connections in the pool
- Sidekiq.redis_pool.shutdown { |conn| conn.disconnect! }
+ Sidekiq.redis_pool.shutdown { |conn| conn.disconnect! }
# re-establish
Sidekiq.redis = sidekiq_redis_config
# in case v8 was initialized we want to make sure it is nil
PrettyText.reset_context
- DiscourseJsProcessor::Transpiler.reset_context if defined? DiscourseJsProcessor::Transpiler
- JsLocaleHelper.reset_context if defined? JsLocaleHelper
+ DiscourseJsProcessor::Transpiler.reset_context if defined?(DiscourseJsProcessor::Transpiler)
+ JsLocaleHelper.reset_context if defined?(JsLocaleHelper)
# warm up v8 after fork, that way we do not fork a v8 context
# it may cause issues if bg threads in a v8 isolate randomly stop
@@ -831,7 +872,7 @@ module Discourse
# you can use Discourse.warn when you want to report custom environment
# with the error, this helps with grouping
def self.warn(message, env = nil)
- append = env ? (+" ") << env.map { |k, v|"#{k}: #{v}" }.join(" ") : ""
+ append = env ? (+" ") << env.map { |k, v| "#{k}: #{v}" }.join(" ") : ""
if !(Logster::Logger === Rails.logger)
Rails.logger.warn("#{message}#{append}")
@@ -839,9 +880,7 @@ module Discourse
end
loggers = [Rails.logger]
- if Rails.logger.chained
- loggers.concat(Rails.logger.chained)
- end
+ loggers.concat(Rails.logger.chained) if Rails.logger.chained
logster_env = env
@@ -849,9 +888,7 @@ module Discourse
logster_env = Logster::Message.populate_from_env(old_env)
# a bit awkward by try to keep the new params
- env.each do |k, v|
- logster_env[k] = v
- end
+ env.each { |k, v| logster_env[k] = v }
end
loggers.each do |logger|
@@ -860,12 +897,7 @@ module Discourse
next
end
- logger.store.report(
- ::Logger::Severity::WARN,
- "discourse",
- message,
- env: logster_env
- )
+ logger.store.report(::Logger::Severity::WARN, "discourse", message, env: logster_env)
end
if old_env
@@ -881,7 +913,6 @@ module Discourse
# report a warning maintaining backtrack for logster
def self.warn_exception(e, message: "", env: nil)
if Rails.logger.respond_to? :add_with_opts
-
env ||= {}
env[:current_db] ||= RailsMultisite::ConnectionManagement.current_db
@@ -891,13 +922,13 @@ module Discourse
"#{message} : #{e.class.name} : #{e}",
"discourse-exception",
backtrace: e.backtrace.join("\n"),
- env: env
+ env: env,
)
else
# no logster ... fallback
Rails.logger.warn("#{message} #{e}\n#{e.backtrace.join("\n")}")
end
- rescue
+ rescue StandardError
STDERR.puts "Failed to report exception #{e} #{message}"
end
@@ -909,17 +940,11 @@ module Discourse
warning << "\nAt #{location}"
warning = warning.join(" ")
- if raise_error
- raise Deprecation.new(warning)
- end
+ raise Deprecation.new(warning) if raise_error
- if Rails.env == "development"
- STDERR.puts(warning)
- end
+ STDERR.puts(warning) if Rails.env == "development"
- if output_in_test && Rails.env == "test"
- STDERR.puts(warning)
- end
+ STDERR.puts(warning) if output_in_test && Rails.env == "test"
digest = Digest::MD5.hexdigest(warning)
redis_key = "deprecate-notice-#{digest}"
@@ -935,7 +960,7 @@ module Discourse
warning
end
- SIDEKIQ_NAMESPACE ||= 'sidekiq'
+ SIDEKIQ_NAMESPACE ||= "sidekiq"
def self.sidekiq_redis_config
conf = GlobalSetting.redis_config.dup
@@ -951,7 +976,8 @@ module Discourse
def self.reset_active_record_cache_if_needed(e)
last_cache_reset = Discourse.last_ar_cache_reset
- if e && e.message =~ /UndefinedColumn/ && (last_cache_reset.nil? || last_cache_reset < 30.seconds.ago)
+ if e && e.message =~ /UndefinedColumn/ &&
+ (last_cache_reset.nil? || last_cache_reset < 30.seconds.ago)
Rails.logger.warn "Clearing Active Record cache, this can happen if schema changed while site is running or in a multisite various databases are running different schemas. Consider running rake multisite:migrate."
Discourse.last_ar_cache_reset = Time.zone.now
Discourse.reset_active_record_cache
@@ -961,7 +987,11 @@ module Discourse
def self.reset_active_record_cache
ActiveRecord::Base.connection.query_cache.clear
(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|
- table.classify.constantize.reset_column_information rescue nil
+ begin
+ table.classify.constantize.reset_column_information
+ rescue StandardError
+ nil
+ end
end
nil
end
@@ -971,7 +1001,7 @@ module Discourse
end
def self.skip_post_deployment_migrations?
- ['1', 'true'].include?(ENV["SKIP_POST_DEPLOYMENT_MIGRATIONS"]&.to_s)
+ %w[1 true].include?(ENV["SKIP_POST_DEPLOYMENT_MIGRATIONS"]&.to_s)
end
# this is used to preload as much stuff as possible prior to forking
@@ -985,7 +1015,11 @@ module Discourse
# load up all models and schema
(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|
- table.classify.constantize.first rescue nil
+ begin
+ table.classify.constantize.first
+ rescue StandardError
+ nil
+ end
end
# ensure we have a full schema cache in case we missed something above
@@ -1024,29 +1058,27 @@ module Discourse
end
[
- Thread.new {
+ Thread.new do
# router warm up
- Rails.application.routes.recognize_path('abc') rescue nil
- },
- Thread.new {
+ begin
+ Rails.application.routes.recognize_path("abc")
+ rescue StandardError
+ nil
+ end
+ end,
+ Thread.new do
# preload discourse version
Discourse.git_version
Discourse.git_branch
Discourse.full_version
- },
- Thread.new {
- require 'actionview_precompiler'
+ end,
+ Thread.new do
+ require "actionview_precompiler"
ActionviewPrecompiler.precompile
- },
- Thread.new {
- LetterAvatar.image_magick_version
- },
- Thread.new {
- SvgSprite.core_svgs
- },
- Thread.new {
- EmberCli.script_chunks
- }
+ end,
+ Thread.new { LetterAvatar.image_magick_version },
+ Thread.new { SvgSprite.core_svgs },
+ Thread.new { EmberCli.script_chunks },
].each(&:join)
ensure
@preloaded_rails = true
@@ -1055,10 +1087,10 @@ module Discourse
mattr_accessor :redis
def self.is_parallel_test?
- ENV['RAILS_ENV'] == "test" && ENV['TEST_ENV_NUMBER']
+ ENV["RAILS_ENV"] == "test" && ENV["TEST_ENV_NUMBER"]
end
- CDN_REQUEST_METHODS ||= ["GET", "HEAD", "OPTIONS"]
+ CDN_REQUEST_METHODS ||= %w[GET HEAD OPTIONS]
def self.is_cdn_request?(env, request_method)
return unless CDN_REQUEST_METHODS.include?(request_method)
@@ -1071,8 +1103,8 @@ module Discourse
end
def self.apply_cdn_headers(headers)
- headers['Access-Control-Allow-Origin'] = '*'
- headers['Access-Control-Allow-Methods'] = CDN_REQUEST_METHODS.join(", ")
+ headers["Access-Control-Allow-Origin"] = "*"
+ headers["Access-Control-Allow-Methods"] = CDN_REQUEST_METHODS.join(", ")
headers
end
@@ -1091,8 +1123,12 @@ module Discourse
end
def self.anonymous_locale(request)
- locale = HttpLanguageParser.parse(request.cookies["locale"]) if SiteSetting.set_locale_from_cookie
- locale ||= HttpLanguageParser.parse(request.env["HTTP_ACCEPT_LANGUAGE"]) if SiteSetting.set_locale_from_accept_language_header
+ locale =
+ HttpLanguageParser.parse(request.cookies["locale"]) if SiteSetting.set_locale_from_cookie
+ locale ||=
+ HttpLanguageParser.parse(
+ request.env["HTTP_ACCEPT_LANGUAGE"],
+ ) if SiteSetting.set_locale_from_accept_language_header
locale
end
end
diff --git a/lib/discourse_connect_base.rb b/lib/discourse_connect_base.rb
index 3a503ddcbe3..b5e04d8f212 100644
--- a/lib/discourse_connect_base.rb
+++ b/lib/discourse_connect_base.rb
@@ -1,12 +1,13 @@
# frozen_string_literal: true
class DiscourseConnectBase
+ class ParseError < RuntimeError
+ end
- class ParseError < RuntimeError; end
-
- ACCESSORS = %i{
+ ACCESSORS = %i[
add_groups
- admin moderator
+ admin
+ moderator
avatar_force_update
avatar_url
bio
@@ -31,11 +32,11 @@ class DiscourseConnectBase
title
username
website
- }
+ ]
FIXNUMS = []
- BOOLS = %i{
+ BOOLS = %i[
admin
avatar_force_update
confirmed_2fa
@@ -46,7 +47,7 @@ class DiscourseConnectBase
require_2fa
require_activation
suppress_welcome_message
- }
+ ]
def self.nonce_expiry_time
@nonce_expiry_time ||= 10.minutes
@@ -80,9 +81,11 @@ class DiscourseConnectBase
decoded_hash = Rack::Utils.parse_query(decoded)
if sso.sign(parsed["sso"]) != parsed["sig"]
- diags = "\n\nsso: #{parsed["sso"]}\n\nsig: #{parsed["sig"]}\n\nexpected sig: #{sso.sign(parsed["sso"])}"
- if parsed["sso"] =~ /[^a-zA-Z0-9=\r\n\/+]/m
- raise ParseError, "The SSO field should be Base64 encoded, using only A-Z, a-z, 0-9, +, /, and = characters. Your input contains characters we don't understand as Base64, see http://en.wikipedia.org/wiki/Base64 #{diags}"
+ diags =
+ "\n\nsso: #{parsed["sso"]}\n\nsig: #{parsed["sig"]}\n\nexpected sig: #{sso.sign(parsed["sso"])}"
+ if parsed["sso"] =~ %r{[^a-zA-Z0-9=\r\n/+]}m
+ raise ParseError,
+ "The SSO field should be Base64 encoded, using only A-Z, a-z, 0-9, +, /, and = characters. Your input contains characters we don't understand as Base64, see http://en.wikipedia.org/wiki/Base64 #{diags}"
else
raise ParseError, "Bad signature for payload #{diags}"
end
@@ -91,9 +94,7 @@ class DiscourseConnectBase
ACCESSORS.each do |k|
val = decoded_hash[k.to_s]
val = val.to_i if FIXNUMS.include? k
- if BOOLS.include? k
- val = ["true", "false"].include?(val) ? val == "true" : nil
- end
+ val = %w[true false].include?(val) ? val == "true" : nil if BOOLS.include? k
sso.public_send("#{k}=", val)
end
@@ -137,12 +138,12 @@ class DiscourseConnectBase
def to_url(base_url = nil)
base = "#{base_url || sso_url}"
- "#{base}#{base.include?('?') ? '&' : '?'}#{payload}"
+ "#{base}#{base.include?("?") ? "&" : "?"}#{payload}"
end
def payload(secret = nil)
payload = Base64.strict_encode64(unsigned_payload)
- "sso=#{CGI::escape(payload)}&sig=#{sign(payload, secret)}"
+ "sso=#{CGI.escape(payload)}&sig=#{sign(payload, secret)}"
end
def unsigned_payload
@@ -157,9 +158,7 @@ class DiscourseConnectBase
payload[k] = val
end
- @custom_fields&.each do |k, v|
- payload["custom.#{k}"] = v.to_s
- end
+ @custom_fields&.each { |k, v| payload["custom.#{k}"] = v.to_s }
payload
end
diff --git a/lib/discourse_connect_provider.rb b/lib/discourse_connect_provider.rb
index 218d081b10a..76f46989df7 100644
--- a/lib/discourse_connect_provider.rb
+++ b/lib/discourse_connect_provider.rb
@@ -1,8 +1,10 @@
# frozen_string_literal: true
class DiscourseConnectProvider < DiscourseConnectBase
- class BlankSecret < RuntimeError; end
- class BlankReturnUrl < RuntimeError; end
+ class BlankSecret < RuntimeError
+ end
+ class BlankReturnUrl < RuntimeError
+ end
def self.parse(payload, sso_secret = nil, **init_kwargs)
parsed_payload = Rack::Utils.parse_query(payload)
@@ -15,11 +17,16 @@ class DiscourseConnectProvider < DiscourseConnectBase
if sso_secret.blank?
begin
host = URI.parse(return_sso_url).host
- Rails.logger.warn("SSO failed; website #{host} is not in the `discourse_connect_provider_secrets` site settings")
+ Rails.logger.warn(
+ "SSO failed; website #{host} is not in the `discourse_connect_provider_secrets` site settings",
+ )
rescue StandardError => e
# going for StandardError cause URI::Error may not be enough, eg it parses to something not
# responding to host
- Discourse.warn_exception(e, message: "SSO failed; invalid or missing return_sso_url in SSO payload")
+ Discourse.warn_exception(
+ e,
+ message: "SSO failed; invalid or missing return_sso_url in SSO payload",
+ )
end
raise BlankSecret
@@ -31,7 +38,7 @@ class DiscourseConnectProvider < DiscourseConnectBase
def self.lookup_return_sso_url(parsed_payload)
decoded = Base64.decode64(parsed_payload["sso"])
decoded_hash = Rack::Utils.parse_query(decoded)
- decoded_hash['return_sso_url']
+ decoded_hash["return_sso_url"]
end
def self.lookup_sso_secret(return_sso_url, parsed_payload)
@@ -39,21 +46,23 @@ class DiscourseConnectProvider < DiscourseConnectBase
return_url_host = URI.parse(return_sso_url).host
- provider_secrets = SiteSetting
- .discourse_connect_provider_secrets
- .split("\n")
- .map { |row| row.split("|", 2) }
- .sort_by { |k, _| k }
- .reverse
+ provider_secrets =
+ SiteSetting
+ .discourse_connect_provider_secrets
+ .split("\n")
+ .map { |row| row.split("|", 2) }
+ .sort_by { |k, _| k }
+ .reverse
first_domain_match = nil
- pair = provider_secrets.find do |domain, configured_secret|
- if WildcardDomainChecker.check_domain(domain, return_url_host)
- first_domain_match ||= configured_secret
- sign(parsed_payload["sso"], configured_secret) == parsed_payload["sig"]
+ pair =
+ provider_secrets.find do |domain, configured_secret|
+ if WildcardDomainChecker.check_domain(domain, return_url_host)
+ first_domain_match ||= configured_secret
+ sign(parsed_payload["sso"], configured_secret) == parsed_payload["sig"]
+ end
end
- end
# falls back to a secret which will fail to validate in DiscourseConnectBase
# this ensures error flow is correct
diff --git a/lib/discourse_dev/category.rb b/lib/discourse_dev/category.rb
index b13c43d7587..7c1fe2500c6 100644
--- a/lib/discourse_dev/category.rb
+++ b/lib/discourse_dev/category.rb
@@ -1,12 +1,11 @@
# frozen_string_literal: true
-require 'discourse_dev/record'
-require 'rails'
-require 'faker'
+require "discourse_dev/record"
+require "rails"
+require "faker"
module DiscourseDev
class Category < Record
-
def initialize
super(::Category, DiscourseDev.config.category[:count])
@parent_category_ids = ::Category.where(parent_category_id: nil).pluck(:id)
@@ -29,7 +28,7 @@ module DiscourseDev
description: Faker::Lorem.paragraph,
user_id: ::Discourse::SYSTEM_USER_ID,
color: Faker::Color.hex_color.last(6),
- parent_category_id: parent_category_id
+ parent_category_id: parent_category_id,
}
end
diff --git a/lib/discourse_dev/config.rb b/lib/discourse_dev/config.rb
index eb4a1d160bd..f83eebe880e 100644
--- a/lib/discourse_dev/config.rb
+++ b/lib/discourse_dev/config.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'rails'
-require 'highline/import'
+require "rails"
+require "highline/import"
module DiscourseDev
class Config
@@ -63,10 +63,11 @@ module DiscourseDev
if settings.present?
email = settings[:email] || "[email protected]"
- new_user = ::User.create!(
- email: email,
- username: settings[:username] || UserNameSuggester.suggest(email)
- )
+ new_user =
+ ::User.create!(
+ email: email,
+ username: settings[:username] || UserNameSuggester.suggest(email),
+ )
new_user.email_tokens.update_all confirmed: true
new_user.activate
end
@@ -88,15 +89,14 @@ module DiscourseDev
def create_admin_user_from_settings(settings)
email = settings[:email]
- admin = ::User.with_email(email).first_or_create!(
- email: email,
- username: settings[:username] || UserNameSuggester.suggest(email),
- password: settings[:password]
- )
+ admin =
+ ::User.with_email(email).first_or_create!(
+ email: email,
+ username: settings[:username] || UserNameSuggester.suggest(email),
+ password: settings[:password],
+ )
admin.grant_admin!
- if admin.trust_level < 1
- admin.change_trust_level!(1)
- end
+ admin.change_trust_level!(1) if admin.trust_level < 1
admin.email_tokens.update_all confirmed: true
admin.activate
end
@@ -107,10 +107,7 @@ module DiscourseDev
password = ask("Password (optional, press ENTER to skip): ")
username = UserNameSuggester.suggest(email)
- admin = ::User.new(
- email: email,
- username: username
- )
+ admin = ::User.new(email: email, username: username)
if password.present?
admin.password = password
@@ -122,7 +119,7 @@ module DiscourseDev
saved = admin.save
if saved
- File.open(file_path, 'a') do | file|
+ File.open(file_path, "a") do |file|
file.puts("admin:")
file.puts(" username: #{admin.username}")
file.puts(" email: #{admin.email}")
@@ -137,9 +134,7 @@ module DiscourseDev
admin.save
admin.grant_admin!
- if admin.trust_level < 1
- admin.change_trust_level!(1)
- end
+ admin.change_trust_level!(1) if admin.trust_level < 1
admin.email_tokens.update_all confirmed: true
admin.activate
diff --git a/lib/discourse_dev/group.rb b/lib/discourse_dev/group.rb
index c346b0c5faa..91a0ffcb7e1 100644
--- a/lib/discourse_dev/group.rb
+++ b/lib/discourse_dev/group.rb
@@ -1,12 +1,11 @@
# frozen_string_literal: true
-require 'discourse_dev/record'
-require 'rails'
-require 'faker'
+require "discourse_dev/record"
+require "rails"
+require "faker"
module DiscourseDev
class Group < Record
-
def initialize
super(::Group, DiscourseDev.config.group[:count])
end
diff --git a/lib/discourse_dev/post.rb b/lib/discourse_dev/post.rb
index ef0e072daa4..350696a7d8d 100644
--- a/lib/discourse_dev/post.rb
+++ b/lib/discourse_dev/post.rb
@@ -1,11 +1,10 @@
# frozen_string_literal: true
-require 'discourse_dev/record'
-require 'faker'
+require "discourse_dev/record"
+require "faker"
module DiscourseDev
class Post < Record
-
attr_reader :topic
def initialize(topic, count)
@@ -28,7 +27,7 @@ module DiscourseDev
raw: Faker::DiscourseMarkdown.sandwich(sentences: 5),
created_at: Faker::Time.between(from: topic.last_posted_at, to: DateTime.now),
skip_validations: true,
- skip_guardian: true
+ skip_guardian: true,
}
end
@@ -44,13 +43,20 @@ module DiscourseDev
def generate_likes(post)
user_ids = [post.user_id]
- Faker::Number.between(from: 0, to: @max_likes_count).times do
- user = self.user
- next if user_ids.include?(user.id)
-
- PostActionCreator.new(user, post, PostActionType.types[:like], created_at: Faker::Time.between(from: post.created_at, to: DateTime.now)).perform
- user_ids << user.id
- end
+ Faker::Number
+ .between(from: 0, to: @max_likes_count)
+ .times do
+ user = self.user
+ next if user_ids.include?(user.id)
+
+ PostActionCreator.new(
+ user,
+ post,
+ PostActionType.types[:like],
+ created_at: Faker::Time.between(from: post.created_at, to: DateTime.now),
+ ).perform
+ user_ids << user.id
+ end
end
def user
@@ -90,13 +96,14 @@ module DiscourseDev
count.times do |i|
begin
user = User.random
- reply = Faker::DiscourseMarkdown.with_user(user.id) do
- {
- topic_id: topic.id,
- raw: Faker::DiscourseMarkdown.sandwich(sentences: 5),
- skip_validations: true
- }
- end
+ reply =
+ Faker::DiscourseMarkdown.with_user(user.id) do
+ {
+ topic_id: topic.id,
+ raw: Faker::DiscourseMarkdown.sandwich(sentences: 5),
+ skip_validations: true,
+ }
+ end
PostCreator.new(user, reply).create!
rescue ActiveRecord::RecordNotSaved => e
puts e
@@ -109,6 +116,5 @@ module DiscourseDev
def self.random
super(::Post)
end
-
end
end
diff --git a/lib/discourse_dev/post_revision.rb b/lib/discourse_dev/post_revision.rb
index 7c1f1da644c..0c282e9540c 100644
--- a/lib/discourse_dev/post_revision.rb
+++ b/lib/discourse_dev/post_revision.rb
@@ -1,11 +1,10 @@
# frozen_string_literal: true
-require 'discourse_dev/record'
-require 'faker'
+require "discourse_dev/record"
+require "faker"
module DiscourseDev
class PostRevision < Record
-
def initialize
super(::PostRevision, DiscourseDev.config.post_revisions[:count])
end
diff --git a/lib/discourse_dev/record.rb b/lib/discourse_dev/record.rb
index 3e2767ef62c..b1b84097df2 100644
--- a/lib/discourse_dev/record.rb
+++ b/lib/discourse_dev/record.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-require 'discourse_dev'
-require 'rails'
-require 'faker'
+require "discourse_dev"
+require "rails"
+require "faker"
module DiscourseDev
class Record
@@ -12,11 +12,12 @@ module DiscourseDev
attr_reader :model, :type
def initialize(model, count = DEFAULT_COUNT)
- @@initialized ||= begin
- Faker::Discourse.unique.clear
- RateLimiter.disable
- true
- end
+ @@initialized ||=
+ begin
+ Faker::Discourse.unique.clear
+ RateLimiter.disable
+ true
+ end
@model = model
@type = model.to_s.downcase.to_sym
@@ -40,11 +41,9 @@ module DiscourseDev
if current_count >= @count
puts "Already have #{current_count} #{type} records"
- Rake.application.top_level_tasks.each do |task_name|
- Rake::Task[task_name].reenable
- end
+ Rake.application.top_level_tasks.each { |task_name| Rake::Task[task_name].reenable }
- Rake::Task['dev:repopulate'].invoke
+ Rake::Task["dev:repopulate"].invoke
return
elsif current_count > 0
@count -= current_count
@@ -74,7 +73,9 @@ module DiscourseDev
end
def self.random(model, use_existing_records: true)
- model.joins(:_custom_fields).where("#{:type}_custom_fields.name = '#{AUTO_POPULATED}'") if !use_existing_records && model.new.respond_to?(:custom_fields)
+ if !use_existing_records && model.new.respond_to?(:custom_fields)
+ model.joins(:_custom_fields).where("#{:type}_custom_fields.name = '#{AUTO_POPULATED}'")
+ end
count = model.count
raise "#{:type} records are not yet populated" if count == 0
diff --git a/lib/discourse_dev/tag.rb b/lib/discourse_dev/tag.rb
index 987d8656e9c..96c06ad6e1d 100644
--- a/lib/discourse_dev/tag.rb
+++ b/lib/discourse_dev/tag.rb
@@ -1,12 +1,11 @@
# frozen_string_literal: true
-require 'discourse_dev/record'
-require 'rails'
-require 'faker'
+require "discourse_dev/record"
+require "rails"
+require "faker"
module DiscourseDev
class Tag < Record
-
def initialize
super(::Tag, DiscourseDev.config.tag[:count])
end
@@ -24,9 +23,7 @@ module DiscourseDev
end
def data
- {
- name: Faker::Discourse.unique.tag,
- }
+ { name: Faker::Discourse.unique.tag }
end
end
end
diff --git a/lib/discourse_dev/topic.rb b/lib/discourse_dev/topic.rb
index c08af628ebd..9c6baaafd50 100644
--- a/lib/discourse_dev/topic.rb
+++ b/lib/discourse_dev/topic.rb
@@ -1,11 +1,10 @@
# frozen_string_literal: true
-require 'discourse_dev/record'
-require 'faker'
+require "discourse_dev/record"
+require "faker"
module DiscourseDev
class Topic < Record
-
def initialize(private_messages: false, recipient: nil, ignore_current_count: false)
@settings = DiscourseDev.config.topic
@private_messages = private_messages
@@ -33,15 +32,9 @@ module DiscourseDev
end
if @category
- merge_attributes = {
- category: @category.id,
- tags: tags
- }
+ merge_attributes = { category: @category.id, tags: tags }
else
- merge_attributes = {
- archetype: "private_message",
- target_usernames: [@recipient]
- }
+ merge_attributes = { archetype: "private_message", target_usernames: [@recipient] }
end
{
@@ -51,9 +44,11 @@ module DiscourseDev
topic_opts: {
import_mode: true,
views: Faker::Number.between(from: 1, to: max_views),
- custom_fields: { dev_sample: true }
+ custom_fields: {
+ dev_sample: true,
+ },
},
- skip_validations: true
+ skip_validations: true,
}.merge(merge_attributes)
end
@@ -61,7 +56,10 @@ module DiscourseDev
if current_count < I18n.t("faker.discourse.topics").count
Faker::Discourse.unique.topic
else
- Faker::Lorem.unique.sentence(word_count: 5, supplemental: true, random_words_to_add: 4).chomp(".")
+ Faker::Lorem
+ .unique
+ .sentence(word_count: 5, supplemental: true, random_words_to_add: 4)
+ .chomp(".")
end
end
@@ -70,9 +68,9 @@ module DiscourseDev
@tags = []
- Faker::Number.between(from: @settings.dig(:tags, :min), to: @settings.dig(:tags, :max)).times do
- @tags << Faker::Discourse.tag
- end
+ Faker::Number
+ .between(from: @settings.dig(:tags, :min), to: @settings.dig(:tags, :max))
+ .times { @tags << Faker::Discourse.tag }
@tags.uniq
end
@@ -92,7 +90,11 @@ module DiscourseDev
if override = @settings.dig(:replies, :overrides).find { |o| o[:title] == topic_data[:title] }
reply_count = override[:count]
else
- reply_count = Faker::Number.between(from: @settings.dig(:replies, :min), to: @settings.dig(:replies, :max))
+ reply_count =
+ Faker::Number.between(
+ from: @settings.dig(:replies, :min),
+ to: @settings.dig(:replies, :max),
+ )
end
topic = post.topic
@@ -123,9 +125,7 @@ module DiscourseDev
end
def delete_unwanted_sidekiq_jobs
- Sidekiq::ScheduledSet.new.each do |job|
- job.delete if job.item["class"] == "Jobs::UserEmail"
- end
+ Sidekiq::ScheduledSet.new.each { |job| job.delete if job.item["class"] == "Jobs::UserEmail" }
end
end
end
diff --git a/lib/discourse_diff.rb b/lib/discourse_diff.rb
index 3887abe134c..e31a699f85a 100644
--- a/lib/discourse_diff.rb
+++ b/lib/discourse_diff.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class DiscourseDiff
-
MAX_DIFFERENCE = 200
def initialize(before, after)
@@ -9,8 +8,8 @@ class DiscourseDiff
@after = after
before_html = tokenize_html_blocks(@before)
after_html = tokenize_html_blocks(@after)
- before_markdown = tokenize_line(CGI::escapeHTML(@before))
- after_markdown = tokenize_line(CGI::escapeHTML(@after))
+ before_markdown = tokenize_line(CGI.escapeHTML(@before))
+ after_markdown = tokenize_line(CGI.escapeHTML(@after))
@block_by_block_diff = ONPDiff.new(before_html, after_html).paragraph_diff
@line_by_line_diff = ONPDiff.new(before_markdown, after_markdown).short_diff
@@ -21,7 +20,8 @@ class DiscourseDiff
inline = []
while i < @block_by_block_diff.size
op_code = @block_by_block_diff[i][1]
- if op_code == :common then inline << @block_by_block_diff[i][0]
+ if op_code == :common
+ inline << @block_by_block_diff[i][0]
else
if op_code == :delete
opposite_op_code = :add
@@ -36,7 +36,11 @@ class DiscourseDiff
end
if i + 1 < @block_by_block_diff.size && @block_by_block_diff[i + 1][1] == opposite_op_code
- diff = ONPDiff.new(tokenize_html(@block_by_block_diff[first][0]), tokenize_html(@block_by_block_diff[second][0])).diff
+ diff =
+ ONPDiff.new(
+ tokenize_html(@block_by_block_diff[first][0]),
+ tokenize_html(@block_by_block_diff[second][0]),
+ ).diff
inline << generate_inline_html(diff)
i += 1
else
@@ -73,7 +77,11 @@ class DiscourseDiff
end
if i + 1 < @block_by_block_diff.size && @block_by_block_diff[i + 1][1] == opposite_op_code
- diff = ONPDiff.new(tokenize_html(@block_by_block_diff[first][0]), tokenize_html(@block_by_block_diff[second][0])).diff
+ diff =
+ ONPDiff.new(
+ tokenize_html(@block_by_block_diff[first][0]),
+ tokenize_html(@block_by_block_diff[second][0]),
+ ).diff
deleted, inserted = generate_side_by_side_html(diff)
left << deleted
right << inserted
@@ -109,9 +117,13 @@ class DiscourseDiff
end
if i + 1 < @line_by_line_diff.size && @line_by_line_diff[i + 1][1] == opposite_op_code
- before_tokens, after_tokens = tokenize_markdown(@line_by_line_diff[first][0]), tokenize_markdown(@line_by_line_diff[second][0])
+ before_tokens, after_tokens =
+ tokenize_markdown(@line_by_line_diff[first][0]),
+ tokenize_markdown(@line_by_line_diff[second][0])
if (before_tokens.size - after_tokens.size).abs > MAX_DIFFERENCE
- before_tokens, after_tokens = tokenize_line(@line_by_line_diff[first][0]), tokenize_line(@line_by_line_diff[second][0])
+ before_tokens, after_tokens =
+ tokenize_line(@line_by_line_diff[first][0]),
+ tokenize_line(@line_by_line_diff[second][0])
end
diff = ONPDiff.new(before_tokens, after_tokens).short_diff
deleted, inserted = generate_side_by_side_markdown(diff)
@@ -178,7 +190,7 @@ class DiscourseDiff
def add_class_or_wrap_in_tags(html_or_text, klass)
result = html_or_text.dup
index_of_next_chevron = result.index(">")
- if result.size > 0 && result[0] == '<' && index_of_next_chevron
+ if result.size > 0 && result[0] == "<" && index_of_next_chevron
index_of_class = result.index("class=")
if index_of_class.nil? || index_of_class > index_of_next_chevron
# we do not have a class for the current tag
@@ -202,9 +214,12 @@ class DiscourseDiff
inline = []
diff.each do |d|
case d[1]
- when :common then inline << d[0]
- when :delete then inline << add_class_or_wrap_in_tags(d[0], "del")
- when :add then inline << add_class_or_wrap_in_tags(d[0], "ins")
+ when :common
+ inline << d[0]
+ when :delete
+ inline << add_class_or_wrap_in_tags(d[0], "del")
+ when :add
+ inline << add_class_or_wrap_in_tags(d[0], "ins")
end
end
inline
@@ -217,8 +232,10 @@ class DiscourseDiff
when :common
deleted << d[0]
inserted << d[0]
- when :delete then deleted << add_class_or_wrap_in_tags(d[0], "del")
- when :add then inserted << add_class_or_wrap_in_tags(d[0], "ins")
+ when :delete
+ deleted << add_class_or_wrap_in_tags(d[0], "del")
+ when :add
+ inserted << add_class_or_wrap_in_tags(d[0], "ins")
end
end
[deleted, inserted]
@@ -231,15 +248,16 @@ class DiscourseDiff
when :common
deleted << d[0]
inserted << d[0]
- when :delete then deleted << "<del>#{d[0]}</del>"
- when :add then inserted << "<ins>#{d[0]}</ins>"
+ when :delete
+ deleted << "<del>#{d[0]}</del>"
+ when :add
+ inserted << "<ins>#{d[0]}</ins>"
end
end
[deleted, inserted]
end
class HtmlTokenizer < Nokogiri::XML::SAX::Document
-
attr_accessor :tokens
def initialize
@@ -253,23 +271,21 @@ class DiscourseDiff
me.tokens
end
- USELESS_TAGS = %w{html body}
+ USELESS_TAGS = %w[html body]
def start_element(name, attributes = [])
return if USELESS_TAGS.include?(name)
- attrs = attributes.map { |a| " #{a[0]}=\"#{CGI::escapeHTML(a[1])}\"" }.join
+ attrs = attributes.map { |a| " #{a[0]}=\"#{CGI.escapeHTML(a[1])}\"" }.join
@tokens << "<#{name}#{attrs}>"
end
- AUTOCLOSING_TAGS = %w{area base br col embed hr img input meta}
+ AUTOCLOSING_TAGS = %w[area base br col embed hr img input meta]
def end_element(name)
return if USELESS_TAGS.include?(name) || AUTOCLOSING_TAGS.include?(name)
@tokens << "</#{name}>"
end
def characters(string)
- @tokens.concat string.scan(/\W|\w+[ \t]*/).map { |x| CGI::escapeHTML(x) }
+ @tokens.concat string.scan(/\W|\w+[ \t]*/).map { |x| CGI.escapeHTML(x) }
end
-
end
-
end
diff --git a/lib/discourse_event.rb b/lib/discourse_event.rb
index 4d7f30e27a1..43c85487651 100644
--- a/lib/discourse_event.rb
+++ b/lib/discourse_event.rb
@@ -3,21 +3,23 @@
# This is meant to be used by plugins to trigger and listen to events
# So we can execute code when things happen.
class DiscourseEvent
-
# Defaults to a hash where default values are empty sets.
def self.events
@events ||= Hash.new { |hash, key| hash[key] = Set.new }
end
def self.trigger(event_name, *args, **kwargs)
- events[event_name].each do |event|
- event.call(*args, **kwargs)
- end
+ events[event_name].each { |event| event.call(*args, **kwargs) }
end
def self.on(event_name, &block)
if event_name == :site_setting_saved
- Discourse.deprecate("The :site_setting_saved event is deprecated. Please use :site_setting_changed instead", since: "2.3.0beta8", drop_from: "2.4", raise_error: true)
+ Discourse.deprecate(
+ "The :site_setting_saved event is deprecated. Please use :site_setting_changed instead",
+ since: "2.3.0beta8",
+ drop_from: "2.4",
+ raise_error: true,
+ )
end
events[event_name] << block
end
diff --git a/lib/discourse_hub.rb b/lib/discourse_hub.rb
index 31d4e8a2f0a..4b5b36d4811 100644
--- a/lib/discourse_hub.rb
+++ b/lib/discourse_hub.rb
@@ -1,16 +1,17 @@
# frozen_string_literal: true
module DiscourseHub
-
STATS_FETCHED_AT_KEY = "stats_fetched_at"
def self.version_check_payload
- default_payload = { installed_version: Discourse::VERSION::STRING }.merge!(Discourse.git_branch == "unknown" ? {} : { branch: Discourse.git_branch })
+ default_payload = { installed_version: Discourse::VERSION::STRING }.merge!(
+ Discourse.git_branch == "unknown" ? {} : { branch: Discourse.git_branch },
+ )
default_payload.merge!(get_payload)
end
def self.discourse_version_check
- get('/version_check', version_check_payload)
+ get("/version_check", version_check_payload)
end
def self.stats_fetched_at=(time_with_zone)
@@ -18,7 +19,11 @@ module DiscourseHub
end
def self.get_payload
- SiteSetting.share_anonymized_statistics && stats_fetched_at < 7.days.ago ? About.fetch_cached_stats.symbolize_keys : {}
+ if SiteSetting.share_anonymized_statistics && stats_fetched_at < 7.days.ago
+ About.fetch_cached_stats.symbolize_keys
+ else
+ {}
+ end
end
def self.get(rel_url, params = {})
@@ -40,27 +45,39 @@ module DiscourseHub
def self.singular_action(action, rel_url, params = {})
connect_opts = connect_opts(params)
- JSON.parse(Excon.public_send(action,
- "#{hub_base_url}#{rel_url}",
- {
- headers: { 'Referer' => referer, 'Accept' => accepts.join(', ') },
- query: params,
- omit_default_port: true
- }.merge(connect_opts)
- ).body)
+ JSON.parse(
+ Excon.public_send(
+ action,
+ "#{hub_base_url}#{rel_url}",
+ {
+ headers: {
+ "Referer" => referer,
+ "Accept" => accepts.join(", "),
+ },
+ query: params,
+ omit_default_port: true,
+ }.merge(connect_opts),
+ ).body,
+ )
end
def self.collection_action(action, rel_url, params = {})
connect_opts = connect_opts(params)
- response = Excon.public_send(action,
- "#{hub_base_url}#{rel_url}",
- {
- body: JSON[params],
- headers: { 'Referer' => referer, 'Accept' => accepts.join(', '), "Content-Type" => "application/json" },
- omit_default_port: true
- }.merge(connect_opts)
- )
+ response =
+ Excon.public_send(
+ action,
+ "#{hub_base_url}#{rel_url}",
+ {
+ body: JSON[params],
+ headers: {
+ "Referer" => referer,
+ "Accept" => accepts.join(", "),
+ "Content-Type" => "application/json",
+ },
+ omit_default_port: true,
+ }.merge(connect_opts),
+ )
if (status = response.status) != 200
Rails.logger.warn(response_status_log_message(rel_url, status))
@@ -87,14 +104,14 @@ module DiscourseHub
def self.hub_base_url
if Rails.env.production?
- ENV['HUB_BASE_URL'] || 'https://api.discourse.org/api'
+ ENV["HUB_BASE_URL"] || "https://api.discourse.org/api"
else
- ENV['HUB_BASE_URL'] || 'http://local.hub:3000/api'
+ ENV["HUB_BASE_URL"] || "http://local.hub:3000/api"
end
end
def self.accepts
- ['application/json', 'application/vnd.discoursehub.v1']
+ %w[application/json application/vnd.discoursehub.v1]
end
def self.referer
@@ -105,5 +122,4 @@ module DiscourseHub
t = Discourse.redis.get(STATS_FETCHED_AT_KEY)
t ? Time.zone.at(t.to_i) : 1.year.ago
end
-
end
diff --git a/lib/discourse_ip_info.rb b/lib/discourse_ip_info.rb
index 7f7116c47da..2949f5858cb 100644
--- a/lib/discourse_ip_info.rb
+++ b/lib/discourse_ip_info.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'maxminddb'
-require 'resolv'
+require "maxminddb"
+require "resolv"
class DiscourseIpInfo
include Singleton
@@ -11,13 +11,13 @@ class DiscourseIpInfo
end
def open_db(path)
- @loc_mmdb = mmdb_load(File.join(path, 'GeoLite2-City.mmdb'))
- @asn_mmdb = mmdb_load(File.join(path, 'GeoLite2-ASN.mmdb'))
+ @loc_mmdb = mmdb_load(File.join(path, "GeoLite2-City.mmdb"))
+ @asn_mmdb = mmdb_load(File.join(path, "GeoLite2-ASN.mmdb"))
@cache = LruRedux::ThreadSafeCache.new(2000)
end
def self.path
- @path ||= File.join(Rails.root, 'vendor', 'data')
+ @path ||= File.join(Rails.root, "vendor", "data")
end
def self.mmdb_path(name)
@@ -25,7 +25,6 @@ class DiscourseIpInfo
end
def self.mmdb_download(name)
-
if GlobalSetting.maxmind_license_key.blank?
STDERR.puts "MaxMind IP database updates require a license"
STDERR.puts "Please set DISCOURSE_MAXMIND_LICENSE_KEY to one you generated at https://www.maxmind.com"
@@ -34,41 +33,29 @@ class DiscourseIpInfo
FileUtils.mkdir_p(path)
- url = "https://download.maxmind.com/app/geoip_download?license_key=#{GlobalSetting.maxmind_license_key}&edition_id=#{name}&suffix=tar.gz"
+ url =
+ "https://download.maxmind.com/app/geoip_download?license_key=#{GlobalSetting.maxmind_license_key}&edition_id=#{name}&suffix=tar.gz"
- gz_file = FileHelper.download(
- url,
- max_file_size: 100.megabytes,
- tmp_file_name: "#{name}.gz",
- validate_uri: false,
- follow_redirect: false
- )
+ gz_file =
+ FileHelper.download(
+ url,
+ max_file_size: 100.megabytes,
+ tmp_file_name: "#{name}.gz",
+ validate_uri: false,
+ follow_redirect: false,
+ )
filename = File.basename(gz_file.path)
dir = "#{Dir.tmpdir}/#{SecureRandom.hex}"
- Discourse::Utils.execute_command(
- "mkdir", "-p", dir
- )
-
- Discourse::Utils.execute_command(
- "cp",
- gz_file.path,
- "#{dir}/#{filename}"
- )
+ Discourse::Utils.execute_command("mkdir", "-p", dir)
- Discourse::Utils.execute_command(
- "tar",
- "-xzvf",
- "#{dir}/#{filename}",
- chdir: dir
- )
+ Discourse::Utils.execute_command("cp", gz_file.path, "#{dir}/#{filename}")
- Dir["#{dir}/**/*.mmdb"].each do |f|
- FileUtils.mv(f, mmdb_path(name))
- end
+ Discourse::Utils.execute_command("tar", "-xzvf", "#{dir}/#{filename}", chdir: dir)
+ Dir["#{dir}/**/*.mmdb"].each { |f| FileUtils.mv(f, mmdb_path(name)) }
ensure
FileUtils.rm_r(dir, force: true) if dir
gz_file&.close!
@@ -96,7 +83,8 @@ class DiscourseIpInfo
if result&.found?
ret[:country] = result.country.name(locale) || result.country.name
ret[:country_code] = result.country.iso_code
- ret[:region] = result.subdivisions.most_specific.name(locale) || result.subdivisions.most_specific.name
+ ret[:region] = result.subdivisions.most_specific.name(locale) ||
+ result.subdivisions.most_specific.name
ret[:city] = result.city.name(locale) || result.city.name
ret[:latitude] = result.location.latitude
ret[:longitude] = result.location.longitude
@@ -104,13 +92,18 @@ class DiscourseIpInfo
# used by plugins or API to locate users more accurately
ret[:geoname_ids] = [
- result.continent.geoname_id, result.country.geoname_id, result.city.geoname_id,
- *result.subdivisions.map(&:geoname_id)
+ result.continent.geoname_id,
+ result.country.geoname_id,
+ result.city.geoname_id,
+ *result.subdivisions.map(&:geoname_id),
]
ret[:geoname_ids].compact!
end
rescue => e
- Discourse.warn_exception(e, message: "IP #{ip} could not be looked up in MaxMind GeoLite2-City database.")
+ Discourse.warn_exception(
+ e,
+ message: "IP #{ip} could not be looked up in MaxMind GeoLite2-City database.",
+ )
end
end
@@ -123,7 +116,10 @@ class DiscourseIpInfo
ret[:organization] = result["autonomous_system_organization"]
end
rescue => e
- Discourse.warn_exception(e, message: "IP #{ip} could not be looked up in MaxMind GeoLite2-ASN database.")
+ Discourse.warn_exception(
+ e,
+ message: "IP #{ip} could not be looked up in MaxMind GeoLite2-ASN database.",
+ )
end
end
@@ -142,10 +138,13 @@ class DiscourseIpInfo
def get(ip, locale: :en, resolve_hostname: false)
ip = ip.to_s
- locale = locale.to_s.sub('_', '-')
+ locale = locale.to_s.sub("_", "-")
- @cache["#{ip}-#{locale}-#{resolve_hostname}"] ||=
- lookup(ip, locale: locale, resolve_hostname: resolve_hostname)
+ @cache["#{ip}-#{locale}-#{resolve_hostname}"] ||= lookup(
+ ip,
+ locale: locale,
+ resolve_hostname: resolve_hostname,
+ )
end
def self.open_db(path)
diff --git a/lib/discourse_js_processor.rb b/lib/discourse_js_processor.rb
index 11f1ee27672..ae167ffe57f 100644
--- a/lib/discourse_js_processor.rb
+++ b/lib/discourse_js_processor.rb
@@ -1,27 +1,28 @@
# frozen_string_literal: true
-require 'execjs'
-require 'mini_racer'
+require "execjs"
+require "mini_racer"
class DiscourseJsProcessor
- class TranspileError < StandardError; end
+ class TranspileError < StandardError
+ end
DISCOURSE_COMMON_BABEL_PLUGINS = [
- 'proposal-optional-chaining',
- ['proposal-decorators', { legacy: true } ],
- 'transform-template-literals',
- 'proposal-class-properties',
- 'proposal-class-static-block',
- 'proposal-private-property-in-object',
- 'proposal-private-methods',
- 'proposal-numeric-separator',
- 'proposal-logical-assignment-operators',
- 'proposal-nullish-coalescing-operator',
- 'proposal-json-strings',
- 'proposal-optional-catch-binding',
- 'transform-parameters',
- 'proposal-async-generator-functions',
- 'proposal-object-rest-spread',
- 'proposal-export-namespace-from',
+ "proposal-optional-chaining",
+ ["proposal-decorators", { legacy: true }],
+ "transform-template-literals",
+ "proposal-class-properties",
+ "proposal-class-static-block",
+ "proposal-private-property-in-object",
+ "proposal-private-methods",
+ "proposal-numeric-separator",
+ "proposal-logical-assignment-operators",
+ "proposal-nullish-coalescing-operator",
+ "proposal-json-strings",
+ "proposal-optional-catch-binding",
+ "transform-parameters",
+ "proposal-async-generator-functions",
+ "proposal-object-rest-spread",
+ "proposal-export-namespace-from",
]
def self.plugin_transpile_paths
@@ -33,22 +34,22 @@ class DiscourseJsProcessor
end
def self.call(input)
- root_path = input[:load_path] || ''
- logical_path = (input[:filename] || '').sub(root_path, '').gsub(/\.(js|es6).*$/, '').sub(/^\//, '')
+ root_path = input[:load_path] || ""
+ logical_path =
+ (input[:filename] || "").sub(root_path, "").gsub(/\.(js|es6).*$/, "").sub(%r{^/}, "")
data = input[:data]
- if should_transpile?(input[:filename])
- data = transpile(data, root_path, logical_path)
- end
+ data = transpile(data, root_path, logical_path) if should_transpile?(input[:filename])
# add sourceURL until we can do proper source maps
if !Rails.env.production? && !ember_cli?(input[:filename])
- plugin_name = root_path[/\/plugins\/([\w-]+)\/assets/, 1]
- source_url = if plugin_name
- "plugins/#{plugin_name}/assets/javascripts/#{logical_path}"
- else
- logical_path
- end
+ plugin_name = root_path[%r{/plugins/([\w-]+)/assets}, 1]
+ source_url =
+ if plugin_name
+ "plugins/#{plugin_name}/assets/javascripts/#{logical_path}"
+ else
+ logical_path
+ end
data = "eval(#{data.inspect} + \"\\n//# sourceURL=#{source_url}\");\n"
end
@@ -62,7 +63,7 @@ class DiscourseJsProcessor
end
def self.should_transpile?(filename)
- filename ||= ''
+ filename ||= ""
# skip ember cli
return false if ember_cli?(filename)
@@ -73,7 +74,7 @@ class DiscourseJsProcessor
# For .js check the path...
return false unless filename.end_with?(".js") || filename.end_with?(".js.erb")
- relative_path = filename.sub(Rails.root.to_s, '').sub(/^\/*/, '')
+ relative_path = filename.sub(Rails.root.to_s, "").sub(%r{^/*}, "")
js_root = "app/assets/javascripts"
test_root = "test/javascripts"
@@ -81,26 +82,27 @@ class DiscourseJsProcessor
return false if relative_path.start_with?("#{js_root}/locales/")
return false if relative_path.start_with?("#{js_root}/plugins/")
- return true if %w(
- start-discourse
- onpopstate-handler
- google-tag-manager
- google-universal-analytics-v3
- google-universal-analytics-v4
- activate-account
- auto-redirect
- embed-application
- app-boot
- ).any? { |f| relative_path == "#{js_root}/#{f}.js" }
+ if %w[
+ start-discourse
+ onpopstate-handler
+ google-tag-manager
+ google-universal-analytics-v3
+ google-universal-analytics-v4
+ activate-account
+ auto-redirect
+ embed-application
+ app-boot
+ ].any? { |f| relative_path == "#{js_root}/#{f}.js" }
+ return true
+ end
return true if plugin_transpile_paths.any? { |prefix| relative_path.start_with?(prefix) }
- !!(relative_path =~ /^#{js_root}\/[^\/]+\// ||
- relative_path =~ /^#{test_root}\/[^\/]+\//)
+ !!(relative_path =~ %r{^#{js_root}/[^/]+/} || relative_path =~ %r{^#{test_root}/[^/]+/})
end
def self.skip_module?(data)
- !!(data.present? && data =~ /^\/\/ discourse-skip-module$/)
+ !!(data.present? && data =~ %r{^// discourse-skip-module$})
end
class Transpiler
@@ -113,19 +115,17 @@ class DiscourseJsProcessor
def self.load_file_in_context(ctx, path, wrap_in_module: nil)
contents = File.read("#{Rails.root}/app/assets/javascripts/#{path}")
- if wrap_in_module
- contents = <<~JS
+ contents = <<~JS if wrap_in_module
define(#{wrap_in_module.to_json}, ["exports", "require", "module"], function(exports, require, module){
#{contents}
});
JS
- end
ctx.eval(contents, filename: path)
end
def self.create_new_context
# timeout any eval that takes longer than 15 seconds
- ctx = MiniRacer::Context.new(timeout: 15000, ensure_gc_after_idle: 2000)
+ ctx = MiniRacer::Context.new(timeout: 15_000, ensure_gc_after_idle: 2000)
# General shims
ctx.attach("rails.logger.info", proc { |err| Rails.logger.info(err.to_s) })
@@ -158,10 +158,26 @@ class DiscourseJsProcessor
# Template Compiler
load_file_in_context(ctx, "node_modules/ember-source/dist/ember-template-compiler.js")
- load_file_in_context(ctx, "node_modules/babel-plugin-ember-template-compilation/src/plugin.js", wrap_in_module: "babel-plugin-ember-template-compilation/index")
- load_file_in_context(ctx, "node_modules/babel-plugin-ember-template-compilation/src/expression-parser.js", wrap_in_module: "babel-plugin-ember-template-compilation/expression-parser")
- load_file_in_context(ctx, "node_modules/babel-import-util/src/index.js", wrap_in_module: "babel-import-util")
- load_file_in_context(ctx, "node_modules/ember-cli-htmlbars/lib/colocated-babel-plugin.js", wrap_in_module: "colocated-babel-plugin")
+ load_file_in_context(
+ ctx,
+ "node_modules/babel-plugin-ember-template-compilation/src/plugin.js",
+ wrap_in_module: "babel-plugin-ember-template-compilation/index",
+ )
+ load_file_in_context(
+ ctx,
+ "node_modules/babel-plugin-ember-template-compilation/src/expression-parser.js",
+ wrap_in_module: "babel-plugin-ember-template-compilation/expression-parser",
+ )
+ load_file_in_context(
+ ctx,
+ "node_modules/babel-import-util/src/index.js",
+ wrap_in_module: "babel-import-util",
+ )
+ load_file_in_context(
+ ctx,
+ "node_modules/ember-cli-htmlbars/lib/colocated-babel-plugin.js",
+ wrap_in_module: "colocated-babel-plugin",
+ )
# Widget HBS compiler
widget_hbs_compiler_source = File.read("#{Rails.root}/lib/javascripts/widget-hbs-compiler.js")
@@ -170,32 +186,44 @@ class DiscourseJsProcessor
#{widget_hbs_compiler_source}
});
JS
- widget_hbs_compiler_transpiled = ctx.call("rawBabelTransform", widget_hbs_compiler_source, {
- ast: false,
- moduleId: 'widget-hbs-compiler',
- plugins: DISCOURSE_COMMON_BABEL_PLUGINS
- })
+ widget_hbs_compiler_transpiled =
+ ctx.call(
+ "rawBabelTransform",
+ widget_hbs_compiler_source,
+ { ast: false, moduleId: "widget-hbs-compiler", plugins: DISCOURSE_COMMON_BABEL_PLUGINS },
+ )
ctx.eval(widget_hbs_compiler_transpiled, filename: "widget-hbs-compiler.js")
# Raw HBS compiler
- load_file_in_context(ctx, "node_modules/handlebars/dist/handlebars.js", wrap_in_module: "handlebars")
-
- raw_hbs_transpiled = ctx.call(
- "rawBabelTransform",
- File.read("#{Rails.root}/app/assets/javascripts/discourse-common/addon/lib/raw-handlebars.js"),
- {
- ast: false,
- moduleId: "raw-handlebars",
- plugins: [
- ['transform-modules-amd', { noInterop: true }],
- *DISCOURSE_COMMON_BABEL_PLUGINS
- ]
- }
+ load_file_in_context(
+ ctx,
+ "node_modules/handlebars/dist/handlebars.js",
+ wrap_in_module: "handlebars",
)
+
+ raw_hbs_transpiled =
+ ctx.call(
+ "rawBabelTransform",
+ File.read(
+ "#{Rails.root}/app/assets/javascripts/discourse-common/addon/lib/raw-handlebars.js",
+ ),
+ {
+ ast: false,
+ moduleId: "raw-handlebars",
+ plugins: [
+ ["transform-modules-amd", { noInterop: true }],
+ *DISCOURSE_COMMON_BABEL_PLUGINS,
+ ],
+ },
+ )
ctx.eval(raw_hbs_transpiled, filename: "raw-handlebars.js")
# Theme template AST transformation plugins
- load_file_in_context(ctx, "discourse-js-processor.js", wrap_in_module: "discourse-js-processor")
+ load_file_in_context(
+ ctx,
+ "discourse-js-processor.js",
+ wrap_in_module: "discourse-js-processor",
+ )
# Make interfaces available via `v8.call`
ctx.eval <<~JS
@@ -262,10 +290,10 @@ class DiscourseJsProcessor
{
skip_module: @skip_module,
moduleId: module_name(root_path, logical_path),
- filename: logical_path || 'unknown',
+ filename: logical_path || "unknown",
themeId: theme_id,
- commonPlugins: DISCOURSE_COMMON_BABEL_PLUGINS
- }
+ commonPlugins: DISCOURSE_COMMON_BABEL_PLUGINS,
+ },
)
end
@@ -274,15 +302,16 @@ class DiscourseJsProcessor
root_base = File.basename(Rails.root)
# If the resource is a plugin, use the plugin name as a prefix
- if root_path =~ /(.*\/#{root_base}\/plugins\/[^\/]+)\//
+ if root_path =~ %r{(.*/#{root_base}/plugins/[^/]+)/}
plugin_path = "#{Regexp.last_match[1]}/plugin.rb"
plugin = Discourse.plugins.find { |p| p.path == plugin_path }
- path = "discourse/plugins/#{plugin.name}/#{logical_path.sub(/javascripts\//, '')}" if plugin
+ path =
+ "discourse/plugins/#{plugin.name}/#{logical_path.sub(%r{javascripts/}, "")}" if plugin
end
# We need to strip the app subdirectory to replicate how ember-cli works.
- path || logical_path&.gsub('app/', '')&.gsub('addon/', '')&.gsub('admin/addon', 'admin')
+ path || logical_path&.gsub("app/", "")&.gsub("addon/", "")&.gsub("admin/addon", "admin")
end
def compile_raw_template(source, theme_id: nil)
diff --git a/lib/discourse_logstash_logger.rb b/lib/discourse_logstash_logger.rb
index ee1b739133d..15225d33849 100644
--- a/lib/discourse_logstash_logger.rb
+++ b/lib/discourse_logstash_logger.rb
@@ -1,27 +1,28 @@
# frozen_string_literal: true
-require 'logstash-logger'
+require "logstash-logger"
class DiscourseLogstashLogger
def self.logger(uri:, type:)
# See Discourse.os_hostname
- hostname = begin
- require 'socket'
- Socket.gethostname
- rescue => e
- `hostname`.chomp
- end
+ hostname =
+ begin
+ require "socket"
+ Socket.gethostname
+ rescue => e
+ `hostname`.chomp
+ end
LogStashLogger.new(
uri: uri,
sync: true,
- customize_event: ->(event) {
- event['hostname'] = hostname
- event['severity_name'] = event['severity']
- event['severity'] = Object.const_get("Logger::Severity::#{event['severity']}")
- event['type'] = type
- event['pid'] = Process.pid
- },
+ customize_event: ->(event) do
+ event["hostname"] = hostname
+ event["severity_name"] = event["severity"]
+ event["severity"] = Object.const_get("Logger::Severity::#{event["severity"]}")
+ event["type"] = type
+ event["pid"] = Process.pid
+ end,
)
end
end
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index b6bcbb98211..9f0fd9e6082 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -4,7 +4,6 @@
# A class that handles interaction between a plugin and the Discourse App.
#
class DiscoursePluginRegistry
-
# Plugins often need to be able to register additional handlers, data, or
# classes that will be used by core classes. This should be used if you
# need to control which type the registry is, and if it doesn't need to
@@ -24,9 +23,7 @@ class DiscoursePluginRegistry
instance_variable_set(:"@#{register_name}", type.new)
end
- define_method(register_name) do
- self.class.public_send(register_name)
- end
+ define_method(register_name) { self.class.public_send(register_name) }
end
# Plugins often need to add values to a list, and we need to filter those
@@ -45,10 +42,7 @@ class DiscoursePluginRegistry
define_singleton_method(register_name) do
unfiltered = public_send(:"_raw_#{register_name}")
- unfiltered
- .filter { |v| v[:plugin].enabled? }
- .map { |v| v[:value] }
- .uniq
+ unfiltered.filter { |v| v[:plugin].enabled? }.map { |v| v[:value] }.uniq
end
define_singleton_method("register_#{register_name.to_s.singularize}") do |value, plugin|
@@ -158,9 +152,7 @@ class DiscoursePluginRegistry
next if each_options[:admin]
end
- Dir.glob("#{root}/**/*.#{ext}") do |f|
- yield f
- end
+ Dir.glob("#{root}/**/*.#{ext}") { |f| yield f }
end
end
@@ -227,7 +219,7 @@ class DiscoursePluginRegistry
def self.seed_paths
result = SeedFu.fixture_paths.dup
- unless Rails.env.test? && ENV['LOAD_PLUGINS'] != "1"
+ unless Rails.env.test? && ENV["LOAD_PLUGINS"] != "1"
seed_path_builders.each { |b| result += b.call }
end
result.uniq
@@ -239,7 +231,7 @@ class DiscoursePluginRegistry
VENDORED_CORE_PRETTY_TEXT_MAP = {
"moment.js" => "vendor/assets/javascripts/moment.js",
- "moment-timezone.js" => "vendor/assets/javascripts/moment-timezone-with-data.js"
+ "moment-timezone.js" => "vendor/assets/javascripts/moment-timezone-with-data.js",
}
def self.core_asset_for_name(name)
asset = VENDORED_CORE_PRETTY_TEXT_MAP[name]
@@ -248,16 +240,12 @@ class DiscoursePluginRegistry
end
def self.reset!
- @@register_names.each do |name|
- instance_variable_set(:"@#{name}", nil)
- end
+ @@register_names.each { |name| instance_variable_set(:"@#{name}", nil) }
end
def self.reset_register!(register_name)
found_register = @@register_names.detect { |name| name == register_name }
- if found_register
- instance_variable_set(:"@#{found_register}", nil)
- end
+ instance_variable_set(:"@#{found_register}", nil) if found_register
end
end
diff --git a/lib/discourse_redis.rb b/lib/discourse_redis.rb
index 4c661cc9afe..e47e9734c56 100644
--- a/lib/discourse_redis.rb
+++ b/lib/discourse_redis.rb
@@ -46,15 +46,103 @@ class DiscourseRedis
end
# Proxy key methods through, but prefix the keys with the namespace
- [:append, :blpop, :brpop, :brpoplpush, :decr, :decrby, :expire, :expireat, :get, :getbit, :getrange, :getset,
- :hdel, :hexists, :hget, :hgetall, :hincrby, :hincrbyfloat, :hkeys, :hlen, :hmget, :hmset, :hset, :hsetnx, :hvals, :incr,
- :incrby, :incrbyfloat, :lindex, :linsert, :llen, :lpop, :lpush, :lpushx, :lrange, :lrem, :lset, :ltrim,
- :mapped_hmset, :mapped_hmget, :mapped_mget, :mapped_mset, :mapped_msetnx, :move, :mset,
- :msetnx, :persist, :pexpire, :pexpireat, :psetex, :pttl, :rename, :renamenx, :rpop, :rpoplpush, :rpush, :rpushx, :sadd, :sadd?, :scard,
- :sdiff, :set, :setbit, :setex, :setnx, :setrange, :sinter, :sismember, :smembers, :sort, :spop, :srandmember, :srem, :srem?, :strlen,
- :sunion, :ttl, :type, :watch, :zadd, :zcard, :zcount, :zincrby, :zrange, :zrangebyscore, :zrank, :zrem, :zremrangebyrank,
- :zremrangebyscore, :zrevrange, :zrevrangebyscore, :zrevrank, :zrangebyscore,
- :dump, :restore].each do |m|
+ %i[
+ append
+ blpop
+ brpop
+ brpoplpush
+ decr
+ decrby
+ expire
+ expireat
+ get
+ getbit
+ getrange
+ getset
+ hdel
+ hexists
+ hget
+ hgetall
+ hincrby
+ hincrbyfloat
+ hkeys
+ hlen
+ hmget
+ hmset
+ hset
+ hsetnx
+ hvals
+ incr
+ incrby
+ incrbyfloat
+ lindex
+ linsert
+ llen
+ lpop
+ lpush
+ lpushx
+ lrange
+ lrem
+ lset
+ ltrim
+ mapped_hmset
+ mapped_hmget
+ mapped_mget
+ mapped_mset
+ mapped_msetnx
+ move
+ mset
+ msetnx
+ persist
+ pexpire
+ pexpireat
+ psetex
+ pttl
+ rename
+ renamenx
+ rpop
+ rpoplpush
+ rpush
+ rpushx
+ sadd
+ sadd?
+ scard
+ sdiff
+ set
+ setbit
+ setex
+ setnx
+ setrange
+ sinter
+ sismember
+ smembers
+ sort
+ spop
+ srandmember
+ srem
+ srem?
+ strlen
+ sunion
+ ttl
+ type
+ watch
+ zadd
+ zcard
+ zcount
+ zincrby
+ zrange
+ zrangebyscore
+ zrank
+ zrem
+ zremrangebyrank
+ zremrangebyscore
+ zrevrange
+ zrevrangebyscore
+ zrevrank
+ zrangebyscore
+ dump
+ restore
+ ].each do |m|
define_method m do |*args, **kwargs|
args[0] = "#{namespace}:#{args[0]}" if @namespace
DiscourseRedis.ignore_readonly { @redis.public_send(m, *args, **kwargs) }
@@ -72,7 +160,7 @@ class DiscourseRedis
end
def mget(*args)
- args.map! { |a| "#{namespace}:#{a}" } if @namespace
+ args.map! { |a| "#{namespace}:#{a}" } if @namespace
DiscourseRedis.ignore_readonly { @redis.mget(*args) }
end
@@ -86,14 +174,13 @@ class DiscourseRedis
def scan_each(options = {}, &block)
DiscourseRedis.ignore_readonly do
- match = options[:match].presence || '*'
+ match = options[:match].presence || "*"
- options[:match] =
- if @namespace
- "#{namespace}:#{match}"
- else
- match
- end
+ options[:match] = if @namespace
+ "#{namespace}:#{match}"
+ else
+ match
+ end
if block
@redis.scan_each(**options) do |key|
@@ -101,17 +188,19 @@ class DiscourseRedis
block.call(key)
end
else
- @redis.scan_each(**options).map do |key|
- key = remove_namespace(key) if @namespace
- key
- end
+ @redis
+ .scan_each(**options)
+ .map do |key|
+ key = remove_namespace(key) if @namespace
+ key
+ end
end
end
end
def keys(pattern = nil)
DiscourseRedis.ignore_readonly do
- pattern = pattern || '*'
+ pattern = pattern || "*"
pattern = "#{namespace}:#{pattern}" if @namespace
keys = @redis.keys(pattern)
@@ -125,9 +214,7 @@ class DiscourseRedis
end
def delete_prefixed(prefix)
- DiscourseRedis.ignore_readonly do
- keys("#{prefix}*").each { |k| Discourse.redis.del(k) }
- end
+ DiscourseRedis.ignore_readonly { keys("#{prefix}*").each { |k| Discourse.redis.del(k) } }
end
def reconnect
diff --git a/lib/discourse_sourcemapping_url_processor.rb b/lib/discourse_sourcemapping_url_processor.rb
index 7b6ae82d563..29095863c50 100644
--- a/lib/discourse_sourcemapping_url_processor.rb
+++ b/lib/discourse_sourcemapping_url_processor.rb
@@ -6,7 +6,8 @@
class DiscourseSourcemappingUrlProcessor < Sprockets::Rails::SourcemappingUrlProcessor
def self.sourcemap_asset_path(sourcemap_logical_path, context:)
result = super(sourcemap_logical_path, context: context)
- if (File.basename(sourcemap_logical_path) === sourcemap_logical_path) || sourcemap_logical_path.start_with?("plugins/")
+ if (File.basename(sourcemap_logical_path) === sourcemap_logical_path) ||
+ sourcemap_logical_path.start_with?("plugins/")
# If the original sourcemap reference is relative, keep it relative
result = File.basename(result)
end
diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rb
index e68b9032cdf..8a8c2d7f878 100644
--- a/lib/discourse_tagging.rb
+++ b/lib/discourse_tagging.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module DiscourseTagging
-
TAGS_FIELD_NAME ||= "tags"
TAGS_FILTER_REGEXP ||= /[\/\?#\[\]@!\$&'\(\)\*\+,;=\.%\\`^\s|\{\}"<>]+/ # /?#[]@!$&'()*+,;=.%\`^|{}"<>
TAGS_STAFF_CACHE_KEY ||= "staff_tag_names"
@@ -22,9 +21,11 @@ module DiscourseTagging
tag_names = DiscourseTagging.tags_for_saving(tag_names_arg, guardian) || []
if !tag_names.empty?
- Tag.where_name(tag_names).joins(:target_tag).includes(:target_tag).each do |tag|
- tag_names[tag_names.index(tag.name)] = tag.target_tag.name
- end
+ Tag
+ .where_name(tag_names)
+ .joins(:target_tag)
+ .includes(:target_tag)
+ .each { |tag| tag_names[tag_names.index(tag.name)] = tag.target_tag.name }
end
# tags currently on the topic
@@ -45,9 +46,7 @@ module DiscourseTagging
# If this user has explicit permission to use certain tags,
# we need to ensure those tags are removed from the list of
# restricted tags
- if permitted_tags.present?
- readonly_tags = readonly_tags - permitted_tags
- end
+ readonly_tags = readonly_tags - permitted_tags if permitted_tags.present?
# visible, but not usable, tags this user is trying to use
disallowed_tags = new_tag_names & readonly_tags
@@ -55,13 +54,19 @@ module DiscourseTagging
disallowed_tags += new_tag_names & hidden_tags
if disallowed_tags.present?
- topic.errors.add(:base, I18n.t("tags.restricted_tag_disallowed", tag: disallowed_tags.join(" ")))
+ topic.errors.add(
+ :base,
+ I18n.t("tags.restricted_tag_disallowed", tag: disallowed_tags.join(" ")),
+ )
return false
end
removed_readonly_tags = removed_tag_names & readonly_tags
if removed_readonly_tags.present?
- topic.errors.add(:base, I18n.t("tags.restricted_tag_remove_disallowed", tag: removed_readonly_tags.join(" ")))
+ topic.errors.add(
+ :base,
+ I18n.t("tags.restricted_tag_remove_disallowed", tag: removed_readonly_tags.join(" ")),
+ )
return false
end
@@ -73,50 +78,61 @@ module DiscourseTagging
if tag_names.present?
# guardian is explicitly nil cause we don't want to strip all
# staff tags that already passed validation
- tags = filter_allowed_tags(
- nil, # guardian
- for_topic: true,
- category: category,
- selected_tags: tag_names,
- only_tag_names: tag_names
- )
+ tags =
+ filter_allowed_tags(
+ nil, # guardian
+ for_topic: true,
+ category: category,
+ selected_tags: tag_names,
+ only_tag_names: tag_names,
+ )
# keep existent tags that current user cannot use
tags += Tag.where(name: old_tag_names & tag_names)
tags = Tag.where(id: tags.map(&:id)).all.to_a if tags.size > 0
- if tags.size < tag_names.size && (category.nil? || category.allow_global_tags || (category.tags.count == 0 && category.tag_groups.count == 0))
+ if tags.size < tag_names.size &&
+ (
+ category.nil? || category.allow_global_tags ||
+ (category.tags.count == 0 && category.tag_groups.count == 0)
+ )
tag_names.each do |name|
- unless Tag.where_name(name).exists?
- tags << Tag.create(name: name)
- end
+ tags << Tag.create(name: name) unless Tag.where_name(name).exists?
end
end
# add missing mandatory parent tags
tag_ids = tags.map(&:id)
- parent_tags_map = DB.query("
+ parent_tags_map =
+ DB
+ .query(
+ "
SELECT tgm.tag_id, tg.parent_tag_id
FROM tag_groups tg
INNER JOIN tag_group_memberships tgm
ON tgm.tag_group_id = tg.id
WHERE tg.parent_tag_id IS NOT NULL
AND tgm.tag_id IN (?)
- ", tag_ids).inject({}) do |h, v|
- h[v.tag_id] ||= []
- h[v.tag_id] << v.parent_tag_id
- h
- end
+ ",
+ tag_ids,
+ )
+ .inject({}) do |h, v|
+ h[v.tag_id] ||= []
+ h[v.tag_id] << v.parent_tag_id
+ h
+ end
- missing_parent_tag_ids = parent_tags_map.map do |_, parent_tag_ids|
- (tag_ids & parent_tag_ids).size == 0 ? parent_tag_ids.first : nil
- end.compact.uniq
+ missing_parent_tag_ids =
+ parent_tags_map
+ .map do |_, parent_tag_ids|
+ (tag_ids & parent_tag_ids).size == 0 ? parent_tag_ids.first : nil
+ end
+ .compact
+ .uniq
- unless missing_parent_tag_ids.empty?
- tags = tags + Tag.where(id: missing_parent_tag_ids).all
- end
+ tags = tags + Tag.where(id: missing_parent_tag_ids).all unless missing_parent_tag_ids.empty?
return false unless validate_min_required_tags_for_category(guardian, topic, category, tags)
return false unless validate_required_tags_from_group(guardian, topic, category, tags)
@@ -137,7 +153,9 @@ module DiscourseTagging
DiscourseEvent.trigger(
:topic_tags_changed,
- topic, old_tag_names: old_tag_names, new_tag_names: topic.tags.map(&:name)
+ topic,
+ old_tag_names: old_tag_names,
+ new_tag_names: topic.tags.map(&:name),
)
return true
@@ -146,12 +164,12 @@ module DiscourseTagging
end
def self.validate_min_required_tags_for_category(guardian, model, category, tags = [])
- if !guardian.is_staff? &&
- category &&
- category.minimum_required_tags > 0 &&
- tags.length < category.minimum_required_tags
-
- model.errors.add(:base, I18n.t("tags.minimum_required_tags", count: category.minimum_required_tags))
+ if !guardian.is_staff? && category && category.minimum_required_tags > 0 &&
+ tags.length < category.minimum_required_tags
+ model.errors.add(
+ :base,
+ I18n.t("tags.minimum_required_tags", count: category.minimum_required_tags),
+ )
false
else
true
@@ -164,17 +182,17 @@ module DiscourseTagging
success = true
category.category_required_tag_groups.each do |crtg|
if tags.length < crtg.min_count ||
- crtg.tag_group.tags.where("tags.id in (?)", tags.map(&:id)).count < crtg.min_count
-
+ crtg.tag_group.tags.where("tags.id in (?)", tags.map(&:id)).count < crtg.min_count
success = false
- model.errors.add(:base,
+ model.errors.add(
+ :base,
I18n.t(
"tags.required_tags_from_group",
count: crtg.min_count,
tag_group_name: crtg.tag_group.name,
- tags: crtg.tag_group.tags.order(:id).pluck(:name).join(", ")
- )
+ tags: crtg.tag_group.tags.order(:id).pluck(:name).join(", "),
+ ),
)
end
end
@@ -189,24 +207,28 @@ module DiscourseTagging
tags_restricted_to_categories = Hash.new { |h, k| h[k] = Set.new }
query = Tag.where(name: tags)
- query.joins(tag_groups: :categories).pluck(:name, 'categories.id').each do |(tag, cat_id)|
- tags_restricted_to_categories[tag] << cat_id
- end
- query.joins(:categories).pluck(:name, 'categories.id').each do |(tag, cat_id)|
- tags_restricted_to_categories[tag] << cat_id
- end
-
- unallowed_tags = tags_restricted_to_categories.keys.select do |tag|
- !tags_restricted_to_categories[tag].include?(category.id)
- end
+ query
+ .joins(tag_groups: :categories)
+ .pluck(:name, "categories.id")
+ .each { |(tag, cat_id)| tags_restricted_to_categories[tag] << cat_id }
+ query
+ .joins(:categories)
+ .pluck(:name, "categories.id")
+ .each { |(tag, cat_id)| tags_restricted_to_categories[tag] << cat_id }
+
+ unallowed_tags =
+ tags_restricted_to_categories.keys.select do |tag|
+ !tags_restricted_to_categories[tag].include?(category.id)
+ end
if unallowed_tags.present?
- msg = I18n.t(
- "tags.forbidden.restricted_tags_cannot_be_used_in_category",
- count: unallowed_tags.size,
- tags: unallowed_tags.sort.join(", "),
- category: category.name
- )
+ msg =
+ I18n.t(
+ "tags.forbidden.restricted_tags_cannot_be_used_in_category",
+ count: unallowed_tags.size,
+ tags: unallowed_tags.sort.join(", "),
+ category: category.name,
+ )
model.errors.add(:base, msg)
return false
end
@@ -214,12 +236,13 @@ module DiscourseTagging
if !category.allow_global_tags && category.has_restricted_tags?
unrestricted_tags = tags - tags_restricted_to_categories.keys
if unrestricted_tags.present?
- msg = I18n.t(
- "tags.forbidden.category_does_not_allow_tags",
- count: unrestricted_tags.size,
- tags: unrestricted_tags.sort.join(", "),
- category: category.name
- )
+ msg =
+ I18n.t(
+ "tags.forbidden.category_does_not_allow_tags",
+ count: unrestricted_tags.size,
+ tags: unrestricted_tags.sort.join(", "),
+ category: category.name,
+ )
model.errors.add(:base, msg)
return false
end
@@ -280,7 +303,8 @@ module DiscourseTagging
def self.filter_allowed_tags(guardian, opts = {})
selected_tag_ids = opts[:selected_tags] ? Tag.where_name(opts[:selected_tags]).pluck(:id) : []
category = opts[:category]
- category_has_restricted_tags = category ? (category.tags.count > 0 || category.tag_groups.count > 0) : false
+ category_has_restricted_tags =
+ category ? (category.tags.count > 0 || category.tag_groups.count > 0) : false
# If guardian is nil, it means the caller doesn't want tags to be filtered
# based on guardian rules. Use the same rules as for staff users.
@@ -288,9 +312,7 @@ module DiscourseTagging
builder_params = {}
- unless selected_tag_ids.empty?
- builder_params[:selected_tag_ids] = selected_tag_ids
- end
+ builder_params[:selected_tag_ids] = selected_tag_ids unless selected_tag_ids.empty?
sql = +"WITH #{TAG_GROUP_RESTRICTIONS_SQL}, #{CATEGORY_RESTRICTIONS_SQL}"
if (opts[:for_input] || opts[:for_topic]) && filter_for_non_staff
@@ -301,13 +323,14 @@ module DiscourseTagging
outer_join = category.nil? || category.allow_global_tags || !category_has_restricted_tags
- distinct_clause = if opts[:order_popularity]
- "DISTINCT ON (topic_count, name)"
- elsif opts[:order_search_results] && opts[:term].present?
- "DISTINCT ON (lower(name) = lower(:cleaned_term), topic_count, name)"
- else
- ""
- end
+ distinct_clause =
+ if opts[:order_popularity]
+ "DISTINCT ON (topic_count, name)"
+ elsif opts[:order_search_results] && opts[:term].present?
+ "DISTINCT ON (lower(name) = lower(:cleaned_term), topic_count, name)"
+ else
+ ""
+ end
sql << <<~SQL
SELECT #{distinct_clause} t.id, t.name, t.topic_count, t.pm_topic_count, t.description,
@@ -336,16 +359,20 @@ module DiscourseTagging
# parent tag requirements
if opts[:for_input]
builder.where(
- builder_params[:selected_tag_ids] ?
- "tgm_id IS NULL OR parent_tag_id IS NULL OR parent_tag_id IN (:selected_tag_ids)" :
- "tgm_id IS NULL OR parent_tag_id IS NULL"
+ (
+ if builder_params[:selected_tag_ids]
+ "tgm_id IS NULL OR parent_tag_id IS NULL OR parent_tag_id IN (:selected_tag_ids)"
+ else
+ "tgm_id IS NULL OR parent_tag_id IS NULL"
+ end
+ ),
)
end
if category && category_has_restricted_tags
builder.where(
category.allow_global_tags ? "category_id = ? OR category_id IS NULL" : "category_id = ?",
- category.id
+ category.id,
)
elsif category || opts[:for_input] || opts[:for_topic]
# tags not restricted to any categories
@@ -354,7 +381,9 @@ module DiscourseTagging
if filter_for_non_staff && (opts[:for_input] || opts[:for_topic])
# exclude staff-only tag groups
- builder.where("tag_group_id IS NULL OR tag_group_id IN (SELECT tag_group_id FROM permitted_tag_groups)")
+ builder.where(
+ "tag_group_id IS NULL OR tag_group_id IN (SELECT tag_group_id FROM permitted_tag_groups)",
+ )
end
term = opts[:term]
@@ -380,7 +409,8 @@ module DiscourseTagging
# - and no search term has been included
required_tag_ids = nil
required_category_tag_group = nil
- if opts[:for_input] && category&.category_required_tag_groups.present? && (filter_for_non_staff || term.blank?)
+ if opts[:for_input] && category&.category_required_tag_groups.present? &&
+ (filter_for_non_staff || term.blank?)
category.category_required_tag_groups.each do |crtg|
group_tags = crtg.tag_group.tags.pluck(:id)
next if (group_tags & selected_tag_ids).size >= crtg.min_count
@@ -426,22 +456,18 @@ module DiscourseTagging
if !one_tag_per_group_ids.empty?
builder.where(
"tag_group_id IS NULL OR tag_group_id NOT IN (?) OR id IN (:selected_tag_ids)",
- one_tag_per_group_ids
+ one_tag_per_group_ids,
)
end
end
- if opts[:exclude_synonyms]
- builder.where("target_tag_id IS NULL")
- end
+ builder.where("target_tag_id IS NULL") if opts[:exclude_synonyms]
if opts[:exclude_has_synonyms]
builder.where("id NOT IN (SELECT target_tag_id FROM tags WHERE target_tag_id IS NOT NULL)")
end
- if opts[:excluded_tag_names]&.any?
- builder.where("name NOT IN (?)", opts[:excluded_tag_names])
- end
+ builder.where("name NOT IN (?)", opts[:excluded_tag_names]) if opts[:excluded_tag_names]&.any?
if opts[:limit]
if required_tag_ids && term.blank?
@@ -465,7 +491,7 @@ module DiscourseTagging
if required_category_tag_group
context[:required_tag_group] = {
name: required_category_tag_group.tag_group.name,
- min_count: required_category_tag_group.min_count
+ min_count: required_category_tag_group.min_count,
}
end
[result, context]
@@ -480,21 +506,15 @@ module DiscourseTagging
else
# Visible tags either have no permissions or have allowable permissions
Tag
- .where.not(
- id:
- TagGroupMembership
- .joins(tag_group: :tag_group_permissions)
- .select(:tag_id)
- )
+ .where.not(id: TagGroupMembership.joins(tag_group: :tag_group_permissions).select(:tag_id))
.or(
- Tag
- .where(
- id:
- TagGroupPermission
- .joins(tag_group: :tag_group_memberships)
- .where(group_id: permitted_group_ids_query(guardian))
- .select('tag_group_memberships.tag_id'),
- )
+ Tag.where(
+ id:
+ TagGroupPermission
+ .joins(tag_group: :tag_group_memberships)
+ .where(group_id: permitted_group_ids_query(guardian))
+ .select("tag_group_memberships.tag_id"),
+ ),
)
end
end
@@ -509,21 +529,18 @@ module DiscourseTagging
def self.permitted_group_ids_query(guardian = nil)
if guardian&.authenticated?
- Group
- .from(
- Group.sanitize_sql(
- ["(SELECT ? AS id UNION #{guardian.user.groups.select(:id).to_sql}) as groups", Group::AUTO_GROUPS[:everyone]]
- )
- )
- .select(:id)
+ Group.from(
+ Group.sanitize_sql(
+ [
+ "(SELECT ? AS id UNION #{guardian.user.groups.select(:id).to_sql}) as groups",
+ Group::AUTO_GROUPS[:everyone],
+ ],
+ ),
+ ).select(:id)
else
- Group
- .from(
- Group.sanitize_sql(
- ["(SELECT ? AS id) AS groups", Group::AUTO_GROUPS[:everyone]]
- )
- )
- .select(:id)
+ Group.from(
+ Group.sanitize_sql(["(SELECT ? AS id) AS groups", Group::AUTO_GROUPS[:everyone]]),
+ ).select(:id)
end
end
@@ -535,9 +552,11 @@ module DiscourseTagging
def self.readonly_tag_names(guardian = nil)
return [] if guardian&.is_staff?
- query = Tag.joins(tag_groups: :tag_group_permissions)
- .where('tag_group_permissions.permission_type = ?',
- TagGroupPermission.permission_types[:readonly])
+ query =
+ Tag.joins(tag_groups: :tag_group_permissions).where(
+ "tag_group_permissions.permission_type = ?",
+ TagGroupPermission.permission_types[:readonly],
+ )
query.pluck(:name)
end
@@ -545,14 +564,12 @@ module DiscourseTagging
# explicit permissions to use these tags
def self.permitted_tag_names(guardian = nil)
query =
- Tag
- .joins(tag_groups: :tag_group_permissions)
- .where(
- tag_group_permissions: {
- group_id: permitted_group_ids(guardian),
- permission_type: TagGroupPermission.permission_types[:full],
- },
- )
+ Tag.joins(tag_groups: :tag_group_permissions).where(
+ tag_group_permissions: {
+ group_id: permitted_group_ids(guardian),
+ permission_type: TagGroupPermission.permission_types[:full],
+ },
+ )
query.pluck(:name).uniq
end
@@ -586,15 +603,14 @@ module DiscourseTagging
tag = tag.dup
tag.downcase! if SiteSetting.force_lowercase_tags
tag.strip!
- tag.gsub!(/[[:space:]]+/, '-')
- tag.gsub!(/[^[:word:][:punct:]]+/, '')
- tag.squeeze!('-')
- tag.gsub!(TAGS_FILTER_REGEXP, '')
+ tag.gsub!(/[[:space:]]+/, "-")
+ tag.gsub!(/[^[:word:][:punct:]]+/, "")
+ tag.squeeze!("-")
+ tag.gsub!(TAGS_FILTER_REGEXP, "")
tag[0...SiteSetting.max_tag_length]
end
def self.tags_for_saving(tags_arg, guardian, opts = {})
-
return [] unless guardian.can_tag_topics? && tags_arg.present?
tag_names = Tag.where_name(tags_arg).pluck(:name)
@@ -609,21 +625,23 @@ module DiscourseTagging
end
def self.add_or_create_tags_by_name(taggable, tag_names_arg, opts = {})
- tag_names = DiscourseTagging.tags_for_saving(tag_names_arg, Guardian.new(Discourse.system_user), opts) || []
+ tag_names =
+ DiscourseTagging.tags_for_saving(tag_names_arg, Guardian.new(Discourse.system_user), opts) ||
+ []
if taggable.tags.pluck(:name).sort != tag_names.sort
taggable.tags = Tag.where_name(tag_names).all
- new_tag_names = taggable.tags.size < tag_names.size ? tag_names - taggable.tags.map(&:name) : []
+ new_tag_names =
+ taggable.tags.size < tag_names.size ? tag_names - taggable.tags.map(&:name) : []
taggable.tags << Tag.where(target_tag_id: taggable.tags.map(&:id)).all
- new_tag_names.each do |name|
- taggable.tags << Tag.create(name: name)
- end
+ new_tag_names.each { |name| taggable.tags << Tag.create(name: name) }
end
end
# Returns true if all were added successfully, or an Array of the
# tags that failed to be added, with errors on each Tag.
def self.add_or_create_synonyms_by_name(target_tag, synonym_names)
- tag_names = DiscourseTagging.tags_for_saving(synonym_names, Guardian.new(Discourse.system_user)) || []
+ tag_names =
+ DiscourseTagging.tags_for_saving(synonym_names, Guardian.new(Discourse.system_user)) || []
tag_names -= [target_tag.name]
existing = Tag.where_name(tag_names).all
target_tag.synonyms << existing
@@ -642,6 +660,6 @@ module DiscourseTagging
def self.muted_tags(user)
return [] unless user
- TagUser.lookup(user, :muted).joins(:tag).pluck('tags.name')
+ TagUser.lookup(user, :muted).joins(:tag).pluck("tags.name")
end
end
diff --git a/lib/discourse_updates.rb b/lib/discourse_updates.rb
index 5fea6c0724f..d20870b9668 100644
--- a/lib/discourse_updates.rb
+++ b/lib/discourse_updates.rb
@@ -1,13 +1,11 @@
# frozen_string_literal: true
module DiscourseUpdates
-
class << self
-
def check_version
attrs = {
installed_version: Discourse::VERSION::STRING,
- installed_sha: (Discourse.git_version == 'unknown' ? nil : Discourse.git_version),
+ installed_sha: (Discourse.git_version == "unknown" ? nil : Discourse.git_version),
installed_describe: Discourse.full_version,
git_branch: Discourse.git_branch,
updated_at: updated_at,
@@ -17,7 +15,7 @@ module DiscourseUpdates
attrs.merge!(
latest_version: latest_version,
critical_updates: critical_updates_available?,
- missing_versions_count: missing_versions_count
+ missing_versions_count: missing_versions_count,
)
end
@@ -25,19 +23,24 @@ module DiscourseUpdates
# replace -commit_count with +commit_count
if version_info.installed_describe =~ /-(\d+)-/
- version_info.installed_describe = version_info.installed_describe.gsub(/-(\d+)-.*/, " +#{$1}")
+ version_info.installed_describe =
+ version_info.installed_describe.gsub(/-(\d+)-.*/, " +#{$1}")
end
if SiteSetting.version_checks?
is_stale_data =
- (version_info.missing_versions_count == 0 && version_info.latest_version != version_info.installed_version) ||
- (version_info.missing_versions_count != 0 && version_info.latest_version == version_info.installed_version)
+ (
+ version_info.missing_versions_count == 0 &&
+ version_info.latest_version != version_info.installed_version
+ ) ||
+ (
+ version_info.missing_versions_count != 0 &&
+ version_info.latest_version == version_info.installed_version
+ )
# Handle cases when version check data is old so we report something that makes sense
- if version_info.updated_at.nil? || # never performed a version check
- last_installed_version != Discourse::VERSION::STRING || # upgraded since the last version check
- is_stale_data
-
+ if version_info.updated_at.nil? || last_installed_version != Discourse::VERSION::STRING || # never performed a version check # upgraded since the last version check
+ is_stale_data
Jobs.enqueue(:version_check, all_sites: true)
version_info.version_check_pending = true
@@ -48,9 +51,8 @@ module DiscourseUpdates
end
version_info.stale_data =
- version_info.version_check_pending ||
- (updated_at && updated_at < 48.hours.ago) ||
- is_stale_data
+ version_info.version_check_pending || (updated_at && updated_at < 48.hours.ago) ||
+ is_stale_data
end
version_info
@@ -82,7 +84,7 @@ module DiscourseUpdates
end
def critical_updates_available?
- (Discourse.redis.get(critical_updates_available_key) || false) == 'true'
+ (Discourse.redis.get(critical_updates_available_key) || false) == "true"
end
def critical_updates_available=(arg)
@@ -110,7 +112,7 @@ module DiscourseUpdates
# store the list in redis
version_keys = []
versions[0, 5].each do |v|
- key = "#{missing_versions_key_prefix}:#{v['version']}"
+ key = "#{missing_versions_key_prefix}:#{v["version"]}"
Discourse.redis.mapped_hmset key, v
version_keys << key
end
@@ -140,11 +142,21 @@ module DiscourseUpdates
end
def new_features
- entries = JSON.parse(Discourse.redis.get(new_features_key)) rescue nil
+ entries =
+ begin
+ JSON.parse(Discourse.redis.get(new_features_key))
+ rescue StandardError
+ nil
+ end
return nil if entries.nil?
entries.select! do |item|
- item["discourse_version"].nil? || Discourse.has_needed_version?(current_version, item["discourse_version"]) rescue nil
+ begin
+ item["discourse_version"].nil? ||
+ Discourse.has_needed_version?(current_version, item["discourse_version"])
+ rescue StandardError
+ nil
+ end
end
entries.sort_by { |item| Time.zone.parse(item["created_at"]).to_i }.reverse
@@ -170,7 +182,12 @@ module DiscourseUpdates
end
def mark_new_features_as_seen(user_id)
- entries = JSON.parse(Discourse.redis.get(new_features_key)) rescue nil
+ entries =
+ begin
+ JSON.parse(Discourse.redis.get(new_features_key))
+ rescue StandardError
+ nil
+ end
return nil if entries.nil?
last_seen = entries.max_by { |x| x["created_at"] }
Discourse.redis.set(new_features_last_seen_key(user_id), last_seen["created_at"])
@@ -204,39 +221,39 @@ module DiscourseUpdates
private
def last_installed_version_key
- 'last_installed_version'
+ "last_installed_version"
end
def latest_version_key
- 'discourse_latest_version'
+ "discourse_latest_version"
end
def critical_updates_available_key
- 'critical_updates_available'
+ "critical_updates_available"
end
def missing_versions_count_key
- 'missing_versions_count'
+ "missing_versions_count"
end
def updated_at_key
- 'last_version_check_at'
+ "last_version_check_at"
end
def missing_versions_list_key
- 'missing_versions'
+ "missing_versions"
end
def missing_versions_key_prefix
- 'missing_version'
+ "missing_version"
end
def new_features_endpoint
- 'https://meta.discourse.org/new-features.json'
+ "https://meta.discourse.org/new-features.json"
end
def new_features_key
- 'new_features'
+ "new_features"
end
def new_features_last_seen_key(user_id)
diff --git a/lib/disk_space.rb b/lib/disk_space.rb
index 9903164e3c1..c7ee672cc0b 100644
--- a/lib/disk_space.rb
+++ b/lib/disk_space.rb
@@ -18,13 +18,13 @@ class DiskSpace
end
def self.free(path)
- output = Discourse::Utils.execute_command('df', '-Pk', path)
+ output = Discourse::Utils.execute_command("df", "-Pk", path)
size_line = output.split("\n")[1]
size_line.split(/\s+/)[3].to_i * 1024
end
def self.percent_free(path)
- output = Discourse::Utils.execute_command('df', '-P', path)
+ output = Discourse::Utils.execute_command("df", "-P", path)
size_line = output.split("\n")[1]
size_line.split(/\s+/)[4].to_i
end
diff --git a/lib/distributed_cache.rb b/lib/distributed_cache.rb
index 89e6058d11c..80fa7bf1f82 100644
--- a/lib/distributed_cache.rb
+++ b/lib/distributed_cache.rb
@@ -1,23 +1,16 @@
# frozen_string_literal: true
-require 'message_bus/distributed_cache'
+require "message_bus/distributed_cache"
class DistributedCache < MessageBus::DistributedCache
def initialize(key, manager: nil, namespace: true)
- super(
- key,
- manager: manager,
- namespace: namespace,
- app_version: Discourse.git_version
- )
+ super(key, manager: manager, namespace: namespace, app_version: Discourse.git_version)
end
# Defer setting of the key in the cache for performance critical path to avoid
# waiting on MessageBus to publish the message which involves writing to Redis.
def defer_set(k, v)
- Scheduler::Defer.later("#{@key}_set") do
- self[k] = v
- end
+ Scheduler::Defer.later("#{@key}_set") { self[k] = v }
end
def defer_get_set(k, &block)
diff --git a/lib/distributed_mutex.rb b/lib/distributed_mutex.rb
index b456244a6d7..f7eb3b4e512 100644
--- a/lib/distributed_mutex.rb
+++ b/lib/distributed_mutex.rb
@@ -31,11 +31,7 @@ class DistributedMutex
LUA
def self.synchronize(key, redis: nil, validity: DEFAULT_VALIDITY, &blk)
- self.new(
- key,
- redis: redis,
- validity: validity
- ).synchronize(&blk)
+ self.new(key, redis: redis, validity: validity).synchronize(&blk)
end
def initialize(key, redis: nil, validity: DEFAULT_VALIDITY)
@@ -58,7 +54,9 @@ class DistributedMutex
ensure
current_time = redis.time[0]
if current_time > expire_time
- warn("held for too long, expected max: #{@validity} secs, took an extra #{current_time - expire_time} secs")
+ warn(
+ "held for too long, expected max: #{@validity} secs, took an extra #{current_time - expire_time} secs",
+ )
end
unlocked = UNLOCK_SCRIPT.eval(redis, [prefixed_key], [expire_time.to_s])
diff --git a/lib/edit_rate_limiter.rb b/lib/edit_rate_limiter.rb
index d9769f52621..b39bcb5a8cd 100644
--- a/lib/edit_rate_limiter.rb
+++ b/lib/edit_rate_limiter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'rate_limiter'
+require "rate_limiter"
class EditRateLimiter < RateLimiter
def initialize(user)
limit = SiteSetting.max_edits_per_day
diff --git a/lib/email.rb b/lib/email.rb
index 8993c2a4163..ec2061c29a6 100644
--- a/lib/email.rb
+++ b/lib/email.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'mail'
+require "mail"
module Email
# See https://www.iana.org/assignments/smtp-enhanced-status-codes/smtp-enhanced-status-codes.xhtml#smtp-enhanced-status-codes-1
@@ -21,19 +21,19 @@ module Email
def self.obfuscate(email)
return email if !Email.is_valid?(email)
- first, _, last = email.rpartition('@')
+ first, _, last = email.rpartition("@")
# Obfuscate each last part, except tld
- last = last.split('.')
+ last = last.split(".")
tld = last.pop
last.map! { |part| obfuscate_part(part) }
last << tld
- "#{obfuscate_part(first)}@#{last.join('.')}"
+ "#{obfuscate_part(first)}@#{last.join(".")}"
end
def self.cleanup_alias(name)
- name ? name.gsub(/[:<>,"]/, '') : name
+ name ? name.gsub(/[:<>,"]/, "") : name
end
def self.extract_parts(raw)
diff --git a/lib/email/authentication_results.rb b/lib/email/authentication_results.rb
index aa8f5ad2ef9..05bea8df78d 100644
--- a/lib/email/authentication_results.rb
+++ b/lib/email/authentication_results.rb
@@ -2,12 +2,7 @@
module Email
class AuthenticationResults
- VERDICT = Enum.new(
- :gray,
- :pass,
- :fail,
- start: 0,
- )
+ VERDICT = Enum.new(:gray, :pass, :fail, start: 0)
def initialize(headers)
@authserv_id = SiteSetting.email_in_authserv_id
@@ -16,11 +11,10 @@ module Email
end
def results
- @results ||= Array(@headers).map do |header|
- parse_header(header.to_s)
- end.filter do |result|
- @authserv_id.blank? || @authserv_id == result[:authserv_id]
- end
+ @results ||=
+ Array(@headers)
+ .map { |header| parse_header(header.to_s) }
+ .filter { |result| @authserv_id.blank? || @authserv_id == result[:authserv_id] }
end
def action
@@ -55,7 +49,8 @@ module Email
end
end
end
- verdict = VERDICT[:gray] if SiteSetting.email_in_authserv_id.blank? && verdict == VERDICT[:pass]
+ verdict = VERDICT[:gray] if SiteSetting.email_in_authserv_id.blank? &&
+ verdict == VERDICT[:pass]
verdict
end
@@ -67,10 +62,11 @@ module Email
authres_version = /\d+#{cfws}?/
no_result = /#{cfws}?;#{cfws}?none/
keyword = /([a-zA-Z0-9-]*[a-zA-Z0-9])/
- authres_payload = /\A#{cfws}?#{authserv_id}(?:#{cfws}#{authres_version})?(?:#{no_result}|([\S\s]*))/
+ authres_payload =
+ /\A#{cfws}?#{authserv_id}(?:#{cfws}#{authres_version})?(?:#{no_result}|([\S\s]*))/
method_version = authres_version
- method = /#{keyword}\s*(?:#{cfws}?\/#{cfws}?#{method_version})?/
+ method = %r{#{keyword}\s*(?:#{cfws}?/#{cfws}?#{method_version})?}
result = keyword
methodspec = /#{cfws}?#{method}#{cfws}?=#{cfws}?#{result}/
reasonspec = /reason#{cfws}?=#{cfws}?#{value}/
@@ -87,27 +83,21 @@ module Email
if resinfo_val
resinfo_scan = resinfo_val.scan(resinfo)
- parsed_resinfo = resinfo_scan.map do |x|
- {
- method: x[2],
- result: x[8],
- reason: x[12] || x[13],
- props: x[-1].scan(propspec).map do |y|
- {
- ptype: y[0],
- property: y[4],
- pvalue: y[8] || y[9]
- }
- end
- }
- end
+ parsed_resinfo =
+ resinfo_scan.map do |x|
+ {
+ method: x[2],
+ result: x[8],
+ reason: x[12] || x[13],
+ props:
+ x[-1]
+ .scan(propspec)
+ .map { |y| { ptype: y[0], property: y[4], pvalue: y[8] || y[9] } },
+ }
+ end
end
- {
- authserv_id: parsed_authserv_id,
- resinfo: parsed_resinfo
- }
+ { authserv_id: parsed_authserv_id, resinfo: parsed_resinfo }
end
-
end
end
diff --git a/lib/email/build_email_helper.rb b/lib/email/build_email_helper.rb
index 80677942a08..51ddd1f97a0 100644
--- a/lib/email/build_email_helper.rb
+++ b/lib/email/build_email_helper.rb
@@ -5,11 +5,11 @@ module Email
def build_email(*builder_args)
builder = Email::MessageBuilder.new(*builder_args)
headers(builder.header_args) if builder.header_args.present?
- mail(builder.build_args).tap { |message|
+ mail(builder.build_args).tap do |message|
if message && h = builder.html_part
message.html_part = h
end
- }
+ end
end
end
end
diff --git a/lib/email/cleaner.rb b/lib/email/cleaner.rb
index 52170a96598..16668dd3fb7 100644
--- a/lib/email/cleaner.rb
+++ b/lib/email/cleaner.rb
@@ -4,7 +4,7 @@ module Email
class Cleaner
def initialize(mail, remove_attachments: true, truncate: true, rejected: false)
@mail = Mail.new(mail)
- @mail.charset = 'UTF-8'
+ @mail.charset = "UTF-8"
@remove_attachments = remove_attachments
@truncate = truncate
@rejected = rejected
@@ -17,13 +17,16 @@ module Email
end
def self.delete_rejected!
- IncomingEmail.delete_by('rejection_message IS NOT NULL AND created_at < ?', SiteSetting.delete_rejected_email_after_days.days.ago)
+ IncomingEmail.delete_by(
+ "rejection_message IS NOT NULL AND created_at < ?",
+ SiteSetting.delete_rejected_email_after_days.days.ago,
+ )
end
private
def truncate!
- parts.each { |part| part.body = part.body.decoded.truncate(truncate_limit, omission: '') }
+ parts.each { |part| part.body = part.body.decoded.truncate(truncate_limit, omission: "") }
end
def parts
diff --git a/lib/email/message_builder.rb b/lib/email/message_builder.rb
index 42aefe600a3..396085955a4 100644
--- a/lib/email/message_builder.rb
+++ b/lib/email/message_builder.rb
@@ -6,7 +6,7 @@ module Email
class MessageBuilder
attr_reader :template_args
- ALLOW_REPLY_BY_EMAIL_HEADER = 'X-Discourse-Allow-Reply-By-Email'
+ ALLOW_REPLY_BY_EMAIL_HEADER = "X-Discourse-Allow-Reply-By-Email"
def initialize(to, opts = nil)
@to = to
@@ -21,30 +21,44 @@ module Email
}.merge!(@opts)
if @template_args[:url].present?
- @template_args[:header_instructions] ||= I18n.t('user_notifications.header_instructions', @template_args)
+ @template_args[:header_instructions] ||= I18n.t(
+ "user_notifications.header_instructions",
+ @template_args,
+ )
if @opts[:include_respond_instructions] == false
- @template_args[:respond_instructions] = ''
- @template_args[:respond_instructions] = I18n.t('user_notifications.pm_participants', @template_args) if @opts[:private_reply]
+ @template_args[:respond_instructions] = ""
+ @template_args[:respond_instructions] = I18n.t(
+ "user_notifications.pm_participants",
+ @template_args,
+ ) if @opts[:private_reply]
else
if @opts[:only_reply_by_email]
string = +"user_notifications.only_reply_by_email"
string << "_pm" if @opts[:private_reply]
else
- string = allow_reply_by_email? ? +"user_notifications.reply_by_email" : +"user_notifications.visit_link_to_respond"
+ string =
+ (
+ if allow_reply_by_email?
+ +"user_notifications.reply_by_email"
+ else
+ +"user_notifications.visit_link_to_respond"
+ end
+ )
string << "_pm" if @opts[:private_reply]
end
@template_args[:respond_instructions] = "---\n" + I18n.t(string, @template_args)
end
if @opts[:add_unsubscribe_link]
- unsubscribe_string = if @opts[:mailing_list_mode]
- "unsubscribe_mailing_list"
- elsif SiteSetting.unsubscribe_via_email_footer
- "unsubscribe_link_and_mail"
- else
- "unsubscribe_link"
- end
+ unsubscribe_string =
+ if @opts[:mailing_list_mode]
+ "unsubscribe_mailing_list"
+ elsif SiteSetting.unsubscribe_via_email_footer
+ "unsubscribe_link_and_mail"
+ else
+ "unsubscribe_link"
+ end
@template_args[:unsubscribe_instructions] = I18n.t(unsubscribe_string, @template_args)
end
end
@@ -52,26 +66,60 @@ module Email
def subject
if @opts[:template] &&
- TranslationOverride.exists?(locale: I18n.locale, translation_key: "#{@opts[:template]}.subject_template")
- augmented_template_args = @template_args.merge({
- site_name: @template_args[:email_prefix],
- optional_re: @opts[:add_re_to_subject] ? I18n.t('subject_re') : '',
- optional_pm: @opts[:private_reply] ? @template_args[:subject_pm] : '',
- optional_cat: @template_args[:show_category_in_subject] ? "[#{@template_args[:show_category_in_subject]}] " : '',
- optional_tags: @template_args[:show_tags_in_subject] ? "#{@template_args[:show_tags_in_subject]} " : '',
- topic_title: @template_args[:topic_title] ? @template_args[:topic_title] : '',
- })
+ TranslationOverride.exists?(
+ locale: I18n.locale,
+ translation_key: "#{@opts[:template]}.subject_template",
+ )
+ augmented_template_args =
+ @template_args.merge(
+ {
+ site_name: @template_args[:email_prefix],
+ optional_re: @opts[:add_re_to_subject] ? I18n.t("subject_re") : "",
+ optional_pm: @opts[:private_reply] ? @template_args[:subject_pm] : "",
+ optional_cat:
+ (
+ if @template_args[:show_category_in_subject]
+ "[#{@template_args[:show_category_in_subject]}] "
+ else
+ ""
+ end
+ ),
+ optional_tags:
+ (
+ if @template_args[:show_tags_in_subject]
+ "#{@template_args[:show_tags_in_subject]} "
+ else
+ ""
+ end
+ ),
+ topic_title: @template_args[:topic_title] ? @template_args[:topic_title] : "",
+ },
+ )
subject = I18n.t("#{@opts[:template]}.subject_template", augmented_template_args)
elsif @opts[:use_site_subject]
subject = String.new(SiteSetting.email_subject)
subject.gsub!("%{site_name}", @template_args[:email_prefix])
- subject.gsub!("%{optional_re}", @opts[:add_re_to_subject] ? I18n.t('subject_re') : '')
- subject.gsub!("%{optional_pm}", @opts[:private_reply] ? @template_args[:subject_pm] : '')
- subject.gsub!("%{optional_cat}", @template_args[:show_category_in_subject] ? "[#{@template_args[:show_category_in_subject]}] " : '')
- subject.gsub!("%{optional_tags}", @template_args[:show_tags_in_subject] ? "#{@template_args[:show_tags_in_subject]} " : '')
- subject.gsub!("%{topic_title}", @template_args[:topic_title]) if @template_args[:topic_title] # must be last for safety
+ subject.gsub!("%{optional_re}", @opts[:add_re_to_subject] ? I18n.t("subject_re") : "")
+ subject.gsub!("%{optional_pm}", @opts[:private_reply] ? @template_args[:subject_pm] : "")
+ subject.gsub!(
+ "%{optional_cat}",
+ (
+ if @template_args[:show_category_in_subject]
+ "[#{@template_args[:show_category_in_subject]}] "
+ else
+ ""
+ end
+ ),
+ )
+ subject.gsub!(
+ "%{optional_tags}",
+ @template_args[:show_tags_in_subject] ? "#{@template_args[:show_tags_in_subject]} " : "",
+ )
+ if @template_args[:topic_title]
+ subject.gsub!("%{topic_title}", @template_args[:topic_title])
+ end # must be last for safety
elsif @opts[:use_topic_title_subject]
- subject = @opts[:add_re_to_subject] ? I18n.t('subject_re') : ''
+ subject = @opts[:add_re_to_subject] ? I18n.t("subject_re") : ""
subject = "#{subject}#{@template_args[:topic_title]}"
elsif @opts[:template]
subject = I18n.t("#{@opts[:template]}.subject_template", @template_args)
@@ -85,34 +133,40 @@ module Email
return unless html_override = @opts[:html_override]
if @template_args[:unsubscribe_instructions].present?
- unsubscribe_instructions = PrettyText.cook(@template_args[:unsubscribe_instructions], sanitize: false).html_safe
+ unsubscribe_instructions =
+ PrettyText.cook(@template_args[:unsubscribe_instructions], sanitize: false).html_safe
html_override.gsub!("%{unsubscribe_instructions}", unsubscribe_instructions)
else
html_override.gsub!("%{unsubscribe_instructions}", "")
end
if @template_args[:header_instructions].present?
- header_instructions = PrettyText.cook(@template_args[:header_instructions], sanitize: false).html_safe
+ header_instructions =
+ PrettyText.cook(@template_args[:header_instructions], sanitize: false).html_safe
html_override.gsub!("%{header_instructions}", header_instructions)
else
html_override.gsub!("%{header_instructions}", "")
end
if @template_args[:respond_instructions].present?
- respond_instructions = PrettyText.cook(@template_args[:respond_instructions], sanitize: false).html_safe
+ respond_instructions =
+ PrettyText.cook(@template_args[:respond_instructions], sanitize: false).html_safe
html_override.gsub!("%{respond_instructions}", respond_instructions)
else
html_override.gsub!("%{respond_instructions}", "")
end
- html = UserNotificationRenderer.render(
- template: 'layouts/email_template',
- format: :html,
- locals: { html_body: html_override.html_safe }
- )
+ html =
+ UserNotificationRenderer.render(
+ template: "layouts/email_template",
+ format: :html,
+ locals: {
+ html_body: html_override.html_safe,
+ },
+ )
Mail::Part.new do
- content_type 'text/html; charset=UTF-8'
+ content_type "text/html; charset=UTF-8"
body html
end
end
@@ -139,14 +193,18 @@ module Email
to: @to,
subject: subject,
body: body,
- charset: 'UTF-8',
+ charset: "UTF-8",
from: from_value,
cc: @opts[:cc],
- bcc: @opts[:bcc]
+ bcc: @opts[:bcc],
}
- args[:delivery_method_options] = @opts[:delivery_method_options] if @opts[:delivery_method_options]
- args[:delivery_method_options] = (args[:delivery_method_options] || {}).merge(return_response: true)
+ args[:delivery_method_options] = @opts[:delivery_method_options] if @opts[
+ :delivery_method_options
+ ]
+ args[:delivery_method_options] = (args[:delivery_method_options] || {}).merge(
+ return_response: true,
+ )
args
end
@@ -154,38 +212,42 @@ module Email
def header_args
result = {}
if @opts[:add_unsubscribe_link]
- unsubscribe_url = @template_args[:unsubscribe_url].presence || @template_args[:user_preferences_url]
- result['List-Unsubscribe'] = "<#{unsubscribe_url}>"
+ unsubscribe_url =
+ @template_args[:unsubscribe_url].presence || @template_args[:user_preferences_url]
+ result["List-Unsubscribe"] = "<#{unsubscribe_url}>"
end
- result['X-Discourse-Post-Id'] = @opts[:post_id].to_s if @opts[:post_id]
- result['X-Discourse-Topic-Id'] = @opts[:topic_id].to_s if @opts[:topic_id]
+ result["X-Discourse-Post-Id"] = @opts[:post_id].to_s if @opts[:post_id]
+ result["X-Discourse-Topic-Id"] = @opts[:topic_id].to_s if @opts[:topic_id]
# at this point these have been filtered by the recipient's guardian for visibility,
# see UserNotifications#send_notification_email
- result['X-Discourse-Tags'] = @template_args[:show_tags_in_subject] if @opts[:show_tags_in_subject]
- result['X-Discourse-Category'] = @template_args[:show_category_in_subject] if @opts[:show_category_in_subject]
+ result["X-Discourse-Tags"] = @template_args[:show_tags_in_subject] if @opts[
+ :show_tags_in_subject
+ ]
+ result["X-Discourse-Category"] = @template_args[:show_category_in_subject] if @opts[
+ :show_category_in_subject
+ ]
# please, don't send us automatic responses...
- result['X-Auto-Response-Suppress'] = 'All'
+ result["X-Auto-Response-Suppress"] = "All"
if !allow_reply_by_email?
# This will end up being the notification_email, which is a
# noreply address.
- result['Reply-To'] = from_value
+ result["Reply-To"] = from_value
else
-
# The only reason we use from address for reply to is for group
# SMTP emails, where the person will be replying to the group's
# email_username.
if !@opts[:use_from_address_for_reply_to]
result[ALLOW_REPLY_BY_EMAIL_HEADER] = true
- result['Reply-To'] = reply_by_email_address
+ result["Reply-To"] = reply_by_email_address
else
# No point in adding a reply-to header if it is going to be identical
# to the from address/alias. If the from option is not present, then
# the default reply-to address is used.
- result['Reply-To'] = from_value if from_value != alias_email(@opts[:from])
+ result["Reply-To"] = from_value if from_value != alias_email(@opts[:from])
end
end
@@ -194,23 +256,24 @@ module Email
def self.custom_headers(string)
result = {}
- string.split('|').each { |item|
- header = item.split(':', 2)
- if header.length == 2
- name = header[0].strip
- value = header[1].strip
- result[name] = value if name.length > 0 && value.length > 0
- end
- } unless string.nil?
+ string
+ .split("|")
+ .each do |item|
+ header = item.split(":", 2)
+ if header.length == 2
+ name = header[0].strip
+ value = header[1].strip
+ result[name] = value if name.length > 0 && value.length > 0
+ end
+ end unless string.nil?
result
end
protected
def allow_reply_by_email?
- SiteSetting.reply_by_email_enabled? &&
- reply_by_email_address.present? &&
- @opts[:allow_reply_by_email]
+ SiteSetting.reply_by_email_enabled? && reply_by_email_address.present? &&
+ @opts[:allow_reply_by_email]
end
def private_reply?
@@ -238,9 +301,10 @@ module Email
end
def alias_email(source)
- return source if @opts[:from_alias].blank? &&
- SiteSetting.email_site_title.blank? &&
- SiteSetting.title.blank?
+ if @opts[:from_alias].blank? && SiteSetting.email_site_title.blank? &&
+ SiteSetting.title.blank?
+ return source
+ end
if @opts[:from_alias].present?
%Q|"#{Email.cleanup_alias(@opts[:from_alias])}" <#{source}>|
@@ -255,7 +319,5 @@ module Email
from_alias = Email.site_title
%Q|"#{Email.cleanup_alias(from_alias)}" <#{source}>|
end
-
end
-
end
diff --git a/lib/email/message_id_service.rb b/lib/email/message_id_service.rb
index fe2af543433..4ba6b0d7375 100644
--- a/lib/email/message_id_service.rb
+++ b/lib/email/message_id_service.rb
@@ -49,9 +49,8 @@ module Email
# inbound email sent to Discourse and handled by Email::Receiver,
# this is the only case where we want to use the original Message-ID
# because we want to maintain threading in the original mail client.
- if use_incoming_email_if_present &&
- incoming_email&.message_id.present? &&
- incoming_email&.created_via == IncomingEmail.created_via_types[:handle_mail]
+ if use_incoming_email_if_present && incoming_email&.message_id.present? &&
+ incoming_email&.created_via == IncomingEmail.created_via_types[:handle_mail]
return "<#{first_post.incoming_email.message_id}>"
end
@@ -100,12 +99,26 @@ module Email
# TODO (martin) 2023-01-01 We should remove these backwards-compatible
# formats for the Message-ID and solely use the discourse/post/999@host
# format.
- topic_ids = message_ids.map { |message_id| message_id[message_id_topic_id_regexp, 1] }.compact.map(&:to_i)
- post_ids = message_ids.map { |message_id| message_id[message_id_post_id_regexp, 1] }.compact.map(&:to_i)
-
- post_ids << message_ids.map { |message_id| message_id[message_id_discourse_regexp, 1] }.compact.map(&:to_i)
-
- post_ids << Post.where(outbound_message_id: message_ids).or(Post.where(topic_id: topic_ids, post_number: 1)).pluck(:id)
+ topic_ids =
+ message_ids
+ .map { |message_id| message_id[message_id_topic_id_regexp, 1] }
+ .compact
+ .map(&:to_i)
+ post_ids =
+ message_ids
+ .map { |message_id| message_id[message_id_post_id_regexp, 1] }
+ .compact
+ .map(&:to_i)
+
+ post_ids << message_ids
+ .map { |message_id| message_id[message_id_discourse_regexp, 1] }
+ .compact
+ .map(&:to_i)
+
+ post_ids << Post
+ .where(outbound_message_id: message_ids)
+ .or(Post.where(topic_id: topic_ids, post_number: 1))
+ .pluck(:id)
post_ids << EmailLog.where(message_id: message_ids).pluck(:post_id)
post_ids << IncomingEmail.where(message_id: message_ids).pluck(:post_id)
@@ -151,11 +164,15 @@ module Email
end
def message_id_clean(message_id)
- message_id.present? && is_message_id_rfc?(message_id) ? message_id.gsub(/^<|>$/, "") : message_id
+ if message_id.present? && is_message_id_rfc?(message_id)
+ message_id.gsub(/^<|>$/, "")
+ else
+ message_id
+ end
end
def is_message_id_rfc?(message_id)
- message_id.start_with?('<') && message_id.include?('@') && message_id.end_with?('>')
+ message_id.start_with?("<") && message_id.include?("@") && message_id.end_with?(">")
end
def host
diff --git a/lib/email/processor.rb b/lib/email/processor.rb
index 4d9f5085d40..9c807fc2b8e 100644
--- a/lib/email/processor.rb
+++ b/lib/email/processor.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module Email
-
class Processor
attr_reader :receiver
@@ -19,7 +18,11 @@ module Email
@receiver = Email::Receiver.new(@mail, @opts)
@receiver.process!
rescue RateLimiter::LimitExceeded
- @opts[:retry_on_rate_limit] ? Jobs.enqueue(:process_email, mail: @mail, source: @opts[:source]) : raise
+ if @opts[:retry_on_rate_limit]
+ Jobs.enqueue(:process_email, mail: @mail, source: @opts[:source])
+ else
+ raise
+ end
rescue => e
return handle_bounce(e) if @receiver.is_bounce?
@@ -37,39 +40,70 @@ module Email
def handle_bounce(e)
# never reply to bounced emails
log_email_process_failure(@mail, e)
- set_incoming_email_rejection_message(@receiver.incoming_email, I18n.t("emails.incoming.errors.bounced_email_error"))
+ set_incoming_email_rejection_message(
+ @receiver.incoming_email,
+ I18n.t("emails.incoming.errors.bounced_email_error"),
+ )
end
def handle_failure(mail_string, e)
- message_template = case e
- when Email::Receiver::NoSenderDetectedError then return nil
- when Email::Receiver::FromReplyByAddressError then return nil
- when Email::Receiver::EmptyEmailError then :email_reject_empty
- when Email::Receiver::NoBodyDetectedError then :email_reject_empty
- when Email::Receiver::UserNotFoundError then :email_reject_user_not_found
- when Email::Receiver::ScreenedEmailError then :email_reject_screened_email
- when Email::Receiver::EmailNotAllowed then :email_reject_not_allowed_email
- when Email::Receiver::AutoGeneratedEmailError then :email_reject_auto_generated
- when Email::Receiver::InactiveUserError then :email_reject_inactive_user
- when Email::Receiver::SilencedUserError then :email_reject_silenced_user
- when Email::Receiver::BadDestinationAddress then :email_reject_bad_destination_address
- when Email::Receiver::StrangersNotAllowedError then :email_reject_strangers_not_allowed
- when Email::Receiver::InsufficientTrustLevelError then :email_reject_insufficient_trust_level
- when Email::Receiver::ReplyUserNotMatchingError then :email_reject_reply_user_not_matching
- when Email::Receiver::TopicNotFoundError then :email_reject_topic_not_found
- when Email::Receiver::TopicClosedError then :email_reject_topic_closed
- when Email::Receiver::InvalidPost then :email_reject_invalid_post
- when Email::Receiver::TooShortPost then :email_reject_post_too_short
- when Email::Receiver::UnsubscribeNotAllowed then :email_reject_invalid_post
- when ActiveRecord::Rollback then :email_reject_invalid_post
- when Email::Receiver::InvalidPostAction then :email_reject_invalid_post_action
- when Discourse::InvalidAccess then :email_reject_invalid_access
- when Email::Receiver::OldDestinationError then :email_reject_old_destination
- when Email::Receiver::ReplyNotAllowedError then :email_reject_reply_not_allowed
- when Email::Receiver::ReplyToDigestError then :email_reject_reply_to_digest
- when Email::Receiver::TooManyRecipientsError then :email_reject_too_many_recipients
- else :email_reject_unrecognized_error
- end
+ message_template =
+ case e
+ when Email::Receiver::NoSenderDetectedError
+ return nil
+ when Email::Receiver::FromReplyByAddressError
+ return nil
+ when Email::Receiver::EmptyEmailError
+ :email_reject_empty
+ when Email::Receiver::NoBodyDetectedError
+ :email_reject_empty
+ when Email::Receiver::UserNotFoundError
+ :email_reject_user_not_found
+ when Email::Receiver::ScreenedEmailError
+ :email_reject_screened_email
+ when Email::Receiver::EmailNotAllowed
+ :email_reject_not_allowed_email
+ when Email::Receiver::AutoGeneratedEmailError
+ :email_reject_auto_generated
+ when Email::Receiver::InactiveUserError
+ :email_reject_inactive_user
+ when Email::Receiver::SilencedUserError
+ :email_reject_silenced_user
+ when Email::Receiver::BadDestinationAddress
+ :email_reject_bad_destination_address
+ when Email::Receiver::StrangersNotAllowedError
+ :email_reject_strangers_not_allowed
+ when Email::Receiver::InsufficientTrustLevelError
+ :email_reject_insufficient_trust_level
+ when Email::Receiver::ReplyUserNotMatchingError
+ :email_reject_reply_user_not_matching
+ when Email::Receiver::TopicNotFoundError
+ :email_reject_topic_not_found
+ when Email::Receiver::TopicClosedError
+ :email_reject_topic_closed
+ when Email::Receiver::InvalidPost
+ :email_reject_invalid_post
+ when Email::Receiver::TooShortPost
+ :email_reject_post_too_short
+ when Email::Receiver::UnsubscribeNotAllowed
+ :email_reject_invalid_post
+ when ActiveRecord::Rollback
+ :email_reject_invalid_post
+ when Email::Receiver::InvalidPostAction
+ :email_reject_invalid_post_action
+ when Discourse::InvalidAccess
+ :email_reject_invalid_access
+ when Email::Receiver::OldDestinationError
+ :email_reject_old_destination
+ when Email::Receiver::ReplyNotAllowedError
+ :email_reject_reply_not_allowed
+ when Email::Receiver::ReplyToDigestError
+ :email_reject_reply_to_digest
+ when Email::Receiver::TooManyRecipientsError
+ :email_reject_too_many_recipients
+ else
+ :email_reject_unrecognized_error
+ end
template_args = {}
client_message = nil
@@ -85,7 +119,7 @@ module Email
end
if message_template == :email_reject_unrecognized_error
- msg = "Unrecognized error type (#{e.class}: #{e.message}) when processing incoming email"
+ msg = "Unrecognized error type (#{e.class}: #{e.message}) when processing incoming email"
msg += "\n\nBacktrace:\n#{e.backtrace.map { |l| " #{l}" }.join("\n")}"
msg += "\n\nMail:\n#{mail_string}"
@@ -109,7 +143,8 @@ module Email
template_args[:destination] = message.to
template_args[:site_name] = SiteSetting.title
- client_message = RejectionMailer.send_rejection(message_template, message.from, template_args)
+ client_message =
+ RejectionMailer.send_rejection(message_template, message.from, template_args)
# only send one rejection email per day to the same email address
if can_send_rejection_email?(message.from, message_template)
@@ -138,7 +173,7 @@ module Email
if incoming_email
incoming_email.update!(
rejection_message: message,
- raw: Email::Cleaner.new(incoming_email.raw, rejected: true).execute
+ raw: Email::Cleaner.new(incoming_email.raw, rejected: true).execute,
)
end
end
@@ -148,7 +183,5 @@ module Email
Rails.logger.warn("Email can not be processed: #{exception}\n\n#{mail_string}")
end
end
-
end
-
end
diff --git a/lib/email/receiver.rb b/lib/email/receiver.rb
index ab318439ba8..05b51c7eb00 100644
--- a/lib/email/receiver.rb
+++ b/lib/email/receiver.rb
@@ -7,31 +7,56 @@ module Email
# If you add a new error, you need to
# * add it to Email::Processor#handle_failure()
# * add text to server.en.yml (parent key: "emails.incoming.errors")
- class ProcessingError < StandardError; end
- class EmptyEmailError < ProcessingError; end
- class ScreenedEmailError < ProcessingError; end
- class UserNotFoundError < ProcessingError; end
- class AutoGeneratedEmailError < ProcessingError; end
- class BouncedEmailError < ProcessingError; end
- class NoBodyDetectedError < ProcessingError; end
- class NoSenderDetectedError < ProcessingError; end
- class FromReplyByAddressError < ProcessingError; end
- class InactiveUserError < ProcessingError; end
- class SilencedUserError < ProcessingError; end
- class BadDestinationAddress < ProcessingError; end
- class StrangersNotAllowedError < ProcessingError; end
- class ReplyNotAllowedError < ProcessingError; end
- class InsufficientTrustLevelError < ProcessingError; end
- class ReplyUserNotMatchingError < ProcessingError; end
- class TopicNotFoundError < ProcessingError; end
- class TopicClosedError < ProcessingError; end
- class InvalidPost < ProcessingError; end
- class TooShortPost < ProcessingError; end
- class InvalidPostAction < ProcessingError; end
- class UnsubscribeNotAllowed < ProcessingError; end
- class EmailNotAllowed < ProcessingError; end
- class OldDestinationError < ProcessingError; end
- class ReplyToDigestError < ProcessingError; end
+ class ProcessingError < StandardError
+ end
+ class EmptyEmailError < ProcessingError
+ end
+ class ScreenedEmailError < ProcessingError
+ end
+ class UserNotFoundError < ProcessingError
+ end
+ class AutoGeneratedEmailError < ProcessingError
+ end
+ class BouncedEmailError < ProcessingError
+ end
+ class NoBodyDetectedError < ProcessingError
+ end
+ class NoSenderDetectedError < ProcessingError
+ end
+ class FromReplyByAddressError < ProcessingError
+ end
+ class InactiveUserError < ProcessingError
+ end
+ class SilencedUserError < ProcessingError
+ end
+ class BadDestinationAddress < ProcessingError
+ end
+ class StrangersNotAllowedError < ProcessingError
+ end
+ class ReplyNotAllowedError < ProcessingError
+ end
+ class InsufficientTrustLevelError < ProcessingError
+ end
+ class ReplyUserNotMatchingError < ProcessingError
+ end
+ class TopicNotFoundError < ProcessingError
+ end
+ class TopicClosedError < ProcessingError
+ end
+ class InvalidPost < ProcessingError
+ end
+ class TooShortPost < ProcessingError
+ end
+ class InvalidPostAction < ProcessingError
+ end
+ class UnsubscribeNotAllowed < ProcessingError
+ end
+ class EmailNotAllowed < ProcessingError
+ end
+ class OldDestinationError < ProcessingError
+ end
+ class ReplyToDigestError < ProcessingError
+ end
class TooManyRecipientsError < ProcessingError
attr_reader :recipients_count
@@ -120,7 +145,7 @@ module Email
imap_uid_validity: @opts[:imap_uid_validity],
imap_uid: @opts[:imap_uid],
imap_group_id: @opts[:imap_group_id],
- imap_sync: false
+ imap_sync: false,
)
incoming_email
@@ -133,9 +158,7 @@ module Email
def create_incoming_email
cc_addresses = Array.wrap(@mail.cc)
- if has_been_forwarded? && embedded_email&.cc
- cc_addresses.concat(embedded_email.cc)
- end
+ cc_addresses.concat(embedded_email.cc) if has_been_forwarded? && embedded_email&.cc
IncomingEmail.create(
message_id: @message_id,
raw: Email::Cleaner.new(@raw_email).execute,
@@ -147,7 +170,7 @@ module Email
imap_uid: @opts[:imap_uid],
imap_group_id: @opts[:imap_group_id],
imap_sync: false,
- created_via: IncomingEmail.created_via_types[@opts[:source] || :unknown]
+ created_via: IncomingEmail.created_via_types[@opts[:source] || :unknown],
)
end
@@ -199,13 +222,15 @@ module Email
end
end
- create_reply(user: user,
- raw: body,
- elided: elided,
- post: post,
- topic: post.topic,
- skip_validations: user.staged?,
- bounce: is_bounce?)
+ create_reply(
+ user: user,
+ raw: body,
+ elided: elided,
+ post: post,
+ topic: post.topic,
+ skip_validations: user.staged?,
+ bounce: is_bounce?,
+ )
else
first_exception = nil
@@ -232,7 +257,9 @@ module Email
end
end
- raise ReplyToDigestError if EmailLog.where(email_type: "digest", message_id: @mail.in_reply_to).exists?
+ if EmailLog.where(email_type: "digest", message_id: @mail.in_reply_to).exists?
+ raise ReplyToDigestError
+ end
raise BadDestinationAddress
end
end
@@ -247,7 +274,7 @@ module Email
def get_all_recipients(mail)
recipients = Set.new
- %i(to cc bcc).each do |field|
+ %i[to cc bcc].each do |field|
next if mail[field].blank?
mail[field].each do |address_field|
@@ -270,10 +297,7 @@ module Email
mail_error_statuses = Array.wrap(@mail.error_status)
if email_log.present?
- email_log.update_columns(
- bounced: true,
- bounce_error_code: mail_error_statuses.first
- )
+ email_log.update_columns(bounced: true, bounce_error_code: mail_error_statuses.first)
post = email_log.post
topic = email_log.topic
end
@@ -293,13 +317,15 @@ module Email
body, elided = select_body
body ||= ""
- create_reply(user: @from_user,
- raw: body,
- elided: elided,
- post: post,
- topic: topic,
- skip_validations: true,
- bounce: true)
+ create_reply(
+ user: @from_user,
+ raw: body,
+ elided: elided,
+ post: post,
+ topic: topic,
+ skip_validations: true,
+ bounce: true,
+ )
end
end
@@ -311,10 +337,11 @@ module Email
end
def bounce_key
- @bounce_key ||= begin
- verp = all_destinations.select { |to| to[/\+verp-\h{32}@/] }.first
- verp && verp[/\+verp-(\h{32})@/, 1]
- end
+ @bounce_key ||=
+ begin
+ verp = all_destinations.select { |to| to[/\+verp-\h{32}@/] }.first
+ verp && verp[/\+verp-(\h{32})@/, 1]
+ end
end
def email_log
@@ -329,13 +356,19 @@ module Email
range = (old_bounce_score + 1..new_bounce_score)
user.user_stat.bounce_score = new_bounce_score
- user.user_stat.reset_bounce_score_after = SiteSetting.reset_bounce_score_after_days.days.from_now
+ user.user_stat.reset_bounce_score_after =
+ SiteSetting.reset_bounce_score_after_days.days.from_now
user.user_stat.save!
if range === SiteSetting.bounce_score_threshold
# NOTE: we check bounce_score before sending emails
# So log we revoked the email...
- reason = I18n.t("user.email.revoked", email: user.email, date: user.user_stat.reset_bounce_score_after)
+ reason =
+ I18n.t(
+ "user.email.revoked",
+ email: user.email,
+ date: user.user_stat.reset_bounce_score_after,
+ )
StaffActionLogger.new(Discourse.system_user).log_revoke_email(user, reason)
# ... and PM the user
SystemMessage.create_from_system_user(user, :email_revoked)
@@ -344,20 +377,24 @@ module Email
end
def is_auto_generated?
- return false if SiteSetting.auto_generated_allowlist.split('|').include?(@from_email)
+ return false if SiteSetting.auto_generated_allowlist.split("|").include?(@from_email)
@mail[:precedence].to_s[/list|junk|bulk|auto_reply/i] ||
- @mail[:from].to_s[/(mailer[\-_]?daemon|post[\-_]?master|no[\-_]?reply)@/i] ||
- @mail[:subject].to_s[/^\s*(Auto:|Automatic reply|Autosvar|Automatisk svar|Automatisch antwoord|Abwesenheitsnotiz|Risposta Non al computer|Automatisch antwoord|Auto Response|Respuesta automática|Fuori sede|Out of Office|Frånvaro|Réponse automatique)/i] ||
- @mail.header.to_s[/auto[\-_]?(response|submitted|replied|reply|generated|respond)|holidayreply|machinegenerated/i]
+ @mail[:from].to_s[/(mailer[\-_]?daemon|post[\-_]?master|no[\-_]?reply)@/i] ||
+ @mail[:subject].to_s[
+ /^\s*(Auto:|Automatic reply|Autosvar|Automatisk svar|Automatisch antwoord|Abwesenheitsnotiz|Risposta Non al computer|Automatisch antwoord|Auto Response|Respuesta automática|Fuori sede|Out of Office|Frånvaro|Réponse automatique)/i
+ ] ||
+ @mail.header.to_s[
+ /auto[\-_]?(response|submitted|replied|reply|generated|respond)|holidayreply|machinegenerated/i
+ ]
end
def is_spam?
case SiteSetting.email_in_spam_header
- when 'X-Spam-Flag'
+ when "X-Spam-Flag"
@mail[:x_spam_flag].to_s[/YES/i]
- when 'X-Spam-Status'
+ when "X-Spam-Status"
@mail[:x_spam_status].to_s[/^Yes, /i]
- when 'X-SES-Spam-Verdict'
+ when "X-SES-Spam-Verdict"
@mail[:x_ses_spam_verdict].to_s[/FAIL/i]
else
false
@@ -394,53 +431,62 @@ module Email
text_content_type ||= ""
converter_opts = {
format_flowed: !!(text_content_type =~ /format\s*=\s*["']?flowed["']?/i),
- delete_flowed_space: !!(text_content_type =~ /DelSp\s*=\s*["']?yes["']?/i)
+ delete_flowed_space: !!(text_content_type =~ /DelSp\s*=\s*["']?yes["']?/i),
}
text = PlainTextToMarkdown.new(text, converter_opts).to_markdown
elided_text = PlainTextToMarkdown.new(elided_text, converter_opts).to_markdown
end
end
- markdown, elided_markdown = if html.present?
- # use the first html extracter that matches
- if html_extracter = HTML_EXTRACTERS.select { |_, r| html[r] }.min_by { |_, r| html =~ r }
- doc = Nokogiri::HTML5.fragment(html)
- self.public_send(:"extract_from_#{html_extracter[0]}", doc)
- else
- markdown = HtmlToMarkdown.new(html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
- markdown = trim_discourse_markers(markdown)
- trim_reply_and_extract_elided(markdown)
+ markdown, elided_markdown =
+ if html.present?
+ # use the first html extracter that matches
+ if html_extracter = HTML_EXTRACTERS.select { |_, r| html[r] }.min_by { |_, r| html =~ r }
+ doc = Nokogiri::HTML5.fragment(html)
+ self.public_send(:"extract_from_#{html_extracter[0]}", doc)
+ else
+ markdown =
+ HtmlToMarkdown.new(html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
+ markdown = trim_discourse_markers(markdown)
+ trim_reply_and_extract_elided(markdown)
+ end
end
- end
- text_format = Receiver::formats[:plaintext]
+ text_format = Receiver.formats[:plaintext]
if text.blank? || (SiteSetting.incoming_email_prefer_html && markdown.present?)
- text, elided_text, text_format = markdown, elided_markdown, Receiver::formats[:markdown]
+ text, elided_text, text_format = markdown, elided_markdown, Receiver.formats[:markdown]
end
if SiteSetting.strip_incoming_email_lines && text.present?
in_code = nil
- text = text.lines.map! do |line|
- stripped = line.strip << "\n"
-
- # Do not strip list items.
- next line if (stripped[0] == '*' || stripped[0] == '-' || stripped[0] == '+') && stripped[1] == ' '
-
- # Match beginning and ending of code blocks.
- if !in_code && stripped[0..2] == '```'
- in_code = '```'
- elsif in_code == '```' && stripped[0..2] == '```'
- in_code = nil
- elsif !in_code && stripped[0..4] == '[code'
- in_code = '[code]'
- elsif in_code == '[code]' && stripped[0..6] == '[/code]'
- in_code = nil
- end
+ text =
+ text
+ .lines
+ .map! do |line|
+ stripped = line.strip << "\n"
+
+ # Do not strip list items.
+ if (stripped[0] == "*" || stripped[0] == "-" || stripped[0] == "+") &&
+ stripped[1] == " "
+ next line
+ end
- # Strip only lines outside code blocks.
- in_code ? line : stripped
- end.join
+ # Match beginning and ending of code blocks.
+ if !in_code && stripped[0..2] == "```"
+ in_code = "```"
+ elsif in_code == "```" && stripped[0..2] == "```"
+ in_code = nil
+ elsif !in_code && stripped[0..4] == "[code"
+ in_code = "[code]"
+ elsif in_code == "[code]" && stripped[0..6] == "[/code]"
+ in_code = nil
+ end
+
+ # Strip only lines outside code blocks.
+ in_code ? line : stripped
+ end
+ .join
end
[text, elided_text, text_format]
@@ -448,7 +494,8 @@ module Email
def to_markdown(html, elided_html)
markdown = HtmlToMarkdown.new(html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
- elided_markdown = HtmlToMarkdown.new(elided_html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
+ elided_markdown =
+ HtmlToMarkdown.new(elided_html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
[EmailReplyTrimmer.trim(markdown), elided_markdown]
end
@@ -481,7 +528,10 @@ module Email
def extract_from_word(doc)
# Word (?) keeps the content in the 'WordSection1' class and uses <p> tags
# When there's something else (<table>, <div>, etc..) there's high chance it's a signature or forwarded email
- elided = doc.css(".WordSection1 > :not(p):not(ul):first-of-type, .WordSection1 > :not(p):not(ul):first-of-type ~ *").remove
+ elided =
+ doc.css(
+ ".WordSection1 > :not(p):not(ul):first-of-type, .WordSection1 > :not(p):not(ul):first-of-type ~ *",
+ ).remove
to_markdown(doc.at(".WordSection1").to_html, elided.to_html)
end
@@ -502,9 +552,12 @@ module Email
def extract_from_mozilla(doc)
# Mozilla (Thunderbird ?) properly identifies signature and forwarded emails
# Remove them and anything that comes after
- elided = doc.css("*[class^='moz-cite'], *[class^='moz-cite'] ~ *, " \
- "*[class^='moz-signature'], *[class^='moz-signature'] ~ *, " \
- "*[class^='moz-forward'], *[class^='moz-forward'] ~ *").remove
+ elided =
+ doc.css(
+ "*[class^='moz-cite'], *[class^='moz-cite'] ~ *, " \
+ "*[class^='moz-signature'], *[class^='moz-signature'] ~ *, " \
+ "*[class^='moz-forward'], *[class^='moz-forward'] ~ *",
+ ).remove
to_markdown(doc.to_html, elided.to_html)
end
@@ -533,14 +586,19 @@ module Email
end
def trim_reply_and_extract_elided(text)
- return [text, ""] if @opts[:skip_trimming] || !SiteSetting.trim_incoming_emails
+ return text, "" if @opts[:skip_trimming] || !SiteSetting.trim_incoming_emails
EmailReplyTrimmer.trim(text, true)
end
def fix_charset(mail_part)
return nil if mail_part.blank? || mail_part.body.blank?
- string = mail_part.body.decoded rescue nil
+ string =
+ begin
+ mail_part.body.decoded
+ rescue StandardError
+ nil
+ end
return nil if string.blank?
@@ -572,23 +630,32 @@ module Email
end
def previous_replies_regex
- strings = I18n.available_locales.map do |locale|
- I18n.with_locale(locale) { I18n.t("user_notifications.previous_discussion") }
- end.uniq
+ strings =
+ I18n
+ .available_locales
+ .map do |locale|
+ I18n.with_locale(locale) { I18n.t("user_notifications.previous_discussion") }
+ end
+ .uniq
- @previous_replies_regex ||= /^--[- ]\n\*(?:#{strings.map { |x| Regexp.escape(x) }.join("|")})\*\n/im
+ @previous_replies_regex ||=
+ /^--[- ]\n\*(?:#{strings.map { |x| Regexp.escape(x) }.join("|")})\*\n/im
end
def reply_above_line_regex
- strings = I18n.available_locales.map do |locale|
- I18n.with_locale(locale) { I18n.t("user_notifications.reply_above_line") }
- end.uniq
+ strings =
+ I18n
+ .available_locales
+ .map do |locale|
+ I18n.with_locale(locale) { I18n.t("user_notifications.reply_above_line") }
+ end
+ .uniq
@reply_above_line_regex ||= /\n(?:#{strings.map { |x| Regexp.escape(x) }.join("|")})\n/im
end
def trim_discourse_markers(reply)
- return '' if reply.blank?
+ return "" if reply.blank?
reply = reply.split(previous_replies_regex)[0]
reply.split(reply_above_line_regex)[0]
end
@@ -598,11 +665,9 @@ module Email
if email_log.present?
email = email_log.to_address || email_log.user&.email
- return [email, email_log.user&.username]
+ return email, email_log.user&.username
elsif mail.bounced?
- Array.wrap(mail.final_recipient).each do |from|
- return extract_from_address_and_name(from)
- end
+ Array.wrap(mail.final_recipient).each { |from| return extract_from_address_and_name(from) }
end
return unless mail[:from]
@@ -613,7 +678,7 @@ module Email
if has_been_forwarded?
if mail[:from].to_s =~ group_incoming_emails_regex && embedded_email[:from].errors.blank?
from_address, from_display_name = extract_from_fields_from_header(embedded_email, :from)
- return [from_address, from_display_name] if from_address
+ return from_address, from_display_name if from_address
end
end
@@ -621,18 +686,21 @@ module Email
# been forwarded via Google Groups, which is why we are checking the
# X-Original-From header too. In future we may want to use the Reply-To
# header in more cases.
- if mail['X-Original-From'].present?
+ if mail["X-Original-From"].present?
if mail[:reply_to] && mail[:reply_to].errors.blank?
- from_address, from_display_name = extract_from_fields_from_header(
- mail, :reply_to, comparison_headers: ['X-Original-From']
- )
- return [from_address, from_display_name] if from_address
+ from_address, from_display_name =
+ extract_from_fields_from_header(
+ mail,
+ :reply_to,
+ comparison_headers: ["X-Original-From"],
+ )
+ return from_address, from_display_name if from_address
end
end
if mail[:from].errors.blank?
from_address, from_display_name = extract_from_fields_from_header(mail, :from)
- return [from_address, from_display_name] if from_address
+ return from_address, from_display_name if from_address
end
return extract_from_address_and_name(mail.from) if mail.from.is_a? String
@@ -640,7 +708,7 @@ module Email
if mail.from.is_a? Mail::AddressContainer
mail.from.each do |from|
from_address, from_display_name = extract_from_address_and_name(from)
- return [from_address, from_display_name] if from_address
+ return from_address, from_display_name if from_address
end
end
@@ -665,7 +733,7 @@ module Email
next if comparison_failed
next if !from_address&.include?("@")
- return [from_address&.downcase, from_display_name&.strip]
+ return from_address&.downcase, from_display_name&.strip
end
[nil, nil]
@@ -674,7 +742,7 @@ module Email
def extract_from_address_and_name(value)
if value[";"]
from_display_name, from_address = value.split(";")
- return [from_address&.strip&.downcase, from_display_name&.strip]
+ return from_address&.strip&.downcase, from_display_name&.strip
end
if value[/<[^>]+>/]
@@ -708,12 +776,13 @@ module Email
username = UserNameSuggester.sanitize_username(display_name) if display_name.present?
begin
- user = User.create!(
- email: email,
- username: UserNameSuggester.suggest(username.presence || email),
- name: display_name.presence || User.suggest_name(email),
- staged: true
- )
+ user =
+ User.create!(
+ email: email,
+ username: UserNameSuggester.suggest(username.presence || email),
+ name: display_name.presence || User.suggest_name(email),
+ staged: true,
+ )
@created_staged_users << user
rescue PG::UniqueViolation, ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
raise if raise_on_failed_create
@@ -740,19 +809,19 @@ module Email
end
def destinations
- @destinations ||= all_destinations
- .map { |d| Email::Receiver.check_address(d, is_bounce?) }
- .reject(&:blank?)
+ @destinations ||=
+ all_destinations.map { |d| Email::Receiver.check_address(d, is_bounce?) }.reject(&:blank?)
end
def sent_to_mailinglist_mirror?
- @sent_to_mailinglist_mirror ||= begin
- destinations.each do |destination|
- return true if destination.is_a?(Category) && destination.mailinglist_mirror?
- end
+ @sent_to_mailinglist_mirror ||=
+ begin
+ destinations.each do |destination|
+ return true if destination.is_a?(Category) && destination.mailinglist_mirror?
+ end
- false
- end
+ false
+ end
end
def self.check_address(address, include_verp = false)
@@ -778,9 +847,10 @@ module Email
end
def process_destination(destination, user, body, elided)
- return if SiteSetting.forwarded_emails_behaviour != "hide" &&
- has_been_forwarded? &&
- process_forwarded_email(destination, user)
+ if SiteSetting.forwarded_emails_behaviour != "hide" && has_been_forwarded? &&
+ process_forwarded_email(destination, user)
+ return
+ end
return if is_bounce? && !destination.is_a?(PostReplyKey)
@@ -788,19 +858,24 @@ module Email
user ||= stage_from_user
create_group_post(destination, user, body, elided)
elsif destination.is_a?(Category)
- raise StrangersNotAllowedError if (user.nil? || user.staged?) && !destination.email_in_allow_strangers
+ if (user.nil? || user.staged?) && !destination.email_in_allow_strangers
+ raise StrangersNotAllowedError
+ end
user ||= stage_from_user
- raise InsufficientTrustLevelError if !user.has_trust_level?(SiteSetting.email_in_min_trust) && !sent_to_mailinglist_mirror?
-
- create_topic(user: user,
- raw: body,
- elided: elided,
- title: subject,
- category: destination.id,
- skip_validations: user.staged?)
+ if !user.has_trust_level?(SiteSetting.email_in_min_trust) && !sent_to_mailinglist_mirror?
+ raise InsufficientTrustLevelError
+ end
+ create_topic(
+ user: user,
+ raw: body,
+ elided: elided,
+ title: subject,
+ category: destination.id,
+ skip_validations: user.staged?,
+ )
elsif destination.is_a?(PostReplyKey)
# We don't stage new users for emails to reply addresses, exit if user is nil
raise BadDestinationAddress if user.blank?
@@ -809,16 +884,19 @@ module Email
raise ReplyNotAllowedError if !Guardian.new(user).can_create_post?(post&.topic)
if destination.user_id != user.id && !forwarded_reply_key?(destination, user)
- raise ReplyUserNotMatchingError, "post_reply_key.user_id => #{destination.user_id.inspect}, user.id => #{user.id.inspect}"
+ raise ReplyUserNotMatchingError,
+ "post_reply_key.user_id => #{destination.user_id.inspect}, user.id => #{user.id.inspect}"
end
- create_reply(user: user,
- raw: body,
- elided: elided,
- post: post,
- topic: post&.topic,
- skip_validations: user.staged?,
- bounce: is_bounce?)
+ create_reply(
+ user: user,
+ raw: body,
+ elided: elided,
+ post: post,
+ topic: post&.topic,
+ skip_validations: user.staged?,
+ bounce: is_bounce?,
+ )
end
end
@@ -839,11 +917,14 @@ module Email
# there will be a corresponding EmailLog record, so we can use that as the
# reply post if it exists
if Email::MessageIdService.discourse_generated_message_id?(mail.in_reply_to)
- post_id_from_email_log = EmailLog.where(message_id: mail.in_reply_to)
- .addressed_to_user(user)
- .order(created_at: :desc)
- .limit(1)
- .pluck(:post_id).last
+ post_id_from_email_log =
+ EmailLog
+ .where(message_id: mail.in_reply_to)
+ .addressed_to_user(user)
+ .order(created_at: :desc)
+ .limit(1)
+ .pluck(:post_id)
+ .last
post_ids << post_id_from_email_log if post_id_from_email_log
end
@@ -851,14 +932,16 @@ module Email
too_old_for_group_smtp = (destination_too_old?(target_post) && group.smtp_enabled)
if target_post.blank? || too_old_for_group_smtp
- create_topic(user: user,
- raw: new_group_topic_body(body, target_post, too_old_for_group_smtp),
- elided: elided,
- title: subject,
- archetype: Archetype.private_message,
- target_group_names: [group.name],
- is_group_message: true,
- skip_validations: true)
+ create_topic(
+ user: user,
+ raw: new_group_topic_body(body, target_post, too_old_for_group_smtp),
+ elided: elided,
+ title: subject,
+ archetype: Archetype.private_message,
+ target_group_names: [group.name],
+ is_group_message: true,
+ skip_validations: true,
+ )
else
# This must be done for the unknown user (who is staged) to
# be allowed to post a reply in the topic.
@@ -866,39 +949,47 @@ module Email
target_post.topic.topic_allowed_users.find_or_create_by!(user_id: user.id)
end
- create_reply(user: user,
- raw: body,
- elided: elided,
- post: target_post,
- topic: target_post.topic,
- skip_validations: true)
+ create_reply(
+ user: user,
+ raw: body,
+ elided: elided,
+ post: target_post,
+ topic: target_post.topic,
+ skip_validations: true,
+ )
end
end
def new_group_topic_body(body, target_post, too_old_for_group_smtp)
return body if !too_old_for_group_smtp
- body + "\n\n----\n\n" + I18n.t(
- "emails.incoming.continuing_old_discussion",
- url: target_post.topic.url,
- title: target_post.topic.title,
- count: SiteSetting.disallow_reply_by_email_after_days
- )
+ body + "\n\n----\n\n" +
+ I18n.t(
+ "emails.incoming.continuing_old_discussion",
+ url: target_post.topic.url,
+ title: target_post.topic.title,
+ count: SiteSetting.disallow_reply_by_email_after_days,
+ )
end
def forwarded_reply_key?(post_reply_key, user)
- incoming_emails = IncomingEmail
- .joins(:post)
- .where('posts.topic_id = ?', post_reply_key.post.topic_id)
- .addressed_to(post_reply_key.reply_key)
- .addressed_to_user(user)
- .pluck(:to_addresses, :cc_addresses)
+ incoming_emails =
+ IncomingEmail
+ .joins(:post)
+ .where("posts.topic_id = ?", post_reply_key.post.topic_id)
+ .addressed_to(post_reply_key.reply_key)
+ .addressed_to_user(user)
+ .pluck(:to_addresses, :cc_addresses)
incoming_emails.each do |to_addresses, cc_addresses|
- next unless contains_email_address_of_user?(to_addresses, user) ||
- contains_email_address_of_user?(cc_addresses, user)
+ unless contains_email_address_of_user?(to_addresses, user) ||
+ contains_email_address_of_user?(cc_addresses, user)
+ next
+ end
- return true if contains_reply_by_email_address(to_addresses, post_reply_key.reply_key) ||
- contains_reply_by_email_address(cc_addresses, post_reply_key.reply_key)
+ if contains_reply_by_email_address(to_addresses, post_reply_key.reply_key) ||
+ contains_reply_by_email_address(cc_addresses, post_reply_key.reply_key)
+ return true
+ end
end
false
@@ -914,10 +1005,12 @@ module Email
def contains_reply_by_email_address(addresses, reply_key)
return false if addresses.blank?
- addresses.split(";").each do |address|
- match = Email::Receiver.reply_by_email_address_regex.match(address)
- return true if match && match.captures&.include?(reply_key)
- end
+ addresses
+ .split(";")
+ .each do |address|
+ match = Email::Receiver.reply_by_email_address_regex.match(address)
+ return true if match && match.captures&.include?(reply_key)
+ end
false
end
@@ -934,13 +1027,14 @@ module Email
end
def embedded_email
- @embedded_email ||= if embedded_email_raw.present?
- mail = Mail.new(embedded_email_raw)
- Email::Validator.ensure_valid_address_lists!(mail)
- mail
- else
- nil
- end
+ @embedded_email ||=
+ if embedded_email_raw.present?
+ mail = Mail.new(embedded_email_raw)
+ Email::Validator.ensure_valid_address_lists!(mail)
+ mail
+ else
+ nil
+ end
end
def process_forwarded_email(destination, user)
@@ -955,30 +1049,40 @@ module Email
end
end
- def forwarded_email_create_topic(destination: , user: , raw: , title: , date: nil, embedded_user: nil)
+ def forwarded_email_create_topic(
+ destination:,
+ user:,
+ raw:,
+ title:,
+ date: nil,
+ embedded_user: nil
+ )
if destination.is_a?(Group)
topic_user = embedded_user&.call || user
- create_topic(user: topic_user,
- raw: raw,
- title: title,
- archetype: Archetype.private_message,
- target_usernames: [user.username],
- target_group_names: [destination.name],
- is_group_message: true,
- skip_validations: true,
- created_at: date)
-
+ create_topic(
+ user: topic_user,
+ raw: raw,
+ title: title,
+ archetype: Archetype.private_message,
+ target_usernames: [user.username],
+ target_group_names: [destination.name],
+ is_group_message: true,
+ skip_validations: true,
+ created_at: date,
+ )
elsif destination.is_a?(Category)
return false if user.staged? && !destination.email_in_allow_strangers
return false if !user.has_trust_level?(SiteSetting.email_in_min_trust)
topic_user = embedded_user&.call || user
- create_topic(user: topic_user,
- raw: raw,
- title: title,
- category: destination.id,
- skip_validations: topic_user.staged?,
- created_at: date)
+ create_topic(
+ user: topic_user,
+ raw: raw,
+ title: title,
+ category: destination.id,
+ skip_validations: topic_user.staged?,
+ created_at: date,
+ )
else
false
end
@@ -994,29 +1098,40 @@ module Email
return false if email.blank? || !email["@"]
- post = forwarded_email_create_topic(destination: destination,
- user: user,
- raw: try_to_encode(embedded.decoded, "UTF-8").presence || embedded.to_s,
- title: embedded.subject.presence || subject,
- date: embedded.date,
- embedded_user: lambda { find_or_create_user(email, display_name) })
+ post =
+ forwarded_email_create_topic(
+ destination: destination,
+ user: user,
+ raw: try_to_encode(embedded.decoded, "UTF-8").presence || embedded.to_s,
+ title: embedded.subject.presence || subject,
+ date: embedded.date,
+ embedded_user: lambda { find_or_create_user(email, display_name) },
+ )
return false unless post
if post.topic
# mark post as seen for the forwarder
- PostTiming.record_timing(user_id: user.id, topic_id: post.topic_id, post_number: post.post_number, msecs: 5000)
+ PostTiming.record_timing(
+ user_id: user.id,
+ topic_id: post.topic_id,
+ post_number: post.post_number,
+ msecs: 5000,
+ )
# create reply when available
if @before_embedded.present?
post_type = Post.types[:regular]
- post_type = Post.types[:whisper] if post.topic.private_message? && destination.usernames[user.username]
-
- create_reply(user: user,
- raw: @before_embedded,
- post: post,
- topic: post.topic,
- post_type: post_type,
- skip_validations: user.staged?)
+ post_type = Post.types[:whisper] if post.topic.private_message? &&
+ destination.usernames[user.username]
+
+ create_reply(
+ user: user,
+ raw: @before_embedded,
+ post: post,
+ topic: post.topic,
+ post_type: post_type,
+ skip_validations: user.staged?,
+ )
else
if @forwarded_by_user
post.topic.topic_allowed_users.find_or_create_by!(user_id: @forwarded_by_user.id)
@@ -1050,15 +1165,28 @@ module Email
[/quote]
MD
- return true if forwarded_email_create_topic(destination: destination, user: user, raw: raw, title: subject)
+ if forwarded_email_create_topic(
+ destination: destination,
+ user: user,
+ raw: raw,
+ title: subject,
+ )
+ true
+ end
end
def self.reply_by_email_address_regex(extract_reply_key = true, include_verp = false)
reply_addresses = [SiteSetting.reply_by_email_address]
- reply_addresses << (SiteSetting.alternative_reply_by_email_addresses.presence || "").split("|")
+ reply_addresses << (SiteSetting.alternative_reply_by_email_addresses.presence || "").split(
+ "|",
+ )
- if include_verp && SiteSetting.reply_by_email_address.present? && SiteSetting.reply_by_email_address["+"]
- reply_addresses << SiteSetting.reply_by_email_address.sub("%{reply_key}", "verp-%{reply_key}")
+ if include_verp && SiteSetting.reply_by_email_address.present? &&
+ SiteSetting.reply_by_email_address["+"]
+ reply_addresses << SiteSetting.reply_by_email_address.sub(
+ "%{reply_key}",
+ "verp-%{reply_key}",
+ )
end
reply_addresses.flatten!
@@ -1074,17 +1202,22 @@ module Email
end
def group_incoming_emails_regex
- @group_incoming_emails_regex = Regexp.union(
- DB.query_single(<<~SQL).map { |e| e.split("|") }.flatten.compact_blank.uniq
+ @group_incoming_emails_regex =
+ Regexp.union(DB.query_single(<<~SQL).map { |e| e.split("|") }.flatten.compact_blank.uniq)
SELECT CONCAT(incoming_email, '|', email_username)
FROM groups
WHERE incoming_email IS NOT NULL OR email_username IS NOT NULL
SQL
- )
end
def category_email_in_regex
- @category_email_in_regex ||= Regexp.union Category.pluck(:email_in).select(&:present?).map { |e| e.split("|") }.flatten.uniq
+ @category_email_in_regex ||=
+ Regexp.union Category
+ .pluck(:email_in)
+ .select(&:present?)
+ .map { |e| e.split("|") }
+ .flatten
+ .uniq
end
def find_related_post(force: false)
@@ -1108,21 +1241,19 @@ module Email
if Array === references
references
elsif references.present?
- references.split(/[\s,]/).map do |r|
- Email::MessageIdService.message_id_clean(r)
- end
+ references.split(/[\s,]/).map { |r| Email::MessageIdService.message_id_clean(r) }
end
end
def likes
- @likes ||= Set.new ["+1", "<3", "❤", I18n.t('post_action_types.like.title').downcase]
+ @likes ||= Set.new ["+1", "<3", "❤", I18n.t("post_action_types.like.title").downcase]
end
def subscription_action_for(body, subject)
return unless SiteSetting.unsubscribe_via_email
return if sent_to_mailinglist_mirror?
- if ([subject, body].compact.map(&:to_s).map(&:downcase) & ['unsubscribe']).any?
+ if ([subject, body].compact.map(&:to_s).map(&:downcase) & ["unsubscribe"]).any?
:confirm_unsubscribe
end
end
@@ -1132,9 +1263,7 @@ module Email
end
def create_topic(options = {})
- if options[:archetype] == Archetype.private_message
- enable_email_pm_setting(options[:user])
- end
+ enable_email_pm_setting(options[:user]) if options[:archetype] == Archetype.private_message
create_post_with_attachments(options)
end
@@ -1151,26 +1280,36 @@ module Email
NotificationLevels.topic_levels[:tracking]
when "watch"
NotificationLevels.topic_levels[:watching]
- else nil
+ else
+ nil
end
end
def create_reply(options = {})
raise TopicNotFoundError if options[:topic].nil? || options[:topic].trashed?
- raise BouncedEmailError if options[:bounce] && options[:topic].archetype != Archetype.private_message
+ if options[:bounce] && options[:topic].archetype != Archetype.private_message
+ raise BouncedEmailError
+ end
options[:post] = nil if options[:post]&.trashed?
- enable_email_pm_setting(options[:user]) if options[:topic].archetype == Archetype.private_message
+ if options[:topic].archetype == Archetype.private_message
+ enable_email_pm_setting(options[:user])
+ end
if post_action_type = post_action_for(options[:raw])
create_post_action(options[:user], options[:post], post_action_type)
elsif notification_level = notification_level_for(options[:raw])
- TopicUser.change(options[:user].id, options[:post].topic_id, notification_level: notification_level)
+ TopicUser.change(
+ options[:user].id,
+ options[:post].topic_id,
+ notification_level: notification_level,
+ )
else
raise TopicClosedError if options[:topic].closed?
options[:topic_id] = options[:topic].id
options[:reply_to_post_number] = options[:post]&.post_number
- options[:is_group_message] = options[:topic].private_message? && options[:topic].allowed_groups.exists?
+ options[:is_group_message] = options[:topic].private_message? &&
+ options[:topic].allowed_groups.exists?
create_post_with_attachments(options)
end
end
@@ -1182,21 +1321,20 @@ module Email
def is_allowed?(attachment)
attachment.content_type !~ SiteSetting.blocked_attachment_content_types_regex &&
- attachment.filename !~ SiteSetting.blocked_attachment_filenames_regex
+ attachment.filename !~ SiteSetting.blocked_attachment_filenames_regex
end
def attachments
- @attachments ||= begin
- attachments = @mail.attachments.select { |attachment| is_allowed?(attachment) }
- attachments << @mail if @mail.attachment? && is_allowed?(@mail)
+ @attachments ||=
+ begin
+ attachments = @mail.attachments.select { |attachment| is_allowed?(attachment) }
+ attachments << @mail if @mail.attachment? && is_allowed?(@mail)
- @mail.parts.each do |part|
- attachments << part if part.attachment? && is_allowed?(part)
- end
+ @mail.parts.each { |part| attachments << part if part.attachment? && is_allowed?(part) }
- attachments.uniq!
- attachments
- end
+ attachments.uniq!
+ attachments
+ end
end
def create_post_with_attachments(options = {})
@@ -1223,10 +1361,13 @@ module Email
if raw[attachment.url]
raw.sub!(attachment.url, upload.url)
- InlineUploads.match_img(raw, uploads: { upload.url => upload }) do |match, src, replacement, _|
- if src == upload.url
- raw = raw.sub(match, replacement)
- end
+ InlineUploads.match_img(
+ raw,
+ uploads: {
+ upload.url => upload,
+ },
+ ) do |match, src, replacement, _|
+ raw = raw.sub(match, replacement) if src == upload.url
end
elsif raw[/\[image:[^\]]*\]/i]
raw.sub!(/\[image:[^\]]*\]/i, UploadMarkdown.new(upload).to_markdown)
@@ -1238,13 +1379,15 @@ module Email
end
else
rejected_attachments << upload
- raw << "\n\n#{I18n.t('emails.incoming.missing_attachment', filename: upload.original_filename)}\n\n"
+ raw << "\n\n#{I18n.t("emails.incoming.missing_attachment", filename: upload.original_filename)}\n\n"
end
ensure
tmp&.close!
end
end
- notify_about_rejected_attachment(rejected_attachments) if rejected_attachments.present? && !user.staged?
+ if rejected_attachments.present? && !user.staged?
+ notify_about_rejected_attachment(rejected_attachments)
+ end
raw
end
@@ -1262,19 +1405,21 @@ module Email
former_title: message.subject,
destination: message.to,
site_name: SiteSetting.title,
- rejected_errors: errors.join("\n")
+ rejected_errors: errors.join("\n"),
}
- client_message = RejectionMailer.send_rejection(:email_reject_attachment, message.from, template_args)
+ client_message =
+ RejectionMailer.send_rejection(:email_reject_attachment, message.from, template_args)
Email::Sender.new(client_message, :email_reject_attachment).send
end
def add_elided_to_raw!(options)
- is_private_message = options[:archetype] == Archetype.private_message ||
- options[:topic].try(:private_message?)
+ is_private_message =
+ options[:archetype] == Archetype.private_message || options[:topic].try(:private_message?)
# only add elided part in messages
- if options[:elided].present? && (SiteSetting.always_show_trimmed_content || is_private_message)
+ if options[:elided].present? &&
+ (SiteSetting.always_show_trimmed_content || is_private_message)
options[:raw] << Email::Receiver.elided_html(options[:elided])
options[:elided] = ""
end
@@ -1303,7 +1448,11 @@ module Email
user = options.delete(:user)
if options[:bounce]
- options[:raw] = I18n.t("system_messages.email_bounced", email: user.email, raw: options[:raw])
+ options[:raw] = I18n.t(
+ "system_messages.email_bounced",
+ email: user.email,
+ raw: options[:raw],
+ )
user = Discourse.system_user
options[:post_type] = Post.types[:whisper]
end
@@ -1316,16 +1465,16 @@ module Email
result = NewPostManager.new(user, options).perform
errors = result.errors.full_messages
- if errors.any? do |message|
+ if errors.any? { |message|
message.include?(I18n.t("activerecord.attributes.post.raw").strip) &&
- message.include?(I18n.t("errors.messages.too_short", count: SiteSetting.min_post_length).strip)
- end
+ message.include?(
+ I18n.t("errors.messages.too_short", count: SiteSetting.min_post_length).strip,
+ )
+ }
raise TooShortPost
end
- if result.errors.present?
- raise InvalidPost, errors.join("\n")
- end
+ raise InvalidPost, errors.join("\n") if result.errors.present?
if result.post
IncomingEmail.transaction do
@@ -1343,11 +1492,16 @@ module Email
# Alert the people involved in the topic now that the incoming email
# has been linked to the post.
- PostJobsEnqueuer.new(result.post, result.post.topic, options[:topic_id].blank?,
- import_mode: options[:import_mode],
- post_alert_options: options[:post_alert_options]
- ).enqueue_jobs
- DiscourseEvent.trigger(:topic_created, result.post.topic, options, user) if result.post.is_first_post?
+ PostJobsEnqueuer.new(
+ result.post,
+ result.post.topic,
+ options[:topic_id].blank?,
+ import_mode: options[:import_mode],
+ post_alert_options: options[:post_alert_options],
+ ).enqueue_jobs
+ if result.post.is_first_post?
+ DiscourseEvent.trigger(:topic_created, result.post.topic, options, user)
+ end
DiscourseEvent.trigger(:post_created, result.post, options, user)
end
@@ -1355,8 +1509,8 @@ module Email
end
def self.elided_html(elided)
- html = +"\n\n" << "<details class='elided'>" << "\n"
- html << "<summary title='#{I18n.t('emails.incoming.show_trimmed_content')}'>&#183;&#183;&#183;</summary>" << "\n\n"
+ html = +"\n\n" << "<details class='elided'>" << "\n"
+ html << "<summary title='#{I18n.t("emails.incoming.show_trimmed_content")}'>&#183;&#183;&#183;</summary>" << "\n\n"
html << elided << "\n\n"
html << "</details>" << "\n"
html
@@ -1365,7 +1519,7 @@ module Email
def add_other_addresses(post, sender, mail_object)
max_staged_users_post = nil
- %i(to cc bcc).each do |d|
+ %i[to cc bcc].each do |d|
next if mail_object[d].blank?
mail_object[d].each do |address_field|
@@ -1379,16 +1533,31 @@ module Email
user = User.find_by_email(email)
# cap number of staged users created per email
- if (!user || user.staged) && @staged_users.count >= SiteSetting.maximum_staged_users_per_email
- max_staged_users_post ||= post.topic.add_moderator_post(sender, I18n.t("emails.incoming.maximum_staged_user_per_email_reached"), import_mode: @opts[:import_mode])
+ if (!user || user.staged) &&
+ @staged_users.count >= SiteSetting.maximum_staged_users_per_email
+ max_staged_users_post ||=
+ post.topic.add_moderator_post(
+ sender,
+ I18n.t("emails.incoming.maximum_staged_user_per_email_reached"),
+ import_mode: @opts[:import_mode],
+ )
next
end
user = find_or_create_user(email, display_name, user: user)
if user && can_invite?(post.topic, user)
post.topic.topic_allowed_users.create!(user_id: user.id)
- TopicUser.auto_notification_for_staging(user.id, post.topic_id, TopicUser.notification_reasons[:auto_watch])
- post.topic.add_small_action(sender, "invited_user", user.username, import_mode: @opts[:import_mode])
+ TopicUser.auto_notification_for_staging(
+ user.id,
+ post.topic_id,
+ TopicUser.notification_reasons[:auto_watch],
+ )
+ post.topic.add_small_action(
+ sender,
+ "invited_user",
+ user.username,
+ import_mode: @opts[:import_mode],
+ )
end
end
rescue ActiveRecord::RecordInvalid, EmailNotAllowed
@@ -1400,13 +1569,15 @@ module Email
def should_invite?(email)
email !~ Email::Receiver.reply_by_email_address_regex &&
- email !~ group_incoming_emails_regex &&
- email !~ category_email_in_regex
+ email !~ group_incoming_emails_regex && email !~ category_email_in_regex
end
def can_invite?(topic, user)
!topic.topic_allowed_users.where(user_id: user.id).exists? &&
- !topic.topic_allowed_groups.where("group_id IN (SELECT group_id FROM group_users WHERE user_id = ?)", user.id).exists?
+ !topic
+ .topic_allowed_groups
+ .where("group_id IN (SELECT group_id FROM group_users WHERE user_id = ?)", user.id)
+ .exists?
end
def send_subscription_mail(action, user)
@@ -1419,26 +1590,21 @@ module Email
end
def stage_sender_user(email, display_name)
- find_or_create_user!(email, display_name).tap do |u|
- log_and_validate_user(u)
- end
+ find_or_create_user!(email, display_name).tap { |u| log_and_validate_user(u) }
end
def delete_created_staged_users
@created_staged_users.each do |user|
- if @incoming_email.user&.id == user.id
- @incoming_email.update_columns(user_id: nil)
- end
+ @incoming_email.update_columns(user_id: nil) if @incoming_email.user&.id == user.id
- if user.posts.count == 0
- UserDestroyer.new(Discourse.system_user).destroy(user, quiet: true)
- end
+ UserDestroyer.new(Discourse.system_user).destroy(user, quiet: true) if user.posts.count == 0
end
end
def enable_email_pm_setting(user)
# ensure user PM emails are enabled (since user is posting via email)
- if !user.staged && user.user_option.email_messages_level == UserOption.email_level_types[:never]
+ if !user.staged &&
+ user.user_option.email_messages_level == UserOption.email_level_types[:never]
user.user_option.update!(email_messages_level: UserOption.email_level_types[:always])
end
end
diff --git a/lib/email/renderer.rb b/lib/email/renderer.rb
index feeb63c4112..a375176e2c8 100644
--- a/lib/email/renderer.rb
+++ b/lib/email/renderer.rb
@@ -2,7 +2,6 @@
module Email
class Renderer
-
def initialize(message, opts = nil)
@message = message
@opts = opts || {}
@@ -10,26 +9,30 @@ module Email
def text
return @text if @text
- @text = (+(@message.text_part ? @message.text_part : @message).body.to_s).force_encoding('UTF-8')
+ @text =
+ (+(@message.text_part ? @message.text_part : @message).body.to_s).force_encoding("UTF-8")
@text = CGI.unescapeHTML(@text)
end
def html
- style = if @message.html_part
- Email::Styles.new(@message.html_part.body.to_s, @opts)
- else
- unstyled = UserNotificationRenderer.render(
- template: 'layouts/email_template',
- format: :html,
- locals: { html_body: PrettyText.cook(text).html_safe }
- )
- Email::Styles.new(unstyled, @opts)
- end
+ style =
+ if @message.html_part
+ Email::Styles.new(@message.html_part.body.to_s, @opts)
+ else
+ unstyled =
+ UserNotificationRenderer.render(
+ template: "layouts/email_template",
+ format: :html,
+ locals: {
+ html_body: PrettyText.cook(text).html_safe,
+ },
+ )
+ Email::Styles.new(unstyled, @opts)
+ end
style.format_basic
style.format_html
style.to_html
end
-
end
end
diff --git a/lib/email/sender.rb b/lib/email/sender.rb
index c31df8b76ac..1f3c59efd04 100644
--- a/lib/email/sender.rb
+++ b/lib/email/sender.rb
@@ -8,11 +8,11 @@
#
# It also adds an HTML part for the plain text body
#
-require 'uri'
-require 'net/smtp'
+require "uri"
+require "net/smtp"
SMTP_CLIENT_ERRORS = [Net::SMTPFatalError, Net::SMTPSyntaxError]
-BYPASS_DISABLE_TYPES = %w(
+BYPASS_DISABLE_TYPES = %w[
admin_login
test_message
new_version
@@ -20,11 +20,10 @@ BYPASS_DISABLE_TYPES = %w(
invite_password_instructions
download_backup_message
admin_confirmation_message
-)
+]
module Email
class Sender
-
def initialize(message, email_type, user = nil)
@message = message
@message_attachments_index = {}
@@ -35,33 +34,40 @@ module Email
def send
bypass_disable = BYPASS_DISABLE_TYPES.include?(@email_type.to_s)
- if SiteSetting.disable_emails == "yes" && !bypass_disable
- return
- end
+ return if SiteSetting.disable_emails == "yes" && !bypass_disable
return if ActionMailer::Base::NullMail === @message
- return if ActionMailer::Base::NullMail === (@message.message rescue nil)
+ if ActionMailer::Base::NullMail ===
+ (
+ begin
+ @message.message
+ rescue StandardError
+ nil
+ end
+ )
+ return
+ end
- return skip(SkippedEmailLog.reason_types[:sender_message_blank]) if @message.blank?
+ return skip(SkippedEmailLog.reason_types[:sender_message_blank]) if @message.blank?
return skip(SkippedEmailLog.reason_types[:sender_message_to_blank]) if @message.to.blank?
if SiteSetting.disable_emails == "non-staff" && !bypass_disable
return unless find_user&.staff?
end
- return skip(SkippedEmailLog.reason_types[:sender_message_to_invalid]) if to_address.end_with?(".invalid")
+ if to_address.end_with?(".invalid")
+ return skip(SkippedEmailLog.reason_types[:sender_message_to_invalid])
+ end
if @message.text_part
if @message.text_part.body.to_s.blank?
return skip(SkippedEmailLog.reason_types[:sender_text_part_body_blank])
end
else
- if @message.body.to_s.blank?
- return skip(SkippedEmailLog.reason_types[:sender_body_blank])
- end
+ return skip(SkippedEmailLog.reason_types[:sender_body_blank]) if @message.body.to_s.blank?
end
- @message.charset = 'UTF-8'
+ @message.charset = "UTF-8"
opts = {}
@@ -70,50 +76,58 @@ module Email
if @message.html_part
@message.html_part.body = renderer.html
else
- @message.html_part = Mail::Part.new do
- content_type 'text/html; charset=UTF-8'
- body renderer.html
- end
+ @message.html_part =
+ Mail::Part.new do
+ content_type "text/html; charset=UTF-8"
+ body renderer.html
+ end
end
# Fix relative (ie upload) HTML links in markdown which do not work well in plain text emails.
# These are the links we add when a user uploads a file or image.
# Ideally we would parse general markdown into plain text, but that is almost an intractable problem.
url_prefix = Discourse.base_url
- @message.parts[0].body = @message.parts[0].body.to_s.gsub(/<a class="attachment" href="(\/uploads\/default\/[^"]+)">([^<]*)<\/a>/, '[\2|attachment](' + url_prefix + '\1)')
- @message.parts[0].body = @message.parts[0].body.to_s.gsub(/<img src="(\/uploads\/default\/[^"]+)"([^>]*)>/, '![](' + url_prefix + '\1)')
+ @message.parts[0].body =
+ @message.parts[0].body.to_s.gsub(
+ %r{<a class="attachment" href="(/uploads/default/[^"]+)">([^<]*)</a>},
+ '[\2|attachment](' + url_prefix + '\1)',
+ )
+ @message.parts[0].body =
+ @message.parts[0].body.to_s.gsub(
+ %r{<img src="(/uploads/default/[^"]+)"([^>]*)>},
+ "![](" + url_prefix + '\1)',
+ )
- @message.text_part.content_type = 'text/plain; charset=UTF-8'
+ @message.text_part.content_type = "text/plain; charset=UTF-8"
user_id = @user&.id
# Set up the email log
- email_log = EmailLog.new(
- email_type: @email_type,
- to_address: to_address,
- user_id: user_id
- )
+ email_log = EmailLog.new(email_type: @email_type, to_address: to_address, user_id: user_id)
if cc_addresses.any?
email_log.cc_addresses = cc_addresses.join(";")
email_log.cc_user_ids = User.with_email(cc_addresses).pluck(:id)
end
- if bcc_addresses.any?
- email_log.bcc_addresses = bcc_addresses.join(";")
- end
+ email_log.bcc_addresses = bcc_addresses.join(";") if bcc_addresses.any?
host = Email::Sender.host_for(Discourse.base_url)
- post_id = header_value('X-Discourse-Post-Id')
- topic_id = header_value('X-Discourse-Topic-Id')
+ post_id = header_value("X-Discourse-Post-Id")
+ topic_id = header_value("X-Discourse-Topic-Id")
reply_key = get_reply_key(post_id, user_id)
from_address = @message.from&.first
- smtp_group_id = from_address.blank? ? nil : Group.where(
- email_username: from_address, smtp_enabled: true
- ).pluck_first(:id)
+ smtp_group_id =
+ (
+ if from_address.blank?
+ nil
+ else
+ Group.where(email_username: from_address, smtp_enabled: true).pluck_first(:id)
+ end
+ )
# always set a default Message ID from the host
- @message.header['Message-ID'] = Email::MessageIdService.generate_default
+ @message.header["Message-ID"] = Email::MessageIdService.generate_default
if topic_id.present? && post_id.present?
post = Post.find_by(id: post_id, topic_id: topic_id)
@@ -130,12 +144,14 @@ module Email
# See https://www.ietf.org/rfc/rfc2919.txt for the List-ID
# specification.
if topic&.category && !topic.category.uncategorized?
- list_id = "#{SiteSetting.title} | #{topic.category.name} <#{topic.category.name.downcase.tr(' ', '-')}.#{host}>"
+ list_id =
+ "#{SiteSetting.title} | #{topic.category.name} <#{topic.category.name.downcase.tr(" ", "-")}.#{host}>"
# subcategory case
if !topic.category.parent_category_id.nil?
parent_category_name = Category.find_by(id: topic.category.parent_category_id).name
- list_id = "#{SiteSetting.title} | #{parent_category_name} #{topic.category.name} <#{topic.category.name.downcase.tr(' ', '-')}.#{parent_category_name.downcase.tr(' ', '-')}.#{host}>"
+ list_id =
+ "#{SiteSetting.title} | #{parent_category_name} #{topic.category.name} <#{topic.category.name.downcase.tr(" ", "-")}.#{parent_category_name.downcase.tr(" ", "-")}.#{host}>"
end
else
list_id = "#{SiteSetting.title} <#{host}>"
@@ -148,16 +164,15 @@ module Email
# conversation between the group and a small handful of people
# directly contacting the group, often just one person.
if !smtp_group_id
-
# https://www.ietf.org/rfc/rfc3834.txt
- @message.header['Precedence'] = 'list'
- @message.header['List-ID'] = list_id
+ @message.header["Precedence"] = "list"
+ @message.header["List-ID"] = list_id
if topic
if SiteSetting.private_email?
- @message.header['List-Archive'] = "#{Discourse.base_url}#{topic.slugless_url}"
+ @message.header["List-Archive"] = "#{Discourse.base_url}#{topic.slugless_url}"
else
- @message.header['List-Archive'] = topic.url
+ @message.header["List-Archive"] = topic.url
end
end
end
@@ -176,61 +191,59 @@ module Email
email_log.topic_id = topic_id if topic_id.present?
if reply_key.present?
- @message.header['Reply-To'] = header_value('Reply-To').gsub!("%{reply_key}", reply_key)
+ @message.header["Reply-To"] = header_value("Reply-To").gsub!("%{reply_key}", reply_key)
@message.header[Email::MessageBuilder::ALLOW_REPLY_BY_EMAIL_HEADER] = nil
end
- MessageBuilder.custom_headers(SiteSetting.email_custom_headers).each do |key, _|
- # Any custom headers added via MessageBuilder that are doubled up here
- # with values that we determine should be set to the last value, which is
- # the one we determined. Our header values should always override the email_custom_headers.
- #
- # While it is valid via RFC5322 to have more than one value for certain headers,
- # we just want to keep it to one, especially in cases where the custom value
- # would conflict with our own.
- #
- # See https://datatracker.ietf.org/doc/html/rfc5322#section-3.6 and
- # https://github.com/mikel/mail/blob/8ef377d6a2ca78aa5bd7f739813f5a0648482087/lib/mail/header.rb#L109-L132
- custom_header = @message.header[key]
- if custom_header.is_a?(Array)
- our_value = custom_header.last.value
-
- # Must be set to nil first otherwise another value is just added
- # to the array of values for the header.
- @message.header[key] = nil
- @message.header[key] = our_value
- end
-
- value = header_value(key)
+ MessageBuilder
+ .custom_headers(SiteSetting.email_custom_headers)
+ .each do |key, _|
+ # Any custom headers added via MessageBuilder that are doubled up here
+ # with values that we determine should be set to the last value, which is
+ # the one we determined. Our header values should always override the email_custom_headers.
+ #
+ # While it is valid via RFC5322 to have more than one value for certain headers,
+ # we just want to keep it to one, especially in cases where the custom value
+ # would conflict with our own.
+ #
+ # See https://datatracker.ietf.org/doc/html/rfc5322#section-3.6 and
+ # https://github.com/mikel/mail/blob/8ef377d6a2ca78aa5bd7f739813f5a0648482087/lib/mail/header.rb#L109-L132
+ custom_header = @message.header[key]
+ if custom_header.is_a?(Array)
+ our_value = custom_header.last.value
+
+ # Must be set to nil first otherwise another value is just added
+ # to the array of values for the header.
+ @message.header[key] = nil
+ @message.header[key] = our_value
+ end
- # Remove Auto-Submitted header for group private message emails, it does
- # not make sense there and may hurt deliverability.
- #
- # From https://www.iana.org/assignments/auto-submitted-keywords/auto-submitted-keywords.xhtml:
- #
- # > Indicates that a message was generated by an automatic process, and is not a direct response to another message.
- if key.downcase == "auto-submitted" && smtp_group_id
- @message.header[key] = nil
- end
+ value = header_value(key)
- # Replace reply_key in custom headers or remove
- if value&.include?('%{reply_key}')
- # Delete old header first or else the same header will be added twice
- @message.header[key] = nil
- if reply_key.present?
- @message.header[key] = value.gsub!('%{reply_key}', reply_key)
+ # Remove Auto-Submitted header for group private message emails, it does
+ # not make sense there and may hurt deliverability.
+ #
+ # From https://www.iana.org/assignments/auto-submitted-keywords/auto-submitted-keywords.xhtml:
+ #
+ # > Indicates that a message was generated by an automatic process, and is not a direct response to another message.
+ @message.header[key] = nil if key.downcase == "auto-submitted" && smtp_group_id
+
+ # Replace reply_key in custom headers or remove
+ if value&.include?("%{reply_key}")
+ # Delete old header first or else the same header will be added twice
+ @message.header[key] = nil
+ @message.header[key] = value.gsub!("%{reply_key}", reply_key) if reply_key.present?
end
end
- end
# pass the original message_id when using mailjet/mandrill/sparkpost
case ActionMailer::Base.smtp_settings[:address]
when /\.mailjet\.com/
- @message.header['X-MJ-CustomID'] = @message.message_id
+ @message.header["X-MJ-CustomID"] = @message.message_id
when "smtp.mandrillapp.com"
- merge_json_x_header('X-MC-Metadata', message_id: @message.message_id)
+ merge_json_x_header("X-MC-Metadata", message_id: @message.message_id)
when "smtp.sparkpostmail.com"
- merge_json_x_header('X-MSYS-API', metadata: { message_id: @message.message_id })
+ merge_json_x_header("X-MSYS-API", metadata: { message_id: @message.message_id })
end
# Parse the HTML again so we can make any final changes before
@@ -239,8 +252,8 @@ module Email
# Suppress images from short emails
if SiteSetting.strip_images_from_short_emails &&
- @message.html_part.body.to_s.bytesize <= SiteSetting.short_email_length &&
- @message.html_part.body =~ /<img[^>]+>/
+ @message.html_part.body.to_s.bytesize <= SiteSetting.short_email_length &&
+ @message.html_part.body =~ /<img[^>]+>/
style.strip_avatars_and_emojis
end
@@ -291,23 +304,26 @@ module Email
end
def to_address
- @to_address ||= begin
- to = @message.try(:to)
- to = to.first if Array === to
- to.presence || "no_email_found"
- end
+ @to_address ||=
+ begin
+ to = @message.try(:to)
+ to = to.first if Array === to
+ to.presence || "no_email_found"
+ end
end
def cc_addresses
- @cc_addresses ||= begin
- @message.try(:cc) || []
- end
+ @cc_addresses ||=
+ begin
+ @message.try(:cc) || []
+ end
end
def bcc_addresses
- @bcc_addresses ||= begin
- @message.try(:bcc) || []
- end
+ @bcc_addresses ||=
+ begin
+ @message.try(:bcc) || []
+ end
end
def self.host_for(base_url)
@@ -333,7 +349,7 @@ module Email
optimized_1X = original_upload.optimized_images.first
if FileHelper.is_supported_image?(original_upload.original_filename) &&
- !should_attach_image?(original_upload, optimized_1X)
+ !should_attach_image?(original_upload, optimized_1X)
next
end
@@ -341,11 +357,12 @@ module Email
next if email_size + attached_upload.filesize > max_email_size
begin
- path = if attached_upload.local?
- Discourse.store.path_for(attached_upload)
- else
- Discourse.store.download(attached_upload).path
- end
+ path =
+ if attached_upload.local?
+ Discourse.store.path_for(attached_upload)
+ else
+ Discourse.store.download(attached_upload).path
+ end
@message_attachments_index[original_upload.sha1] = @message.attachments.size
@message.attachments[original_upload.original_filename] = File.read(path)
@@ -357,8 +374,8 @@ module Email
env: {
post_id: post.id,
upload_id: original_upload.id,
- filename: original_upload.original_filename
- }
+ filename: original_upload.original_filename,
+ },
)
end
end
@@ -368,7 +385,10 @@ module Email
def should_attach_image?(upload, optimized_1X = nil)
return if !SiteSetting.secure_uploads_allow_embed_images_in_emails || !upload.secure?
- return if (optimized_1X&.filesize || upload.filesize) > SiteSetting.secure_uploads_max_email_embed_image_size_kb.kilobytes
+ if (optimized_1X&.filesize || upload.filesize) >
+ SiteSetting.secure_uploads_max_email_embed_image_size_kb.kilobytes
+ return
+ end
true
end
@@ -391,8 +411,7 @@ module Email
#
def fix_parts_after_attachments!
has_attachments = @message.attachments.present?
- has_alternative_renderings =
- @message.html_part.present? && @message.text_part.present?
+ has_alternative_renderings = @message.html_part.present? && @message.text_part.present?
if has_attachments && has_alternative_renderings
@message.content_type = "multipart/mixed"
@@ -403,15 +422,16 @@ module Email
text_part = @message.text_part
@message.text_part = nil
- content = Mail::Part.new do
- content_type "multipart/alternative"
+ content =
+ Mail::Part.new do
+ content_type "multipart/alternative"
- # we have to re-specify the charset and give the part the decoded body
- # here otherwise the parts will get encoded with US-ASCII which makes
- # a bunch of characters not render correctly in the email
- part content_type: "text/html; charset=utf-8", body: html_part.body.decoded
- part content_type: "text/plain; charset=utf-8", body: text_part.body.decoded
- end
+ # we have to re-specify the charset and give the part the decoded body
+ # here otherwise the parts will get encoded with US-ASCII which makes
+ # a bunch of characters not render correctly in the email
+ part content_type: "text/html; charset=utf-8", body: html_part.body.decoded
+ part content_type: "text/plain; charset=utf-8", body: text_part.body.decoded
+ end
@message.parts.unshift(content)
end
@@ -437,7 +457,7 @@ module Email
email_type: @email_type,
to_address: to_address,
user_id: @user&.id,
- reason_type: reason_type
+ reason_type: reason_type,
}
attributes[:custom_reason] = custom_reason if custom_reason
@@ -445,7 +465,12 @@ module Email
end
def merge_json_x_header(name, value)
- data = JSON.parse(@message.header[name].to_s) rescue nil
+ data =
+ begin
+ JSON.parse(@message.header[name].to_s)
+ rescue StandardError
+ nil
+ end
data ||= {}
data.merge!(value)
# /!\ @message.header is not a standard ruby hash.
@@ -460,12 +485,12 @@ module Email
def get_reply_key(post_id, user_id)
# ALLOW_REPLY_BY_EMAIL_HEADER is only added if we are _not_ sending
# via group SMTP and if reply by email site settings are configured
- return if !user_id || !post_id || !header_value(Email::MessageBuilder::ALLOW_REPLY_BY_EMAIL_HEADER).present?
+ if !user_id || !post_id ||
+ !header_value(Email::MessageBuilder::ALLOW_REPLY_BY_EMAIL_HEADER).present?
+ return
+ end
- PostReplyKey.create_or_find_by!(
- post_id: post_id,
- user_id: user_id
- ).reply_key
+ PostReplyKey.create_or_find_by!(post_id: post_id, user_id: user_id).reply_key
end
def self.bounceable_reply_address?
@@ -514,7 +539,9 @@ module Email
#
# https://meta.discourse.org/t/discourse-email-messages-are-incorrectly-threaded/233499
def add_identification_field_headers(topic, post)
- @message.header["Message-ID"] = Email::MessageIdService.generate_or_use_existing(post.id).first
+ @message.header["Message-ID"] = Email::MessageIdService.generate_or_use_existing(
+ post.id,
+ ).first
if post.post_number > 1
op_message_id = Email::MessageIdService.generate_or_use_existing(topic.first_post.id).first
@@ -523,11 +550,12 @@ module Email
# Whenever we reply to a post directly _or_ quote a post, a PostReply
# record is made, with the reply_post_id referencing the newly created
# post, and the post_id referencing the post that was quoted or replied to.
- referenced_posts = Post
- .joins("INNER JOIN post_replies ON post_replies.post_id = posts.id ")
- .where("post_replies.reply_post_id = ?", post.id)
- .order(id: :desc)
- .to_a
+ referenced_posts =
+ Post
+ .joins("INNER JOIN post_replies ON post_replies.post_id = posts.id ")
+ .where("post_replies.reply_post_id = ?", post.id)
+ .order(id: :desc)
+ .to_a
##
# No referenced posts means that we are just creating a new post not
@@ -543,7 +571,8 @@ module Email
# every directly replied to post can go into In-Reply-To.
#
# We want to make sure all of the outbound_message_ids are already filled here.
- in_reply_to_message_ids = MessageIdService.generate_or_use_existing(referenced_posts.map(&:id))
+ in_reply_to_message_ids =
+ MessageIdService.generate_or_use_existing(referenced_posts.map(&:id))
@message.header["In-Reply-To"] = in_reply_to_message_ids
most_recent_post_message_id = in_reply_to_message_ids.last
@@ -559,7 +588,9 @@ module Email
parent_message_ids = MessageIdService.generate_or_use_existing(reply_tree.values.flatten)
@message.header["References"] = [
- op_message_id, parent_message_ids, most_recent_post_message_id
+ op_message_id,
+ parent_message_ids,
+ most_recent_post_message_id,
].flatten.uniq
end
end
diff --git a/lib/email/styles.rb b/lib/email/styles.rb
index cd561eb8b58..ee240b981ef 100644
--- a/lib/email/styles.rb
+++ b/lib/email/styles.rb
@@ -7,7 +7,8 @@
module Email
class Styles
MAX_IMAGE_DIMENSION = 400
- ONEBOX_IMAGE_BASE_STYLE = "max-height: 80%; max-width: 20%; height: auto; float: left; margin-right: 10px;"
+ ONEBOX_IMAGE_BASE_STYLE =
+ "max-height: 80%; max-width: 20%; height: auto; float: left; margin-right: 10px;"
ONEBOX_IMAGE_THUMBNAIL_STYLE = "width: 60px;"
ONEBOX_INLINE_AVATAR_STYLE = "width: 20px; height: 20px; float: none; vertical-align: middle;"
@@ -29,12 +30,12 @@ module Email
end
def add_styles(node, new_styles)
- existing = node['style']
+ existing = node["style"]
if existing.present?
# merge styles
- node['style'] = "#{new_styles}; #{existing}"
+ node["style"] = "#{new_styles}; #{existing}"
else
- node['style'] = new_styles
+ node["style"] = new_styles
end
end
@@ -47,12 +48,12 @@ module Email
if !css.blank?
# there is a minor race condition here, CssParser could be
# loaded by ::CssParser::Parser not loaded
- require 'css_parser' unless defined?(::CssParser::Parser)
+ require "css_parser" unless defined?(::CssParser::Parser)
parser = ::CssParser::Parser.new(import: false)
parser.load_string!(css)
parser.each_selector do |selector, value|
- @custom_styles[selector] ||= +''
+ @custom_styles[selector] ||= +""
@custom_styles[selector] << value
end
end
@@ -67,118 +68,148 @@ module Email
@fragment.css('svg, img[src$=".svg"]').remove
# images
- @fragment.css('img').each do |img|
- next if img['class'] == 'site-logo'
-
- if (img['class'] && img['class']['emoji']) || (img['src'] && img['src'][/\/_?emoji\//])
- img['width'] = img['height'] = 20
- else
- # use dimensions of original iPhone screen for 'too big, let device rescale'
- if img['width'].to_i > (320) || img['height'].to_i > (480)
- img['width'] = img['height'] = 'auto'
+ @fragment
+ .css("img")
+ .each do |img|
+ next if img["class"] == "site-logo"
+
+ if (img["class"] && img["class"]["emoji"]) || (img["src"] && img["src"][%r{/_?emoji/}])
+ img["width"] = img["height"] = 20
+ else
+ # use dimensions of original iPhone screen for 'too big, let device rescale'
+ if img["width"].to_i > (320) || img["height"].to_i > (480)
+ img["width"] = img["height"] = "auto"
+ end
end
- end
- if img['src']
- # ensure all urls are absolute
- img['src'] = "#{Discourse.base_url}#{img['src']}" if img['src'][/^\/[^\/]/]
- # ensure no schemaless urls
- img['src'] = "#{uri.scheme}:#{img['src']}" if img['src'][/^\/\//]
+ if img["src"]
+ # ensure all urls are absolute
+ img["src"] = "#{Discourse.base_url}#{img["src"]}" if img["src"][%r{^/[^/]}]
+ # ensure no schemaless urls
+ img["src"] = "#{uri.scheme}:#{img["src"]}" if img["src"][%r{^//}]
+ end
end
- end
# add max-width to big images
- big_images = @fragment.css('img[width="auto"][height="auto"]') -
- @fragment.css('aside.onebox img') -
- @fragment.css('img.site-logo, img.emoji')
- big_images.each do |img|
- add_styles(img, 'max-width: 100%;') if img['style'] !~ /max-width/
- end
+ big_images =
+ @fragment.css('img[width="auto"][height="auto"]') - @fragment.css("aside.onebox img") -
+ @fragment.css("img.site-logo, img.emoji")
+ big_images.each { |img| add_styles(img, "max-width: 100%;") if img["style"] !~ /max-width/ }
# topic featured link
- @fragment.css('a.topic-featured-link').each do |e|
- e['style'] = "color:#858585;padding:2px 8px;border:1px solid #e6e6e6;border-radius:2px;box-shadow:0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);"
- end
+ @fragment
+ .css("a.topic-featured-link")
+ .each do |e|
+ e[
+ "style"
+ ] = "color:#858585;padding:2px 8px;border:1px solid #e6e6e6;border-radius:2px;box-shadow:0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);"
+ end
# attachments
- @fragment.css('a.attachment').each do |a|
- # ensure all urls are absolute
- if a['href'] =~ /^\/[^\/]/
- a['href'] = "#{Discourse.base_url}#{a['href']}"
- end
+ @fragment
+ .css("a.attachment")
+ .each do |a|
+ # ensure all urls are absolute
+ a["href"] = "#{Discourse.base_url}#{a["href"]}" if a["href"] =~ %r{^/[^/]}
- # ensure no schemaless urls
- if a['href'] && a['href'].starts_with?("//")
- a['href'] = "#{uri.scheme}:#{a['href']}"
+ # ensure no schemaless urls
+ a["href"] = "#{uri.scheme}:#{a["href"]}" if a["href"] && a["href"].starts_with?("//")
end
- end
end
def onebox_styles
# Links to other topics
- style('aside.quote', 'padding: 12px 25px 2px 12px; margin-bottom: 10px;')
- style('aside.quote div.info-line', 'color: #666; margin: 10px 0')
- style('aside.quote .avatar', 'margin-right: 5px; width:20px; height:20px; vertical-align:middle;')
- style('aside.quote', 'border-left: 5px solid #e9e9e9; background-color: #f8f8f8; margin: 0;')
+ style("aside.quote", "padding: 12px 25px 2px 12px; margin-bottom: 10px;")
+ style("aside.quote div.info-line", "color: #666; margin: 10px 0")
+ style(
+ "aside.quote .avatar",
+ "margin-right: 5px; width:20px; height:20px; vertical-align:middle;",
+ )
+ style("aside.quote", "border-left: 5px solid #e9e9e9; background-color: #f8f8f8; margin: 0;")
- style('blockquote', 'border-left: 5px solid #e9e9e9; background-color: #f8f8f8; margin-left: 0; padding: 12px;')
+ style(
+ "blockquote",
+ "border-left: 5px solid #e9e9e9; background-color: #f8f8f8; margin-left: 0; padding: 12px;",
+ )
# Oneboxes
- style('aside.onebox', "border: 5px solid #e9e9e9; padding: 12px 25px 12px 12px; margin-bottom: 10px;")
- style('aside.onebox header img.site-icon', "width: 16px; height: 16px; margin-right: 3px;")
- style('aside.onebox header a[href]', "color: #222222; text-decoration: none;")
- style('aside.onebox .onebox-body', "clear: both")
- style('aside.onebox .onebox-body img:not(.onebox-avatar-inline)', ONEBOX_IMAGE_BASE_STYLE)
- style('aside.onebox .onebox-body img.thumbnail', ONEBOX_IMAGE_THUMBNAIL_STYLE)
- style('aside.onebox .onebox-body h3, aside.onebox .onebox-body h4', "font-size: 1.17em; margin: 10px 0;")
- style('.onebox-metadata', "color: #919191")
- style('.github-info', "margin-top: 10px;")
- style('.github-info .added', "color: #090;")
- style('.github-info .removed', "color: #e45735;")
- style('.github-info div', "display: inline; margin-right: 10px;")
- style('.github-icon-container', 'float: left;')
- style('.github-icon-container *', 'fill: #646464; width: 40px; height: 40px;')
- style('.github-body-container', 'font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace; margin-top: 1em !important;')
- style('.onebox-avatar-inline', ONEBOX_INLINE_AVATAR_STYLE)
-
- @fragment.css('.github-body-container .excerpt').remove
-
- @fragment.css('aside.quote blockquote > p').each do |p|
- p['style'] = 'padding: 0;'
- end
+ style(
+ "aside.onebox",
+ "border: 5px solid #e9e9e9; padding: 12px 25px 12px 12px; margin-bottom: 10px;",
+ )
+ style("aside.onebox header img.site-icon", "width: 16px; height: 16px; margin-right: 3px;")
+ style("aside.onebox header a[href]", "color: #222222; text-decoration: none;")
+ style("aside.onebox .onebox-body", "clear: both")
+ style("aside.onebox .onebox-body img:not(.onebox-avatar-inline)", ONEBOX_IMAGE_BASE_STYLE)
+ style("aside.onebox .onebox-body img.thumbnail", ONEBOX_IMAGE_THUMBNAIL_STYLE)
+ style(
+ "aside.onebox .onebox-body h3, aside.onebox .onebox-body h4",
+ "font-size: 1.17em; margin: 10px 0;",
+ )
+ style(".onebox-metadata", "color: #919191")
+ style(".github-info", "margin-top: 10px;")
+ style(".github-info .added", "color: #090;")
+ style(".github-info .removed", "color: #e45735;")
+ style(".github-info div", "display: inline; margin-right: 10px;")
+ style(".github-icon-container", "float: left;")
+ style(".github-icon-container *", "fill: #646464; width: 40px; height: 40px;")
+ style(
+ ".github-body-container",
+ 'font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace; margin-top: 1em !important;',
+ )
+ style(".onebox-avatar-inline", ONEBOX_INLINE_AVATAR_STYLE)
+
+ @fragment.css(".github-body-container .excerpt").remove
+
+ @fragment.css("aside.quote blockquote > p").each { |p| p["style"] = "padding: 0;" }
# Convert all `aside.quote` tags to `blockquote`s
- @fragment.css('aside.quote').each do |n|
- original_node = n.dup
- original_node.search('div.quote-controls').remove
- blockquote = original_node.css('blockquote').inner_html.strip.start_with?("<p") ? original_node.css('blockquote').inner_html : "<p style='padding: 0;'>#{original_node.css('blockquote').inner_html}</p>"
- n.inner_html = original_node.css('div.title').inner_html + blockquote
- n.name = "blockquote"
- end
+ @fragment
+ .css("aside.quote")
+ .each do |n|
+ original_node = n.dup
+ original_node.search("div.quote-controls").remove
+ blockquote =
+ (
+ if original_node.css("blockquote").inner_html.strip.start_with?("<p")
+ original_node.css("blockquote").inner_html
+ else
+ "<p style='padding: 0;'>#{original_node.css("blockquote").inner_html}</p>"
+ end
+ )
+ n.inner_html = original_node.css("div.title").inner_html + blockquote
+ n.name = "blockquote"
+ end
# Finally, convert all `aside` tags to `div`s
- @fragment.css('aside, article, header').each do |n|
- n.name = "div"
- end
+ @fragment.css("aside, article, header").each { |n| n.name = "div" }
# iframes can't go in emails, so replace them with clickable links
- @fragment.css('iframe').each do |i|
- begin
- # sometimes, iframes are blocklisted...
- if i["src"].blank?
+ @fragment
+ .css("iframe")
+ .each do |i|
+ begin
+ # sometimes, iframes are blocklisted...
+ if i["src"].blank?
+ i.remove
+ next
+ end
+
+ src_uri =
+ i["data-original-href"].present? ? URI(i["data-original-href"]) : URI(i["src"])
+ # If an iframe is protocol relative, use SSL when displaying it
+ display_src =
+ "#{src_uri.scheme || "https"}://#{src_uri.host}#{src_uri.path}#{src_uri.query.nil? ? "" : "?" + src_uri.query}#{src_uri.fragment.nil? ? "" : "#" + src_uri.fragment}"
+ i.replace(
+ Nokogiri::HTML5.fragment(
+ "<p><a href='#{src_uri.to_s}'>#{CGI.escapeHTML(display_src)}</a><p>",
+ ),
+ )
+ rescue URI::Error
+ # If the URL is weird, remove the iframe
i.remove
- next
end
-
- src_uri = i["data-original-href"].present? ? URI(i["data-original-href"]) : URI(i['src'])
- # If an iframe is protocol relative, use SSL when displaying it
- display_src = "#{src_uri.scheme || 'https'}://#{src_uri.host}#{src_uri.path}#{src_uri.query.nil? ? '' : '?' + src_uri.query}#{src_uri.fragment.nil? ? '' : '#' + src_uri.fragment}"
- i.replace(Nokogiri::HTML5.fragment("<p><a href='#{src_uri.to_s}'>#{CGI.escapeHTML(display_src)}</a><p>"))
- rescue URI::Error
- # If the URL is weird, remove the iframe
- i.remove
end
- end
end
def format_html
@@ -189,67 +220,93 @@ module Email
reset_tables
html_lang = SiteSetting.default_locale.sub("_", "-")
- style('html', nil, lang: html_lang, 'xml:lang' => html_lang)
- style('body', "line-height: 1.4; text-align:#{ Rtl.new(nil).enabled? ? 'right' : 'left' };")
- style('body', nil, dir: Rtl.new(nil).enabled? ? 'rtl' : 'ltr')
+ style("html", nil, :lang => html_lang, "xml:lang" => html_lang)
+ style("body", "line-height: 1.4; text-align:#{Rtl.new(nil).enabled? ? "right" : "left"};")
+ style("body", nil, dir: Rtl.new(nil).enabled? ? "rtl" : "ltr")
+
+ style(
+ ".with-dir",
+ "text-align:#{Rtl.new(nil).enabled? ? "right" : "left"};",
+ dir: Rtl.new(nil).enabled? ? "rtl" : "ltr",
+ )
- style('.with-dir',
- "text-align:#{ Rtl.new(nil).enabled? ? 'right' : 'left' };",
- dir: Rtl.new(nil).enabled? ? 'rtl' : 'ltr'
+ style("blockquote > :first-child", "margin-top: 0;")
+ style("blockquote > :last-child", "margin-bottom: 0;")
+ style("blockquote > p", "padding: 0;")
+
+ style(
+ ".with-accent-colors",
+ "background-color: #{SiteSetting.email_accent_bg_color}; color: #{SiteSetting.email_accent_fg_color};",
+ )
+ style("h4", "color: #222;")
+ style("h3", "margin: 30px 0 10px;")
+ style("hr", "background-color: #ddd; height: 1px; border: 1px;")
+ style(
+ "a",
+ "text-decoration: none; font-weight: bold; color: #{SiteSetting.email_link_color};",
+ )
+ style("ul", "margin: 0 0 0 10px; padding: 0 0 0 20px;")
+ style("li", "padding-bottom: 10px")
+ style("div.summary-footer", "color:#666; font-size:95%; text-align:center; padding-top:15px;")
+ style("span.post-count", "margin: 0 5px; color: #777;")
+ style("pre", "word-wrap: break-word; max-width: 694px;")
+ style("code", "background-color: #f9f9f9; padding: 2px 5px;")
+ style("pre code", "display: block; background-color: #f9f9f9; overflow: auto; padding: 5px;")
+ style("pre.onebox code", "white-space: normal;")
+ style("pre code li", "white-space: pre;")
+ style(
+ ".featured-topic a",
+ "text-decoration: none; font-weight: bold; color: #{SiteSetting.email_link_color}; line-height:1.5em;",
+ )
+ style(
+ ".summary-email",
+ "-moz-box-sizing:border-box;-ms-text-size-adjust:100%;-webkit-box-sizing:border-box;-webkit-text-size-adjust:100%;box-sizing:border-box;color:#0a0a0a;font-family:Arial,sans-serif;font-size:14px;font-weight:400;line-height:1.3;margin:0;min-width:100%;padding:0;width:100%",
)
- style('blockquote > :first-child', 'margin-top: 0;')
- style('blockquote > :last-child', 'margin-bottom: 0;')
- style('blockquote > p', 'padding: 0;')
-
- style('.with-accent-colors', "background-color: #{SiteSetting.email_accent_bg_color}; color: #{SiteSetting.email_accent_fg_color};")
- style('h4', 'color: #222;')
- style('h3', 'margin: 30px 0 10px;')
- style('hr', 'background-color: #ddd; height: 1px; border: 1px;')
- style('a', "text-decoration: none; font-weight: bold; color: #{SiteSetting.email_link_color};")
- style('ul', 'margin: 0 0 0 10px; padding: 0 0 0 20px;')
- style('li', 'padding-bottom: 10px')
- style('div.summary-footer', 'color:#666; font-size:95%; text-align:center; padding-top:15px;')
- style('span.post-count', 'margin: 0 5px; color: #777;')
- style('pre', 'word-wrap: break-word; max-width: 694px;')
- style('code', 'background-color: #f9f9f9; padding: 2px 5px;')
- style('pre code', 'display: block; background-color: #f9f9f9; overflow: auto; padding: 5px;')
- style('pre.onebox code', 'white-space: normal;')
- style('pre code li', 'white-space: pre;')
- style('.featured-topic a', "text-decoration: none; font-weight: bold; color: #{SiteSetting.email_link_color}; line-height:1.5em;")
- style('.summary-email', "-moz-box-sizing:border-box;-ms-text-size-adjust:100%;-webkit-box-sizing:border-box;-webkit-text-size-adjust:100%;box-sizing:border-box;color:#0a0a0a;font-family:Arial,sans-serif;font-size:14px;font-weight:400;line-height:1.3;margin:0;min-width:100%;padding:0;width:100%")
-
- style('.previous-discussion', 'font-size: 17px; color: #444; margin-bottom:10px;')
- style('.notification-date', "text-align:right;color:#999999;padding-right:5px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;font-size:11px")
- style('.username', "font-size:13px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;text-decoration:none;font-weight:bold")
- style('.username-link', "color:#{SiteSetting.email_link_color};")
- style('.username-title', "color:#777;margin-left:5px;")
- style('.user-title', "font-size:13px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;text-decoration:none;margin-left:5px;color: #999;")
- style('.post-wrapper', "margin-bottom:25px;")
- style('.user-avatar', 'vertical-align:top;width:55px;')
- style('.user-avatar img', nil, width: '45', height: '45')
- style('hr', 'background-color: #ddd; height: 1px; border: 1px;')
- style('.rtl', 'direction: rtl;')
- style('div.body', 'padding-top:5px;')
- style('.whisper div.body', 'font-style: italic; color: #9c9c9c;')
- style('.lightbox-wrapper .meta', 'display: none')
- style('div.undecorated-link-footer a', "font-weight: normal;")
- style('.mso-accent-link', "mso-border-alt: 6px solid #{SiteSetting.email_accent_bg_color}; background-color: #{SiteSetting.email_accent_bg_color};")
- style('.reply-above-line', "font-size: 10px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;color: #b5b5b5;padding: 5px 0px 20px;border-top: 1px dotted #ddd;")
+ style(".previous-discussion", "font-size: 17px; color: #444; margin-bottom:10px;")
+ style(
+ ".notification-date",
+ "text-align:right;color:#999999;padding-right:5px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;font-size:11px",
+ )
+ style(
+ ".username",
+ "font-size:13px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;text-decoration:none;font-weight:bold",
+ )
+ style(".username-link", "color:#{SiteSetting.email_link_color};")
+ style(".username-title", "color:#777;margin-left:5px;")
+ style(
+ ".user-title",
+ "font-size:13px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;text-decoration:none;margin-left:5px;color: #999;",
+ )
+ style(".post-wrapper", "margin-bottom:25px;")
+ style(".user-avatar", "vertical-align:top;width:55px;")
+ style(".user-avatar img", nil, width: "45", height: "45")
+ style("hr", "background-color: #ddd; height: 1px; border: 1px;")
+ style(".rtl", "direction: rtl;")
+ style("div.body", "padding-top:5px;")
+ style(".whisper div.body", "font-style: italic; color: #9c9c9c;")
+ style(".lightbox-wrapper .meta", "display: none")
+ style("div.undecorated-link-footer a", "font-weight: normal;")
+ style(
+ ".mso-accent-link",
+ "mso-border-alt: 6px solid #{SiteSetting.email_accent_bg_color}; background-color: #{SiteSetting.email_accent_bg_color};",
+ )
+ style(
+ ".reply-above-line",
+ "font-size: 10px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;color: #b5b5b5;padding: 5px 0px 20px;border-top: 1px dotted #ddd;",
+ )
onebox_styles
plugin_styles
dark_mode_styles
- style('.post-excerpt img', "max-width: 50%; max-height: #{MAX_IMAGE_DIMENSION}px;")
+ style(".post-excerpt img", "max-width: 50%; max-height: #{MAX_IMAGE_DIMENSION}px;")
format_custom
end
def format_custom
- custom_styles.each do |selector, value|
- style(selector, value)
- end
+ custom_styles.each { |selector, value| style(selector, value) }
end
# this method is reserved for styles specific to plugin
@@ -258,33 +315,46 @@ module Email
end
def inline_secure_images(attachments, attachments_index)
- stripped_media = @fragment.css('[data-stripped-secure-media], [data-stripped-secure-upload]')
+ stripped_media = @fragment.css("[data-stripped-secure-media], [data-stripped-secure-upload]")
upload_shas = {}
stripped_media.each do |div|
- url = div['data-stripped-secure-media'] || div['data-stripped-secure-upload']
+ url = div["data-stripped-secure-media"] || div["data-stripped-secure-upload"]
filename = File.basename(url)
filename_bare = filename.gsub(File.extname(filename), "")
- sha1 = filename_bare.partition('_').first
+ sha1 = filename_bare.partition("_").first
upload_shas[url] = sha1
end
uploads = Upload.select(:original_filename, :sha1).where(sha1: upload_shas.values)
stripped_media.each do |div|
- upload = uploads.find do |upl|
- upl.sha1 == (upload_shas[div['data-stripped-secure-media']] || upload_shas[div['data-stripped-secure-upload']])
- end
+ upload =
+ uploads.find do |upl|
+ upl.sha1 ==
+ (
+ upload_shas[div["data-stripped-secure-media"]] ||
+ upload_shas[div["data-stripped-secure-upload"]]
+ )
+ end
next if !upload
if attachments[attachments_index[upload.sha1]]
url = attachments[attachments_index[upload.sha1]].url
- onebox_type = div['data-onebox-type']
- style = if onebox_type
- onebox_style = onebox_type == "avatar-inline" ? ONEBOX_INLINE_AVATAR_STYLE : ONEBOX_IMAGE_THUMBNAIL_STYLE
- "#{onebox_style} #{ONEBOX_IMAGE_BASE_STYLE}"
- else
- calculate_width_and_height_style(div)
- end
+ onebox_type = div["data-onebox-type"]
+ style =
+ if onebox_type
+ onebox_style =
+ (
+ if onebox_type == "avatar-inline"
+ ONEBOX_INLINE_AVATAR_STYLE
+ else
+ ONEBOX_IMAGE_THUMBNAIL_STYLE
+ end
+ )
+ "#{onebox_style} #{ONEBOX_IMAGE_BASE_STYLE}"
+ else
+ calculate_width_and_height_style(div)
+ end
div.add_next_sibling(<<~HTML)
<img src="#{url}" data-embedded-secure-image="true" style="#{style}" />
@@ -309,39 +379,45 @@ module Email
end
def strip_avatars_and_emojis
- @fragment.search('img').each do |img|
- next unless img['src']
-
- if img['src'][/_avatar/]
- img.parent['style'] = "vertical-align: top;" if img.parent&.name == 'td'
- img.remove
- end
+ @fragment
+ .search("img")
+ .each do |img|
+ next unless img["src"]
+
+ if img["src"][/_avatar/]
+ img.parent["style"] = "vertical-align: top;" if img.parent&.name == "td"
+ img.remove
+ end
- if img['title'] && img['src'][/\/_?emoji\//]
- img.add_previous_sibling(img['title'] || "emoji")
- img.remove
+ if img["title"] && img["src"][%r{/_?emoji/}]
+ img.add_previous_sibling(img["title"] || "emoji")
+ img.remove
+ end
end
- end
end
def decorate_hashtags
- @fragment.search(".hashtag-cooked").each do |hashtag|
- hashtag.children.each(&:remove)
- hashtag.add_child(<<~HTML)
+ @fragment
+ .search(".hashtag-cooked")
+ .each do |hashtag|
+ hashtag.children.each(&:remove)
+ hashtag.add_child(<<~HTML)
<span>##{hashtag["data-slug"]}</span>
HTML
- end
+ end
end
def make_all_links_absolute
site_uri = URI(Discourse.base_url)
- @fragment.css("a").each do |link|
- begin
- link["href"] = "#{site_uri}#{link['href']}" unless URI(link["href"].to_s).host.present?
- rescue URI::Error
- # leave it
+ @fragment
+ .css("a")
+ .each do |link|
+ begin
+ link["href"] = "#{site_uri}#{link["href"]}" unless URI(link["href"].to_s).host.present?
+ rescue URI::Error
+ # leave it
+ end
end
- end
end
private
@@ -350,8 +426,16 @@ module Email
# When we ship the email template and its styles we strip all css classes so to give our
# dark mode styles we are including in the template a selector we add a data-attr of 'dm=value' to
# the appropriate place
- style(".digest-header, .digest-topic, .digest-topic-title-wrapper, .digest-topic-stats, .popular-post-excerpt", nil, dm: "header")
- style(".digest-content, .header-popular-posts, .spacer, .popular-post-spacer, .popular-post-meta, .digest-new-header, .digest-new-topic, .body", nil, dm: "body")
+ style(
+ ".digest-header, .digest-topic, .digest-topic-title-wrapper, .digest-topic-stats, .popular-post-excerpt",
+ nil,
+ dm: "header",
+ )
+ style(
+ ".digest-content, .header-popular-posts, .spacer, .popular-post-spacer, .popular-post-meta, .digest-new-header, .digest-new-topic, .body",
+ nil,
+ dm: "body",
+ )
style(".with-accent-colors, .digest-content-header", nil, dm: "body_primary")
style(".digest-topic-body", nil, dm: "topic-body")
style(".summary-footer", nil, dm: "text-color")
@@ -363,18 +447,19 @@ module Email
host = forum_uri.host
scheme = forum_uri.scheme
- @fragment.css('[href]').each do |element|
- href = element['href']
- if href.start_with?("\/\/#{host}")
- element['href'] = "#{scheme}:#{href}"
+ @fragment
+ .css("[href]")
+ .each do |element|
+ href = element["href"]
+ element["href"] = "#{scheme}:#{href}" if href.start_with?("\/\/#{host}")
end
- end
end
def calculate_width_and_height_style(div)
- width = div['data-width']
- height = div['data-height']
- if width.present? && height.present? && height.to_i < MAX_IMAGE_DIMENSION && width.to_i < MAX_IMAGE_DIMENSION
+ width = div["data-width"]
+ height = div["data-height"]
+ if width.present? && height.present? && height.to_i < MAX_IMAGE_DIMENSION &&
+ width.to_i < MAX_IMAGE_DIMENSION
"width: #{width}px; height: #{height}px;"
else
"max-width: 50%; max-height: #{MAX_IMAGE_DIMENSION}px;"
@@ -386,59 +471,68 @@ module Email
# notification template but that may not catch everything
PrettyText.strip_secure_uploads(@fragment)
- style('div.secure-upload-notice', 'border: 5px solid #e9e9e9; padding: 5px; display: inline-block;')
- style('div.secure-upload-notice a', "color: #{SiteSetting.email_link_color}")
+ style(
+ "div.secure-upload-notice",
+ "border: 5px solid #e9e9e9; padding: 5px; display: inline-block;",
+ )
+ style("div.secure-upload-notice a", "color: #{SiteSetting.email_link_color}")
end
def correct_first_body_margin
- @fragment.css('div.body p').each do |element|
- element['style'] = "margin-top:0; border: 0;"
- end
+ @fragment.css("div.body p").each { |element| element["style"] = "margin-top:0; border: 0;" }
end
def correct_footer_style
- @fragment.css('.footer').each do |element|
- element['style'] = "color:#666;"
- element.css('a').each do |inner|
- inner['style'] = "color:#666;"
+ @fragment
+ .css(".footer")
+ .each do |element|
+ element["style"] = "color:#666;"
+ element.css("a").each { |inner| inner["style"] = "color:#666;" }
end
- end
end
def correct_footer_style_highlight_first
footernum = 0
- @fragment.css('.footer.highlight').each do |element|
- linknum = 0
- element.css('a').each do |inner|
- # we want the first footer link to be specially highlighted as IMPORTANT
- if footernum == (0) && linknum == (0)
- bg_color = SiteSetting.email_accent_bg_color
- inner['style'] = "background-color: #{bg_color}; color: #{SiteSetting.email_accent_fg_color}; border-top: 4px solid #{bg_color}; border-right: 6px solid #{bg_color}; border-bottom: 4px solid #{bg_color}; border-left: 6px solid #{bg_color}; display: inline-block; font-weight: bold;"
- end
+ @fragment
+ .css(".footer.highlight")
+ .each do |element|
+ linknum = 0
+ element
+ .css("a")
+ .each do |inner|
+ # we want the first footer link to be specially highlighted as IMPORTANT
+ if footernum == (0) && linknum == (0)
+ bg_color = SiteSetting.email_accent_bg_color
+ inner[
+ "style"
+ ] = "background-color: #{bg_color}; color: #{SiteSetting.email_accent_fg_color}; border-top: 4px solid #{bg_color}; border-right: 6px solid #{bg_color}; border-bottom: 4px solid #{bg_color}; border-left: 6px solid #{bg_color}; display: inline-block; font-weight: bold;"
+ end
+ return
+ end
return
end
- return
- end
end
def strip_classes_and_ids
- @fragment.css('*').each do |element|
- element.delete('class')
- element.delete('id')
- end
+ @fragment
+ .css("*")
+ .each do |element|
+ element.delete("class")
+ element.delete("id")
+ end
end
def reset_tables
- style('table', nil, cellspacing: '0', cellpadding: '0', border: '0')
+ style("table", nil, cellspacing: "0", cellpadding: "0", border: "0")
end
def style(selector, style, attribs = {})
- @fragment.css(selector).each do |element|
- add_styles(element, style) if style
- attribs.each do |k, v|
- element[k] = v
+ @fragment
+ .css(selector)
+ .each do |element|
+ add_styles(element, style) if style
+ attribs.each { |k, v| element[k] = v }
end
- end
end
end
end
diff --git a/lib/email/validator.rb b/lib/email/validator.rb
index 2795055a93e..764bb7e13c2 100644
--- a/lib/email/validator.rb
+++ b/lib/email/validator.rb
@@ -10,7 +10,7 @@ module Email
end
def self.ensure_valid_address_lists!(mail)
- [:to, :cc, :bcc].each do |field|
+ %i[to cc bcc].each do |field|
addresses = mail[field]
if addresses&.errors.present?
@@ -21,7 +21,8 @@ module Email
def self.ensure_valid_date!(mail)
if mail.date.nil?
- raise Email::Receiver::InvalidPost, I18n.t("system_messages.email_reject_invalid_post_specified.date_invalid")
+ raise Email::Receiver::InvalidPost,
+ I18n.t("system_messages.email_reject_invalid_post_specified.date_invalid")
end
end
end
diff --git a/lib/email_backup_token.rb b/lib/email_backup_token.rb
index 098f7c7e073..0aef08ca542 100644
--- a/lib/email_backup_token.rb
+++ b/lib/email_backup_token.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class EmailBackupToken
-
def self.key(user_id)
"email-backup-token:#{user_id}"
end
diff --git a/lib/email_controller_helper/base_email_unsubscriber.rb b/lib/email_controller_helper/base_email_unsubscriber.rb
index b04560040ca..46267cb36e7 100644
--- a/lib/email_controller_helper/base_email_unsubscriber.rb
+++ b/lib/email_controller_helper/base_email_unsubscriber.rb
@@ -20,7 +20,7 @@ module EmailControllerHelper
controller.instance_variable_set(
:@unsubscribed_from_all,
- key_owner.user_option.unsubscribed_from_all?
+ key_owner.user_option.unsubscribed_from_all?,
)
end
@@ -38,10 +38,12 @@ module EmailControllerHelper
end
if params[:unsubscribe_all]
- key_owner.user_option.update_columns(email_digests: false,
- email_level: UserOption.email_level_types[:never],
- email_messages_level: UserOption.email_level_types[:never],
- mailing_list_mode: false)
+ key_owner.user_option.update_columns(
+ email_digests: false,
+ email_level: UserOption.email_level_types[:never],
+ email_messages_level: UserOption.email_level_types[:never],
+ mailing_list_mode: false,
+ )
updated = true
end
diff --git a/lib/email_controller_helper/digest_email_unsubscriber.rb b/lib/email_controller_helper/digest_email_unsubscriber.rb
index 7291d01258b..b96e77402c5 100644
--- a/lib/email_controller_helper/digest_email_unsubscriber.rb
+++ b/lib/email_controller_helper/digest_email_unsubscriber.rb
@@ -12,22 +12,34 @@ module EmailControllerHelper
never = frequencies.delete_at(0)
allowed_frequencies = %w[never weekly every_month every_six_months]
- result = frequencies.reduce(frequencies: [], current: nil, selected: nil, take_next: false) do |memo, v|
- memo[:current] = v[:name] if v[:value] == frequency_in_minutes && email_digests
- next(memo) unless allowed_frequencies.include?(v[:name])
-
- memo.tap do |m|
- m[:selected] = v[:value] if m[:take_next] && email_digests
- m[:frequencies] << [I18n.t("unsubscribe.digest_frequency.#{v[:name]}"), v[:value]]
- m[:take_next] = !m[:take_next] && m[:current]
+ result =
+ frequencies.reduce(
+ frequencies: [],
+ current: nil,
+ selected: nil,
+ take_next: false,
+ ) do |memo, v|
+ memo[:current] = v[:name] if v[:value] == frequency_in_minutes && email_digests
+ next(memo) unless allowed_frequencies.include?(v[:name])
+
+ memo.tap do |m|
+ m[:selected] = v[:value] if m[:take_next] && email_digests
+ m[:frequencies] << [I18n.t("unsubscribe.digest_frequency.#{v[:name]}"), v[:value]]
+ m[:take_next] = !m[:take_next] && m[:current]
+ end
end
- end
- digest_frequencies = result.slice(:frequencies, :current, :selected).tap do |r|
- r[:frequencies] << [I18n.t("unsubscribe.digest_frequency.#{never[:name]}"), never[:value]]
- r[:selected] ||= never[:value]
- r[:current] ||= never[:name]
- end
+ digest_frequencies =
+ result
+ .slice(:frequencies, :current, :selected)
+ .tap do |r|
+ r[:frequencies] << [
+ I18n.t("unsubscribe.digest_frequency.#{never[:name]}"),
+ never[:value],
+ ]
+ r[:selected] ||= never[:value]
+ r[:current] ||= never[:name]
+ end
controller.instance_variable_set(:@digest_frequencies, digest_frequencies)
end
@@ -40,7 +52,7 @@ module EmailControllerHelper
unsubscribe_key.user.user_option.update_columns(
digest_after_minutes: digest_frequency,
- email_digests: digest_frequency.positive?
+ email_digests: digest_frequency.positive?,
)
updated = true
end
diff --git a/lib/email_controller_helper/topic_email_unsubscriber.rb b/lib/email_controller_helper/topic_email_unsubscriber.rb
index 6265853f541..eda37b7d667 100644
--- a/lib/email_controller_helper/topic_email_unsubscriber.rb
+++ b/lib/email_controller_helper/topic_email_unsubscriber.rb
@@ -11,16 +11,25 @@ module EmailControllerHelper
controller.instance_variable_set(:@topic, topic)
controller.instance_variable_set(
:@watching_topic,
- TopicUser.exists?(user: key_owner, notification_level: watching, topic_id: topic.id)
+ TopicUser.exists?(user: key_owner, notification_level: watching, topic_id: topic.id),
)
return if topic.category_id.blank?
- return if !CategoryUser.exists?(user: key_owner, notification_level: CategoryUser.watching_levels, category_id: topic.category_id)
+ if !CategoryUser.exists?(
+ user: key_owner,
+ notification_level: CategoryUser.watching_levels,
+ category_id: topic.category_id,
+ )
+ return
+ end
controller.instance_variable_set(
:@watched_count,
- TopicUser.joins(:topic)
- .where(user: key_owner, notification_level: watching).where(topics: { category_id: topic.category_id }).count
+ TopicUser
+ .joins(:topic)
+ .where(user: key_owner, notification_level: watching)
+ .where(topics: { category_id: topic.category_id })
+ .count,
)
end
@@ -31,27 +40,33 @@ module EmailControllerHelper
return updated if topic.nil?
if params[:unwatch_topic]
- TopicUser.where(topic_id: topic.id, user_id: key_owner.id)
- .update_all(notification_level: TopicUser.notification_levels[:tracking])
+ TopicUser.where(topic_id: topic.id, user_id: key_owner.id).update_all(
+ notification_level: TopicUser.notification_levels[:tracking],
+ )
updated = true
end
if params[:unwatch_category] && topic.category_id
- TopicUser.joins(:topic)
+ TopicUser
+ .joins(:topic)
.where(user: key_owner, notification_level: TopicUser.notification_levels[:watching])
.where(topics: { category_id: topic.category_id })
.update_all(notification_level: TopicUser.notification_levels[:tracking])
- CategoryUser
- .where(user_id: key_owner.id, category_id: topic.category_id, notification_level: CategoryUser.watching_levels)
- .destroy_all
+ CategoryUser.where(
+ user_id: key_owner.id,
+ category_id: topic.category_id,
+ notification_level: CategoryUser.watching_levels,
+ ).destroy_all
updated = true
end
if params[:mute_topic]
- TopicUser.where(topic_id: topic.id, user_id: key_owner.id).update_all(notification_level: TopicUser.notification_levels[:muted])
+ TopicUser.where(topic_id: topic.id, user_id: key_owner.id).update_all(
+ notification_level: TopicUser.notification_levels[:muted],
+ )
updated = true
end
diff --git a/lib/email_cook.rb b/lib/email_cook.rb
index 89b59891f12..2c76e1f2ff2 100644
--- a/lib/email_cook.rb
+++ b/lib/email_cook.rb
@@ -2,9 +2,9 @@
# A very simple formatter for imported emails
class EmailCook
-
def self.raw_regexp
- @raw_regexp ||= /^\[plaintext\]$\n(.*)\n^\[\/plaintext\]$(?:\s^\[attachments\]$\n(.*)\n^\[\/attachments\]$)?(?:\s^\[elided\]$\n(.*)\n^\[\/elided\]$)?/m
+ @raw_regexp ||=
+ %r{^\[plaintext\]$\n(.*)\n^\[/plaintext\]$(?:\s^\[attachments\]$\n(.*)\n^\[/attachments\]$)?(?:\s^\[elided\]$\n(.*)\n^\[/elided\]$)?}m
end
def initialize(raw)
@@ -22,7 +22,7 @@ class EmailCook
def link_string!(line, unescaped_line)
unescaped_line = unescaped_line.strip
line.gsub!(/\S+/) do |str|
- if str.match?(/^(https?:\/\/)[\S]+$/i)
+ if str.match?(%r{^(https?://)[\S]+$}i)
begin
url = URI.parse(str).to_s
if unescaped_line == url
@@ -52,7 +52,7 @@ class EmailCook
if line =~ /^\s*>/
in_quote = true
- line.sub!(/^[\s>]*/, '')
+ line.sub!(/^[\s>]*/, "")
unescaped_line = line
line = CGI.escapeHTML(line)
@@ -64,7 +64,6 @@ class EmailCook
quote_buffer = ""
in_quote = false
else
-
sz = line.size
unescaped_line = line
@@ -72,9 +71,7 @@ class EmailCook
link_string!(line, unescaped_line)
if sz < 60
- if in_text && line == "\n"
- result << "<br>"
- end
+ result << "<br>" if in_text && line == "\n"
result << line
result << "<br>"
@@ -86,11 +83,9 @@ class EmailCook
end
end
- if in_quote && quote_buffer.present?
- add_quote(result, quote_buffer)
- end
+ add_quote(result, quote_buffer) if in_quote && quote_buffer.present?
- result.gsub!(/(<br>\n*){3,10}/, '<br><br>')
+ result.gsub!(/(<br>\n*){3,10}/, "<br><br>")
result
end
@@ -98,10 +93,9 @@ class EmailCook
# fallback to PrettyText if we failed to detect a body
return PrettyText.cook(@raw, opts) if @body.nil?
- result = htmlify(@body)
+ result = htmlify(@body)
result << "\n<br>" << @attachment_html if @attachment_html.present?
result << "\n<br><br>" << Email::Receiver.elided_html(htmlify(@elided)) if @elided.present?
result
end
-
end
diff --git a/lib/email_updater.rb b/lib/email_updater.rb
index 8f5fb292e2b..c25c2382e86 100644
--- a/lib/email_updater.rb
+++ b/lib/email_updater.rb
@@ -26,8 +26,8 @@ class EmailUpdater
if SiteSetting.hide_email_address_taken
Jobs.enqueue(:critical_user_email, type: "account_exists", user_id: existing_user.id)
else
- error_message = +'change_email.error'
- error_message << '_staged' if existing_user.staged?
+ error_message = +"change_email.error"
+ error_message << "_staged" if existing_user.staged?
errors.add(:base, I18n.t(error_message))
end
end
@@ -57,19 +57,23 @@ class EmailUpdater
@change_req.new_email = email
end
- if @change_req.change_state.blank? || @change_req.change_state == EmailChangeRequest.states[:complete]
- @change_req.change_state = if SiteSetting.require_change_email_confirmation || @user.staff?
- EmailChangeRequest.states[:authorizing_old]
- else
- EmailChangeRequest.states[:authorizing_new]
- end
+ if @change_req.change_state.blank? ||
+ @change_req.change_state == EmailChangeRequest.states[:complete]
+ @change_req.change_state =
+ if SiteSetting.require_change_email_confirmation || @user.staff?
+ EmailChangeRequest.states[:authorizing_old]
+ else
+ EmailChangeRequest.states[:authorizing_new]
+ end
end
if @change_req.change_state == EmailChangeRequest.states[:authorizing_old]
- @change_req.old_email_token = @user.email_tokens.create!(email: @user.email, scope: EmailToken.scopes[:email_update])
+ @change_req.old_email_token =
+ @user.email_tokens.create!(email: @user.email, scope: EmailToken.scopes[:email_update])
send_email(add ? "confirm_old_email_add" : "confirm_old_email", @change_req.old_email_token)
elsif @change_req.change_state == EmailChangeRequest.states[:authorizing_new]
- @change_req.new_email_token = @user.email_tokens.create!(email: email, scope: EmailToken.scopes[:email_update])
+ @change_req.new_email_token =
+ @user.email_tokens.create!(email: email, scope: EmailToken.scopes[:email_update])
send_email("confirm_new_email", @change_req.new_email_token)
end
@@ -83,7 +87,7 @@ class EmailUpdater
User.transaction do
email_token = EmailToken.confirmable(token, scope: EmailToken.scopes[:email_update])
if email_token.blank?
- errors.add(:base, I18n.t('change_email.already_done'))
+ errors.add(:base, I18n.t("change_email.already_done"))
confirm_result = :error
next
end
@@ -91,15 +95,24 @@ class EmailUpdater
email_token.update!(confirmed: true)
@user = email_token.user
- @change_req = @user.email_change_requests
- .where('old_email_token_id = :token_id OR new_email_token_id = :token_id', token_id: email_token.id)
- .first
+ @change_req =
+ @user
+ .email_change_requests
+ .where(
+ "old_email_token_id = :token_id OR new_email_token_id = :token_id",
+ token_id: email_token.id,
+ )
+ .first
case @change_req.try(:change_state)
when EmailChangeRequest.states[:authorizing_old]
@change_req.update!(
change_state: EmailChangeRequest.states[:authorizing_new],
- new_email_token: @user.email_tokens.create!(email: @change_req.new_email, scope: EmailToken.scopes[:email_update])
+ new_email_token:
+ @user.email_tokens.create!(
+ email: @change_req.new_email,
+ scope: EmailToken.scopes[:email_update],
+ ),
)
send_email("confirm_new_email", @change_req.new_email_token)
confirm_result = :authorizing_new
diff --git a/lib/ember_cli.rb b/lib/ember_cli.rb
index fd3892918b5..00c65610bad 100644
--- a/lib/ember_cli.rb
+++ b/lib/ember_cli.rb
@@ -2,37 +2,47 @@
module EmberCli
def self.assets
- @assets ||= begin
- assets = %w(
- discourse.js
- admin.js
- wizard.js
- ember_jquery.js
- markdown-it-bundle.js
- start-discourse.js
- vendor.js
- )
- assets += Dir.glob("app/assets/javascripts/discourse/scripts/*.js").map { |f| File.basename(f) }
+ @assets ||=
+ begin
+ assets = %w[
+ discourse.js
+ admin.js
+ wizard.js
+ ember_jquery.js
+ markdown-it-bundle.js
+ start-discourse.js
+ vendor.js
+ ]
+ assets +=
+ Dir.glob("app/assets/javascripts/discourse/scripts/*.js").map { |f| File.basename(f) }
- Discourse.find_plugin_js_assets(include_disabled: true).each do |file|
- next if file.ends_with?("_extra") # these are still handled by sprockets
- assets << "#{file}.js"
- end
+ Discourse
+ .find_plugin_js_assets(include_disabled: true)
+ .each do |file|
+ next if file.ends_with?("_extra") # these are still handled by sprockets
+ assets << "#{file}.js"
+ end
- assets
- end
+ assets
+ end
end
def self.script_chunks
- return @@chunk_infos if defined? @@chunk_infos
+ return @@chunk_infos if defined?(@@chunk_infos)
- raw_chunk_infos = JSON.parse(File.read("#{Rails.configuration.root}/app/assets/javascripts/discourse/dist/chunks.json"))
+ raw_chunk_infos =
+ JSON.parse(
+ File.read("#{Rails.configuration.root}/app/assets/javascripts/discourse/dist/chunks.json"),
+ )
- chunk_infos = raw_chunk_infos["scripts"].map do |info|
- logical_name = info["afterFile"][/\Aassets\/(.*)\.js\z/, 1]
- chunks = info["scriptChunks"].map { |filename| filename[/\Aassets\/(.*)\.js\z/, 1] }
- [logical_name, chunks]
- end.to_h
+ chunk_infos =
+ raw_chunk_infos["scripts"]
+ .map do |info|
+ logical_name = info["afterFile"][%r{\Aassets/(.*)\.js\z}, 1]
+ chunks = info["scriptChunks"].map { |filename| filename[%r{\Aassets/(.*)\.js\z}, 1] }
+ [logical_name, chunks]
+ end
+ .to_h
@@chunk_infos = chunk_infos if Rails.env.production?
chunk_infos
@@ -45,9 +55,11 @@ module EmberCli
end
def self.ember_version
- @version ||= begin
- ember_source_package_raw = File.read("#{Rails.root}/app/assets/javascripts/node_modules/ember-source/package.json")
- JSON.parse(ember_source_package_raw)["version"]
- end
+ @version ||=
+ begin
+ ember_source_package_raw =
+ File.read("#{Rails.root}/app/assets/javascripts/node_modules/ember-source/package.json")
+ JSON.parse(ember_source_package_raw)["version"]
+ end
end
end
diff --git a/lib/encodings.rb b/lib/encodings.rb
index 8bf0c7c72be..b8e68f24e57 100644
--- a/lib/encodings.rb
+++ b/lib/encodings.rb
@@ -1,12 +1,12 @@
# frozen_string_literal: true
-require 'rchardet'
+require "rchardet"
module Encodings
def self.to_utf8(string)
result = CharDet.detect(string)
- encoded_string = try_utf8(string, result['encoding']) if result && result['encoding']
+ encoded_string = try_utf8(string, result["encoding"]) if result && result["encoding"]
encoded_string = force_utf8(string) if encoded_string.nil?
encoded_string
end
@@ -15,21 +15,18 @@ module Encodings
encoded = string.encode(Encoding::UTF_8, source_encoding)
encoded&.valid_encoding? ? delete_bom!(encoded) : nil
rescue Encoding::InvalidByteSequenceError,
- Encoding::UndefinedConversionError,
- Encoding::ConverterNotFoundError
+ Encoding::UndefinedConversionError,
+ Encoding::ConverterNotFoundError
nil
end
def self.force_utf8(string)
- encoded_string = string.encode(Encoding::UTF_8,
- undef: :replace,
- invalid: :replace,
- replace: '')
+ encoded_string = string.encode(Encoding::UTF_8, undef: :replace, invalid: :replace, replace: "")
delete_bom!(encoded_string)
end
def self.delete_bom!(string)
- string.sub!(/\A\xEF\xBB\xBF/, '') unless string.blank?
+ string.sub!(/\A\xEF\xBB\xBF/, "") unless string.blank?
string
end
end
diff --git a/lib/enum.rb b/lib/enum.rb
index d4401219002..9c87135c723 100644
--- a/lib/enum.rb
+++ b/lib/enum.rb
@@ -43,15 +43,11 @@ class Enum < Hash
# Public: Create a subset of enum, only include specified keys.
def only(*keys)
- dup.tap do |d|
- d.keep_if { |k| keys.include?(k) }
- end
+ dup.tap { |d| d.keep_if { |k| keys.include?(k) } }
end
# Public: Create a subset of enum, preserve all items but specified ones.
def except(*keys)
- dup.tap do |d|
- d.delete_if { |k| keys.include?(k) }
- end
+ dup.tap { |d| d.delete_if { |k| keys.include?(k) } }
end
end
diff --git a/lib/excerpt_parser.rb b/lib/excerpt_parser.rb
index 2a4fbc8e3b1..f01499e9343 100644
--- a/lib/excerpt_parser.rb
+++ b/lib/excerpt_parser.rb
@@ -28,15 +28,14 @@ class ExcerptParser < Nokogiri::XML::SAX::Document
end
def self.get_excerpt(html, length, options)
- html ||= ''
- length = html.length if html.include?('excerpt') && CUSTOM_EXCERPT_REGEX === html
+ html ||= ""
+ length = html.length if html.include?("excerpt") && CUSTOM_EXCERPT_REGEX === html
me = self.new(length, options)
parser = Nokogiri::HTML::SAX::Parser.new(me)
- catch(:done) do
- parser.parse(html)
- end
+ catch(:done) { parser.parse(html) }
excerpt = me.excerpt.strip
- excerpt = excerpt.gsub(/\s*\n+\s*/, "\n\n") if options[:keep_onebox_source] || options[:keep_onebox_body]
+ excerpt = excerpt.gsub(/\s*\n+\s*/, "\n\n") if options[:keep_onebox_source] ||
+ options[:keep_onebox_body]
excerpt = CGI.unescapeHTML(excerpt) if options[:text_entities] == true
excerpt
end
@@ -53,8 +52,12 @@ class ExcerptParser < Nokogiri::XML::SAX::Document
end
def include_tag(name, attributes)
- characters("<#{name} #{attributes.map { |k, v| "#{k}=\"#{escape_attribute(v)}\"" }.join(' ')}>",
- truncate: false, count_it: false, encode: false)
+ characters(
+ "<#{name} #{attributes.map { |k, v| "#{k}=\"#{escape_attribute(v)}\"" }.join(" ")}>",
+ truncate: false,
+ count_it: false,
+ encode: false,
+ )
end
def start_element(name, attributes = [])
@@ -62,7 +65,7 @@ class ExcerptParser < Nokogiri::XML::SAX::Document
when "img"
attributes = Hash[*attributes.flatten]
- if attributes["class"]&.include?('emoji')
+ if attributes["class"]&.include?("emoji")
if @remap_emoji
title = (attributes["alt"] || "").gsub(":", "")
title = Emoji.lookup_unicode(title) || attributes["alt"]
@@ -83,68 +86,53 @@ class ExcerptParser < Nokogiri::XML::SAX::Document
elsif !attributes["title"].blank?
characters("[#{attributes["title"]}]")
else
- characters("[#{I18n.t 'excerpt_image'}]")
+ characters("[#{I18n.t "excerpt_image"}]")
end
- characters("(#{attributes['src']})") if @markdown_images
+ characters("(#{attributes["src"]})") if @markdown_images
end
-
when "a"
unless @strip_links
include_tag(name, attributes)
@in_a = true
end
-
when "aside"
attributes = Hash[*attributes.flatten]
- unless (@keep_onebox_source || @keep_onebox_body) && attributes['class']&.include?('onebox')
+ unless (@keep_onebox_source || @keep_onebox_body) && attributes["class"]&.include?("onebox")
@in_quote = true
end
- if attributes['class']&.include?('quote')
- if @keep_quotes || (@keep_onebox_body && attributes['data-topic'].present?)
+ if attributes["class"]&.include?("quote")
+ if @keep_quotes || (@keep_onebox_body && attributes["data-topic"].present?)
@in_quote = false
end
end
-
- when 'article'
- if attributes.include?(['class', 'onebox-body'])
- @in_quote = !@keep_onebox_body
- end
-
- when 'header'
- if attributes.include?(['class', 'source'])
- @in_quote = !@keep_onebox_source
- end
-
+ when "article"
+ @in_quote = !@keep_onebox_body if attributes.include?(%w[class onebox-body])
+ when "header"
+ @in_quote = !@keep_onebox_source if attributes.include?(%w[class source])
when "div", "span"
- if attributes.include?(["class", "excerpt"])
+ if attributes.include?(%w[class excerpt])
@excerpt = +""
@current_length = 0
@start_excerpt = true
end
-
when "details"
@detail_contents = +"" if @in_details_depth == 0
@in_details_depth += 1
-
when "summary"
if @in_details_depth == 1 && !@in_summary
@summary_contents = +""
@in_summary = true
end
-
when "svg"
attributes = Hash[*attributes.flatten]
if attributes["class"]&.include?("d-icon") && @keep_svg
include_tag(name, attributes)
@in_svg = true
end
-
when "use"
- if @in_svg && @keep_svg
- include_tag(name, attributes)
- end
+ include_tag(name, attributes) if @in_svg && @keep_svg
end
end
@@ -170,20 +158,22 @@ class ExcerptParser < Nokogiri::XML::SAX::Document
@detail_contents = clean(@detail_contents)
if @current_length + @summary_contents.length >= @length
- characters(@summary_contents,
- encode: false,
- before_string: "<details class='disabled'><summary>",
- after_string: "</summary></details>")
+ characters(
+ @summary_contents,
+ encode: false,
+ before_string: "<details class='disabled'><summary>",
+ after_string: "</summary></details>",
+ )
else
- characters(@summary_contents,
- truncate: false,
- encode: false,
- before_string: "<details><summary>",
- after_string: "</summary>")
-
- characters(@detail_contents,
- encode: false,
- after_string: "</details>")
+ characters(
+ @summary_contents,
+ truncate: false,
+ encode: false,
+ before_string: "<details><summary>",
+ after_string: "</summary>",
+ )
+
+ characters(@detail_contents, encode: false, after_string: "</details>")
end
end
when "summary"
@@ -202,7 +192,14 @@ class ExcerptParser < Nokogiri::XML::SAX::Document
ERB::Util.html_escape(str.strip)
end
- def characters(string, truncate: true, count_it: true, encode: true, before_string: nil, after_string: nil)
+ def characters(
+ string,
+ truncate: true,
+ count_it: true,
+ encode: true,
+ before_string: nil,
+ after_string: nil
+ )
return if @in_quote
# we call length on this so might as well ensure we have a string
diff --git a/lib/external_upload_helpers.rb b/lib/external_upload_helpers.rb
index 5b0e43f5ab3..3ac4cea5bcc 100644
--- a/lib/external_upload_helpers.rb
+++ b/lib/external_upload_helpers.rb
@@ -5,35 +5,41 @@
module ExternalUploadHelpers
extend ActiveSupport::Concern
- class ExternalUploadValidationError < StandardError; end
+ class ExternalUploadValidationError < StandardError
+ end
PRESIGNED_PUT_RATE_LIMIT_PER_MINUTE = 10
CREATE_MULTIPART_RATE_LIMIT_PER_MINUTE = 10
COMPLETE_MULTIPART_RATE_LIMIT_PER_MINUTE = 10
included do
- before_action :external_store_check, only: [
- :generate_presigned_put,
- :complete_external_upload,
- :create_multipart,
- :batch_presign_multipart_parts,
- :abort_multipart,
- :complete_multipart
- ]
- before_action :direct_s3_uploads_check, only: [
- :generate_presigned_put,
- :complete_external_upload,
- :create_multipart,
- :batch_presign_multipart_parts,
- :abort_multipart,
- :complete_multipart
- ]
- before_action :can_upload_external?, only: [:create_multipart, :generate_presigned_put]
+ before_action :external_store_check,
+ only: %i[
+ generate_presigned_put
+ complete_external_upload
+ create_multipart
+ batch_presign_multipart_parts
+ abort_multipart
+ complete_multipart
+ ]
+ before_action :direct_s3_uploads_check,
+ only: %i[
+ generate_presigned_put
+ complete_external_upload
+ create_multipart
+ batch_presign_multipart_parts
+ abort_multipart
+ complete_multipart
+ ]
+ before_action :can_upload_external?, only: %i[create_multipart generate_presigned_put]
end
def generate_presigned_put
RateLimiter.new(
- current_user, "generate-presigned-put-upload-stub", ExternalUploadHelpers::PRESIGNED_PUT_RATE_LIMIT_PER_MINUTE, 1.minute
+ current_user,
+ "generate-presigned-put-upload-stub",
+ ExternalUploadHelpers::PRESIGNED_PUT_RATE_LIMIT_PER_MINUTE,
+ 1.minute,
).performed!
file_name = params.require(:file_name)
@@ -44,28 +50,28 @@ module ExternalUploadHelpers
validate_before_create_direct_upload(
file_name: file_name,
file_size: file_size,
- upload_type: type
+ upload_type: type,
)
rescue ExternalUploadValidationError => err
return render_json_error(err.message, status: 422)
end
- external_upload_data = ExternalUploadManager.create_direct_upload(
- current_user: current_user,
- file_name: file_name,
- file_size: file_size,
- upload_type: type,
- metadata: parse_allowed_metadata(params[:metadata])
- )
+ external_upload_data =
+ ExternalUploadManager.create_direct_upload(
+ current_user: current_user,
+ file_name: file_name,
+ file_size: file_size,
+ upload_type: type,
+ metadata: parse_allowed_metadata(params[:metadata]),
+ )
render json: external_upload_data
end
def complete_external_upload
unique_identifier = params.require(:unique_identifier)
- external_upload_stub = ExternalUploadStub.find_by(
- unique_identifier: unique_identifier, created_by: current_user
- )
+ external_upload_stub =
+ ExternalUploadStub.find_by(unique_identifier: unique_identifier, created_by: current_user)
return render_404 if external_upload_stub.blank?
complete_external_upload_via_manager(external_upload_stub)
@@ -73,7 +79,10 @@ module ExternalUploadHelpers
def create_multipart
RateLimiter.new(
- current_user, "create-multipart-upload", ExternalUploadHelpers::CREATE_MULTIPART_RATE_LIMIT_PER_MINUTE, 1.minute
+ current_user,
+ "create-multipart-upload",
+ ExternalUploadHelpers::CREATE_MULTIPART_RATE_LIMIT_PER_MINUTE,
+ 1.minute,
).performed!
file_name = params.require(:file_name)
@@ -84,22 +93,23 @@ module ExternalUploadHelpers
validate_before_create_multipart(
file_name: file_name,
file_size: file_size,
- upload_type: upload_type
+ upload_type: upload_type,
)
rescue ExternalUploadValidationError => err
return render_json_error(err.message, status: 422)
end
begin
- external_upload_data = create_direct_multipart_upload do
- ExternalUploadManager.create_direct_multipart_upload(
- current_user: current_user,
- file_name: file_name,
- file_size: file_size,
- upload_type: upload_type,
- metadata: parse_allowed_metadata(params[:metadata])
- )
- end
+ external_upload_data =
+ create_direct_multipart_upload do
+ ExternalUploadManager.create_direct_multipart_upload(
+ current_user: current_user,
+ file_name: file_name,
+ file_size: file_size,
+ upload_type: upload_type,
+ metadata: parse_allowed_metadata(params[:metadata]),
+ )
+ end
rescue ExternalUploadHelpers::ExternalUploadValidationError => err
return render_json_error(err.message, status: 422)
end
@@ -121,21 +131,19 @@ module ExternalUploadHelpers
# The other external upload endpoints are not hit as often, so they can stay as constant
# values for now.
RateLimiter.new(
- current_user, "batch-presign", SiteSetting.max_batch_presign_multipart_per_minute, 1.minute
+ current_user,
+ "batch-presign",
+ SiteSetting.max_batch_presign_multipart_per_minute,
+ 1.minute,
).performed!
- part_numbers = part_numbers.map do |part_number|
- validate_part_number(part_number)
- end
+ part_numbers = part_numbers.map { |part_number| validate_part_number(part_number) }
- external_upload_stub = ExternalUploadStub.find_by(
- unique_identifier: unique_identifier, created_by: current_user
- )
+ external_upload_stub =
+ ExternalUploadStub.find_by(unique_identifier: unique_identifier, created_by: current_user)
return render_404 if external_upload_stub.blank?
- if !multipart_upload_exists?(external_upload_stub)
- return render_404
- end
+ return render_404 if !multipart_upload_exists?(external_upload_stub)
store = multipart_store(external_upload_stub.upload_type)
@@ -144,7 +152,7 @@ module ExternalUploadHelpers
presigned_urls[part_number] = store.presign_multipart_part(
upload_id: external_upload_stub.external_upload_identifier,
key: external_upload_stub.key,
- part_number: part_number
+ part_number: part_number,
)
end
@@ -157,10 +165,16 @@ module ExternalUploadHelpers
store.list_multipart_parts(
upload_id: external_upload_stub.external_upload_identifier,
key: external_upload_stub.key,
- max_parts: 1
+ max_parts: 1,
)
rescue Aws::S3::Errors::NoSuchUpload => err
- debug_upload_error(err, I18n.t("upload.external_upload_not_found", additional_detail: "path: #{external_upload_stub.key}"))
+ debug_upload_error(
+ err,
+ I18n.t(
+ "upload.external_upload_not_found",
+ additional_detail: "path: #{external_upload_stub.key}",
+ ),
+ )
return false
end
true
@@ -168,9 +182,8 @@ module ExternalUploadHelpers
def abort_multipart
external_upload_identifier = params.require(:external_upload_identifier)
- external_upload_stub = ExternalUploadStub.find_by(
- external_upload_identifier: external_upload_identifier
- )
+ external_upload_stub =
+ ExternalUploadStub.find_by(external_upload_identifier: external_upload_identifier)
# The stub could have already been deleted by an earlier error via
# ExternalUploadManager, so we consider this a great success if the
@@ -183,12 +196,20 @@ module ExternalUploadHelpers
begin
store.abort_multipart(
upload_id: external_upload_stub.external_upload_identifier,
- key: external_upload_stub.key
+ key: external_upload_stub.key,
)
rescue Aws::S3::Errors::ServiceError => err
- return render_json_error(
- debug_upload_error(err, I18n.t("upload.abort_multipart_failure", additional_detail: "external upload stub id: #{external_upload_stub.id}")),
- status: 422
+ return(
+ render_json_error(
+ debug_upload_error(
+ err,
+ I18n.t(
+ "upload.abort_multipart_failure",
+ additional_detail: "external upload stub id: #{external_upload_stub.id}",
+ ),
+ ),
+ status: 422,
+ )
)
end
@@ -202,45 +223,57 @@ module ExternalUploadHelpers
parts = params.require(:parts)
RateLimiter.new(
- current_user, "complete-multipart-upload", ExternalUploadHelpers::COMPLETE_MULTIPART_RATE_LIMIT_PER_MINUTE, 1.minute
+ current_user,
+ "complete-multipart-upload",
+ ExternalUploadHelpers::COMPLETE_MULTIPART_RATE_LIMIT_PER_MINUTE,
+ 1.minute,
).performed!
- external_upload_stub = ExternalUploadStub.find_by(
- unique_identifier: unique_identifier, created_by: current_user
- )
+ external_upload_stub =
+ ExternalUploadStub.find_by(unique_identifier: unique_identifier, created_by: current_user)
return render_404 if external_upload_stub.blank?
- if !multipart_upload_exists?(external_upload_stub)
- return render_404
- end
+ return render_404 if !multipart_upload_exists?(external_upload_stub)
store = multipart_store(external_upload_stub.upload_type)
- parts = parts.map do |part|
- part_number = part[:part_number]
- etag = part[:etag]
- part_number = validate_part_number(part_number)
-
- if etag.blank?
- raise Discourse::InvalidParameters.new("All parts must have an etag and a valid part number")
- end
-
- # this is done so it's an array of hashes rather than an array of
- # ActionController::Parameters
- { part_number: part_number, etag: etag }
- end.sort_by do |part|
- part[:part_number]
- end
+ parts =
+ parts
+ .map do |part|
+ part_number = part[:part_number]
+ etag = part[:etag]
+ part_number = validate_part_number(part_number)
+
+ if etag.blank?
+ raise Discourse::InvalidParameters.new(
+ "All parts must have an etag and a valid part number",
+ )
+ end
+
+ # this is done so it's an array of hashes rather than an array of
+ # ActionController::Parameters
+ { part_number: part_number, etag: etag }
+ end
+ .sort_by { |part| part[:part_number] }
begin
- complete_response = store.complete_multipart(
- upload_id: external_upload_stub.external_upload_identifier,
- key: external_upload_stub.key,
- parts: parts
- )
+ complete_response =
+ store.complete_multipart(
+ upload_id: external_upload_stub.external_upload_identifier,
+ key: external_upload_stub.key,
+ parts: parts,
+ )
rescue Aws::S3::Errors::ServiceError => err
- return render_json_error(
- debug_upload_error(err, I18n.t("upload.complete_multipart_failure", additional_detail: "external upload stub id: #{external_upload_stub.id}")),
- status: 422
+ return(
+ render_json_error(
+ debug_upload_error(
+ err,
+ I18n.t(
+ "upload.complete_multipart_failure",
+ additional_detail: "external upload stub id: #{external_upload_stub.id}",
+ ),
+ ),
+ status: 422,
+ )
)
end
@@ -270,27 +303,40 @@ module ExternalUploadHelpers
end
rescue ExternalUploadManager::SizeMismatchError => err
render_json_error(
- debug_upload_error(err, I18n.t("upload.size_mismatch_failure", additional_detail: err.message)),
- status: 422
+ debug_upload_error(
+ err,
+ I18n.t("upload.size_mismatch_failure", additional_detail: err.message),
+ ),
+ status: 422,
)
rescue ExternalUploadManager::ChecksumMismatchError => err
render_json_error(
- debug_upload_error(err, I18n.t("upload.checksum_mismatch_failure", additional_detail: err.message)),
- status: 422
+ debug_upload_error(
+ err,
+ I18n.t("upload.checksum_mismatch_failure", additional_detail: err.message),
+ ),
+ status: 422,
)
rescue ExternalUploadManager::CannotPromoteError => err
render_json_error(
- debug_upload_error(err, I18n.t("upload.cannot_promote_failure", additional_detail: err.message)),
- status: 422
+ debug_upload_error(
+ err,
+ I18n.t("upload.cannot_promote_failure", additional_detail: err.message),
+ ),
+ status: 422,
)
rescue ExternalUploadManager::DownloadFailedError, Aws::S3::Errors::NotFound => err
render_json_error(
- debug_upload_error(err, I18n.t("upload.download_failure", additional_detail: err.message)),
- status: 422
+ debug_upload_error(
+ err,
+ I18n.t("upload.download_failure", additional_detail: err.message),
+ ),
+ status: 422,
)
rescue => err
Discourse.warn_exception(
- err, message: "Complete external upload failed unexpectedly for user #{current_user.id}"
+ err,
+ message: "Complete external upload failed unexpectedly for user #{current_user.id}",
)
render_json_error(I18n.t("upload.failed"), status: 422)
@@ -308,10 +354,8 @@ module ExternalUploadHelpers
def validate_part_number(part_number)
part_number = part_number.to_i
- if !part_number.between?(1, 10000)
- raise Discourse::InvalidParameters.new(
- "Each part number should be between 1 and 10000"
- )
+ if !part_number.between?(1, 10_000)
+ raise Discourse::InvalidParameters.new("Each part number should be between 1 and 10000")
end
part_number
end
diff --git a/lib/faker/discourse.rb b/lib/faker/discourse.rb
index a2c4720026d..ed527841dcb 100644
--- a/lib/faker/discourse.rb
+++ b/lib/faker/discourse.rb
@@ -1,25 +1,24 @@
# frozen_string_literal: true
-require 'faker'
+require "faker"
module Faker
class Discourse < Base
class << self
-
def tag
- fetch('discourse.tags')
+ fetch("discourse.tags")
end
def category
- fetch('discourse.categories')
+ fetch("discourse.categories")
end
def group
- fetch('discourse.groups')
+ fetch("discourse.groups")
end
def topic
- fetch('discourse.topics')
+ fetch("discourse.topics")
end
end
end
diff --git a/lib/faker/discourse_markdown.rb b/lib/faker/discourse_markdown.rb
index 8f5266a1914..f893f051894 100644
--- a/lib/faker/discourse_markdown.rb
+++ b/lib/faker/discourse_markdown.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-require 'faker'
-require 'net/http'
-require 'json'
+require "faker"
+require "net/http"
+require "json"
module Faker
class DiscourseMarkdown < Markdown
@@ -27,11 +27,8 @@ module Faker
image = next_image
image_file = load_image(image)
- upload = ::UploadCreator.new(
- image_file,
- image[:filename],
- origin: image[:url]
- ).create_for(user_id)
+ upload =
+ ::UploadCreator.new(image_file, image[:filename], origin: image[:url]).create_for(user_id)
::UploadMarkdown.new(upload).to_markdown if upload.present? && upload.persisted?
rescue => e
@@ -62,7 +59,7 @@ module Faker
end
image = @images.pop
- { filename: "#{image['id']}.jpg", url: "#{image['download_url']}.jpg" }
+ { filename: "#{image["id"]}.jpg", url: "#{image["download_url"]}.jpg" }
end
def image_cache_dir
@@ -74,12 +71,13 @@ module Faker
if !::File.exist?(cache_path)
FileUtils.mkdir_p(image_cache_dir)
- temp_file = ::FileHelper.download(
- image[:url],
- max_file_size: [SiteSetting.max_image_size_kb.kilobytes, 10.megabytes].max,
- tmp_file_name: "image",
- follow_redirect: true
- )
+ temp_file =
+ ::FileHelper.download(
+ image[:url],
+ max_file_size: [SiteSetting.max_image_size_kb.kilobytes, 10.megabytes].max,
+ tmp_file_name: "image",
+ follow_redirect: true,
+ )
FileUtils.cp(temp_file, cache_path)
end
diff --git a/lib/feed_element_installer.rb b/lib/feed_element_installer.rb
index 2e0ecd40ec3..c96e89d1446 100644
--- a/lib/feed_element_installer.rb
+++ b/lib/feed_element_installer.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'rexml/document'
-require 'rss'
+require "rexml/document"
+require "rss"
class FeedElementInstaller
private_class_method :new
@@ -10,7 +10,7 @@ class FeedElementInstaller
# RSS Specification at http://cyber.harvard.edu/rss/rss.html#extendingRss
# > A RSS feed may contain [non-standard elements], only if those elements are *defined in a namespace*
- new(element_name, feed).install if element_name.include?(':')
+ new(element_name, feed).install if element_name.include?(":")
end
attr_reader :feed, :original_name, :element_namespace, :element_name, :element_accessor
@@ -18,12 +18,13 @@ class FeedElementInstaller
def initialize(element_name, feed)
@feed = feed
@original_name = element_name
- @element_namespace, @element_name = *element_name.split(':')
+ @element_namespace, @element_name = *element_name.split(":")
@element_accessor = "#{@element_namespace}_#{@element_name}"
end
def element_uri
- @element_uri ||= REXML::Document.new(feed).root&.attributes&.namespaces&.fetch(@element_namespace, '') || ''
+ @element_uri ||=
+ REXML::Document.new(feed).root&.attributes&.namespaces&.fetch(@element_namespace, "") || ""
end
def install
@@ -34,13 +35,34 @@ class FeedElementInstaller
private
def install_in_rss
- RSS::Rss::Channel::Item.install_text_element(element_name, element_uri, '?', element_accessor, nil, original_name)
+ RSS::Rss::Channel::Item.install_text_element(
+ element_name,
+ element_uri,
+ "?",
+ element_accessor,
+ nil,
+ original_name,
+ )
RSS::BaseListener.install_get_text_element(element_uri, element_name, element_accessor)
end
def install_in_atom
- RSS::Atom::Entry.install_text_element(element_name, element_uri, '?', element_accessor, nil, original_name)
- RSS::Atom::Feed::Entry.install_text_element(element_name, element_uri, '?', element_accessor, nil, original_name)
+ RSS::Atom::Entry.install_text_element(
+ element_name,
+ element_uri,
+ "?",
+ element_accessor,
+ nil,
+ original_name,
+ )
+ RSS::Atom::Feed::Entry.install_text_element(
+ element_name,
+ element_uri,
+ "?",
+ element_accessor,
+ nil,
+ original_name,
+ )
RSS::BaseListener.install_get_text_element(element_uri, element_name, element_accessor)
end
@@ -49,6 +71,7 @@ class FeedElementInstaller
end
def installed_in_atom?
- RSS::Atom::Entry.method_defined?(element_accessor) || RSS::Atom::Feed::Entry.method_defined?(element_accessor)
+ RSS::Atom::Entry.method_defined?(element_accessor) ||
+ RSS::Atom::Feed::Entry.method_defined?(element_accessor)
end
end
diff --git a/lib/file_helper.rb b/lib/file_helper.rb
index 31530a12e96..9b57251f83c 100644
--- a/lib/file_helper.rb
+++ b/lib/file_helper.rb
@@ -5,11 +5,10 @@ require "mini_mime"
require "open-uri"
class FileHelper
-
def self.log(log_level, message)
Rails.logger.public_send(
log_level,
- "#{RailsMultisite::ConnectionManagement.current_db}: #{message}"
+ "#{RailsMultisite::ConnectionManagement.current_db}: #{message}",
)
end
@@ -41,29 +40,31 @@ class FileHelper
attr_accessor :status
end
- def self.download(url,
- max_file_size:,
- tmp_file_name:,
- follow_redirect: false,
- read_timeout: 5,
- skip_rate_limit: false,
- verbose: false,
- validate_uri: true,
- retain_on_max_file_size_exceeded: false)
-
+ def self.download(
+ url,
+ max_file_size:,
+ tmp_file_name:,
+ follow_redirect: false,
+ read_timeout: 5,
+ skip_rate_limit: false,
+ verbose: false,
+ validate_uri: true,
+ retain_on_max_file_size_exceeded: false
+ )
url = "https:" + url if url.start_with?("//")
- raise Discourse::InvalidParameters.new(:url) unless url =~ /^https?:\/\//
+ raise Discourse::InvalidParameters.new(:url) unless url =~ %r{^https?://}
tmp = nil
- fd = FinalDestination.new(
- url,
- max_redirects: follow_redirect ? 5 : 0,
- skip_rate_limit: skip_rate_limit,
- verbose: verbose,
- validate_uri: validate_uri,
- timeout: read_timeout
- )
+ fd =
+ FinalDestination.new(
+ url,
+ max_redirects: follow_redirect ? 5 : 0,
+ skip_rate_limit: skip_rate_limit,
+ verbose: verbose,
+ validate_uri: validate_uri,
+ timeout: read_timeout,
+ )
fd.get do |response, chunk, uri|
if tmp.nil?
@@ -110,7 +111,7 @@ class FileHelper
def self.optimize_image!(filename, allow_pngquant: false)
image_optim(
allow_pngquant: allow_pngquant,
- strip_image_metadata: SiteSetting.strip_image_metadata
+ strip_image_metadata: SiteSetting.strip_image_metadata,
).optimize_image!(filename)
end
@@ -119,23 +120,26 @@ class FileHelper
# sometimes up to 200ms searching for binaries and looking at versions
memoize("image_optim", allow_pngquant, strip_image_metadata) do
pngquant_options = false
- if allow_pngquant
- pngquant_options = { allow_lossy: true }
- end
+ pngquant_options = { allow_lossy: true } if allow_pngquant
ImageOptim.new(
# GLOBAL
timeout: 15,
skip_missing_workers: true,
# PNG
- oxipng: { level: 3, strip: strip_image_metadata },
+ oxipng: {
+ level: 3,
+ strip: strip_image_metadata,
+ },
optipng: false,
advpng: false,
pngcrush: false,
pngout: false,
pngquant: pngquant_options,
# JPG
- jpegoptim: { strip: strip_image_metadata ? "all" : "none" },
+ jpegoptim: {
+ strip: strip_image_metadata ? "all" : "none",
+ },
jpegtran: false,
jpegrecompress: false,
# Skip looking for gifsicle, svgo binaries
@@ -150,24 +154,24 @@ class FileHelper
end
def self.supported_gravatar_extensions
- @@supported_gravatar_images ||= Set.new(%w{jpg jpeg png gif})
+ @@supported_gravatar_images ||= Set.new(%w[jpg jpeg png gif])
end
def self.supported_images
- @@supported_images ||= Set.new %w{jpg jpeg png gif svg ico webp}
+ @@supported_images ||= Set.new %w[jpg jpeg png gif svg ico webp]
end
def self.inline_images
# SVG cannot safely be shown as a document
- @@inline_images ||= supported_images - %w{svg}
+ @@inline_images ||= supported_images - %w[svg]
end
def self.supported_audio
- @@supported_audio ||= Set.new %w{mp3 ogg oga opus wav m4a m4b m4p m4r aac flac}
+ @@supported_audio ||= Set.new %w[mp3 ogg oga opus wav m4a m4b m4p m4r aac flac]
end
def self.supported_video
- @@supported_video ||= Set.new %w{mov mp4 webm ogv m4v 3gp avi mpeg}
+ @@supported_video ||= Set.new %w[mov mp4 webm ogv m4v 3gp avi mpeg]
end
def self.supported_video_regexp
diff --git a/lib/file_store/base_store.rb b/lib/file_store/base_store.rb
index 8b4c41cf6f4..f73114ca897 100644
--- a/lib/file_store/base_store.rb
+++ b/lib/file_store/base_store.rb
@@ -1,10 +1,9 @@
# frozen_string_literal: true
module FileStore
-
class BaseStore
- UPLOAD_PATH_REGEX ||= %r|/(original/\d+X/.*)|
- OPTIMIZED_IMAGE_PATH_REGEX ||= %r|/(optimized/\d+X/.*)|
+ UPLOAD_PATH_REGEX ||= %r{/(original/\d+X/.*)}
+ OPTIMIZED_IMAGE_PATH_REGEX ||= %r{/(optimized/\d+X/.*)}
TEMPORARY_UPLOAD_PREFIX ||= "temp/"
def store_upload(file, upload, content_type = nil)
@@ -38,7 +37,7 @@ module FileStore
def upload_path
path = File.join("uploads", RailsMultisite::ConnectionManagement.current_db)
return path if !Rails.env.test?
- File.join(path, "test_#{ENV['TEST_ENV_NUMBER'].presence || '0'}")
+ File.join(path, "test_#{ENV["TEST_ENV_NUMBER"].presence || "0"}")
end
def self.temporary_upload_path(file_name, folder_prefix: "")
@@ -46,12 +45,7 @@ module FileStore
# characters, which can interfere with external providers operations and
# introduce other unexpected behaviour.
file_name_random = "#{SecureRandom.hex}#{File.extname(file_name)}"
- File.join(
- TEMPORARY_UPLOAD_PREFIX,
- folder_prefix,
- SecureRandom.hex,
- file_name_random
- )
+ File.join(TEMPORARY_UPLOAD_PREFIX, folder_prefix, SecureRandom.hex, file_name_random)
end
def has_been_uploaded?(url)
@@ -96,25 +90,37 @@ module FileStore
def download(object, max_file_size_kb: nil)
DistributedMutex.synchronize("download_#{object.sha1}", validity: 3.minutes) do
- extension = File.extname(object.respond_to?(:original_filename) ? object.original_filename : object.url)
+ extension =
+ File.extname(
+ object.respond_to?(:original_filename) ? object.original_filename : object.url,
+ )
filename = "#{object.sha1}#{extension}"
file = get_from_cache(filename)
if !file
- max_file_size_kb ||= [SiteSetting.max_image_size_kb, SiteSetting.max_attachment_size_kb].max.kilobytes
+ max_file_size_kb ||= [
+ SiteSetting.max_image_size_kb,
+ SiteSetting.max_attachment_size_kb,
+ ].max.kilobytes
secure = object.respond_to?(:secure) ? object.secure? : object.upload.secure?
- url = secure ?
- Discourse.store.signed_url_for_path(object.url) :
- Discourse.store.cdn_url(object.url)
-
- url = SiteSetting.scheme + ":" + url if url =~ /^\/\//
- file = FileHelper.download(
- url,
- max_file_size: max_file_size_kb,
- tmp_file_name: "discourse-download",
- follow_redirect: true
- )
+ url =
+ (
+ if secure
+ Discourse.store.signed_url_for_path(object.url)
+ else
+ Discourse.store.cdn_url(object.url)
+ end
+ )
+
+ url = SiteSetting.scheme + ":" + url if url =~ %r{^//}
+ file =
+ FileHelper.download(
+ url,
+ max_file_size: max_file_size_kb,
+ tmp_file_name: "discourse-download",
+ follow_redirect: true,
+ )
return nil if file.nil?
@@ -162,7 +168,8 @@ module FileStore
upload = optimized_image.upload
version = optimized_image.version || 1
- extension = "_#{version}_#{optimized_image.width}x#{optimized_image.height}#{optimized_image.extension}"
+ extension =
+ "_#{version}_#{optimized_image.width}x#{optimized_image.height}#{optimized_image.extension}"
get_path_for("optimized", upload.id, upload.sha1, extension)
end
@@ -214,5 +221,4 @@ module FileStore
path
end
end
-
end
diff --git a/lib/file_store/local_store.rb b/lib/file_store/local_store.rb
index 4922eca7077..c0461aa50a7 100644
--- a/lib/file_store/local_store.rb
+++ b/lib/file_store/local_store.rb
@@ -1,11 +1,9 @@
# frozen_string_literal: true
-require 'file_store/base_store'
+require "file_store/base_store"
module FileStore
-
class LocalStore < BaseStore
-
def store_file(file, path)
copy_file(file, "#{public_dir}#{path}")
"#{Discourse.base_path}#{path}"
@@ -64,7 +62,13 @@ module FileStore
def purge_tombstone(grace_period)
if Dir.exist?(Discourse.store.tombstone_dir)
Discourse::Utils.execute_command(
- 'find', tombstone_dir, '-mtime', "+#{grace_period}", '-type', 'f', '-delete'
+ "find",
+ tombstone_dir,
+ "-mtime",
+ "+#{grace_period}",
+ "-type",
+ "f",
+ "-delete",
)
end
end
@@ -108,9 +112,13 @@ module FileStore
FileUtils.mkdir_p(File.join(public_dir, upload_path))
Discourse::Utils.execute_command(
- 'rsync', '-a', '--safe-links', "#{source_path}/", "#{upload_path}/",
+ "rsync",
+ "-a",
+ "--safe-links",
+ "#{source_path}/",
+ "#{upload_path}/",
failure_message: "Failed to copy uploads.",
- chdir: public_dir
+ chdir: public_dir,
)
end
@@ -119,15 +127,14 @@ module FileStore
def list_missing(model)
count = 0
model.find_each do |upload|
-
# could be a remote image
- next unless upload.url =~ /^\/[^\/]/
+ next unless upload.url =~ %r{^/[^/]}
path = "#{public_dir}#{upload.url}"
bad = true
begin
bad = false if File.size(path) != 0
- rescue
+ rescue StandardError
# something is messed up
end
if bad
diff --git a/lib/file_store/s3_store.rb b/lib/file_store/s3_store.rb
index 074bf924468..8fdbd2d9fab 100644
--- a/lib/file_store/s3_store.rb
+++ b/lib/file_store/s3_store.rb
@@ -7,61 +7,64 @@ require "s3_helper"
require "file_helper"
module FileStore
-
class S3Store < BaseStore
TOMBSTONE_PREFIX ||= "tombstone/"
- delegate :abort_multipart, :presign_multipart_part, :list_multipart_parts,
- :complete_multipart, to: :s3_helper
+ delegate :abort_multipart,
+ :presign_multipart_part,
+ :list_multipart_parts,
+ :complete_multipart,
+ to: :s3_helper
def initialize(s3_helper = nil)
@s3_helper = s3_helper
end
def s3_helper
- @s3_helper ||= S3Helper.new(s3_bucket,
- Rails.configuration.multisite ? multisite_tombstone_prefix : TOMBSTONE_PREFIX
- )
+ @s3_helper ||=
+ S3Helper.new(
+ s3_bucket,
+ Rails.configuration.multisite ? multisite_tombstone_prefix : TOMBSTONE_PREFIX,
+ )
end
def store_upload(file, upload, content_type = nil)
upload.url = nil
path = get_path_for_upload(upload)
- url, upload.etag = store_file(
- file,
- path,
- filename: upload.original_filename,
- content_type: content_type,
- cache_locally: true,
- private_acl: upload.secure?
- )
+ url, upload.etag =
+ store_file(
+ file,
+ path,
+ filename: upload.original_filename,
+ content_type: content_type,
+ cache_locally: true,
+ private_acl: upload.secure?,
+ )
url
end
- def move_existing_stored_upload(
- existing_external_upload_key:,
- upload: nil,
- content_type: nil
- )
+ def move_existing_stored_upload(existing_external_upload_key:, upload: nil, content_type: nil)
upload.url = nil
path = get_path_for_upload(upload)
- url, upload.etag = store_file(
- nil,
- path,
- filename: upload.original_filename,
- content_type: content_type,
- cache_locally: false,
- private_acl: upload.secure?,
- move_existing: true,
- existing_external_upload_key: existing_external_upload_key
- )
+ url, upload.etag =
+ store_file(
+ nil,
+ path,
+ filename: upload.original_filename,
+ content_type: content_type,
+ cache_locally: false,
+ private_acl: upload.secure?,
+ move_existing: true,
+ existing_external_upload_key: existing_external_upload_key,
+ )
url
end
def store_optimized_image(file, optimized_image, content_type = nil, secure: false)
optimized_image.url = nil
path = get_path_for_optimized_image(optimized_image)
- url, optimized_image.etag = store_file(file, path, content_type: content_type, private_acl: secure)
+ url, optimized_image.etag =
+ store_file(file, path, content_type: content_type, private_acl: secure)
url
end
@@ -85,8 +88,9 @@ module FileStore
cache_file(file, File.basename(path)) if opts[:cache_locally]
options = {
acl: opts[:private_acl] ? "private" : "public-read",
- cache_control: 'max-age=31556952, public, immutable',
- content_type: opts[:content_type].presence || MiniMime.lookup_by_filename(filename)&.content_type
+ cache_control: "max-age=31556952, public, immutable",
+ content_type:
+ opts[:content_type].presence || MiniMime.lookup_by_filename(filename)&.content_type,
}
# add a "content disposition: attachment" header with the original
@@ -96,7 +100,8 @@ module FileStore
# browser.
if !FileHelper.is_inline_image?(filename)
options[:content_disposition] = ActionDispatch::Http::ContentDisposition.format(
- disposition: "attachment", filename: filename
+ disposition: "attachment",
+ filename: filename,
)
end
@@ -106,11 +111,7 @@ module FileStore
if opts[:move_existing] && opts[:existing_external_upload_key]
original_path = opts[:existing_external_upload_key]
options[:apply_metadata_to_destination] = true
- path, etag = s3_helper.copy(
- original_path,
- path,
- options: options
- )
+ path, etag = s3_helper.copy(original_path, path, options: options)
delete_file(original_path)
else
path, etag = s3_helper.upload(file, path, options)
@@ -142,7 +143,7 @@ module FileStore
begin
parsed_url = URI.parse(UrlHelper.encode(url))
- rescue
+ rescue StandardError
# There are many exceptions possible here including Addressable::URI:: exceptions
# and URI:: exceptions, catch all may seem wide, but it makes no sense to raise ever
# on an invalid url here
@@ -169,7 +170,10 @@ module FileStore
s3_cdn_url = URI.parse(SiteSetting.Upload.s3_cdn_url || "")
cdn_hostname = s3_cdn_url.hostname
- return true if cdn_hostname.presence && url[cdn_hostname] && (s3_cdn_url.path.blank? || parsed_url.path.starts_with?(s3_cdn_url.path))
+ if cdn_hostname.presence && url[cdn_hostname] &&
+ (s3_cdn_url.path.blank? || parsed_url.path.starts_with?(s3_cdn_url.path))
+ return true
+ end
false
end
@@ -186,7 +190,11 @@ module FileStore
end
def s3_upload_host
- SiteSetting.Upload.s3_cdn_url.present? ? SiteSetting.Upload.s3_cdn_url : "https:#{absolute_base_url}"
+ if SiteSetting.Upload.s3_cdn_url.present?
+ SiteSetting.Upload.s3_cdn_url
+ else
+ "https:#{absolute_base_url}"
+ end
end
def external?
@@ -208,28 +216,45 @@ module FileStore
def path_for(upload)
url = upload&.url
- FileStore::LocalStore.new.path_for(upload) if url && url[/^\/[^\/]/]
+ FileStore::LocalStore.new.path_for(upload) if url && url[%r{^/[^/]}]
end
def url_for(upload, force_download: false)
- upload.secure? || force_download ?
- presigned_get_url(get_upload_key(upload), force_download: force_download, filename: upload.original_filename) :
+ if upload.secure? || force_download
+ presigned_get_url(
+ get_upload_key(upload),
+ force_download: force_download,
+ filename: upload.original_filename,
+ )
+ else
upload.url
+ end
end
def cdn_url(url)
return url if SiteSetting.Upload.s3_cdn_url.blank?
- schema = url[/^(https?:)?\/\//, 1]
+ schema = url[%r{^(https?:)?//}, 1]
folder = s3_bucket_folder_path.nil? ? "" : "#{s3_bucket_folder_path}/"
- url.sub(File.join("#{schema}#{absolute_base_url}", folder), File.join(SiteSetting.Upload.s3_cdn_url, "/"))
+ url.sub(
+ File.join("#{schema}#{absolute_base_url}", folder),
+ File.join(SiteSetting.Upload.s3_cdn_url, "/"),
+ )
end
- def signed_url_for_path(path, expires_in: SiteSetting.s3_presigned_get_url_expires_after_seconds, force_download: false)
+ def signed_url_for_path(
+ path,
+ expires_in: SiteSetting.s3_presigned_get_url_expires_after_seconds,
+ force_download: false
+ )
key = path.sub(absolute_base_url + "/", "")
presigned_get_url(key, expires_in: expires_in, force_download: force_download)
end
- def signed_url_for_temporary_upload(file_name, expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS, metadata: {})
+ def signed_url_for_temporary_upload(
+ file_name,
+ expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS,
+ metadata: {}
+ )
key = temporary_upload_path(file_name)
s3_helper.presigned_url(
key,
@@ -237,16 +262,15 @@ module FileStore
expires_in: expires_in,
opts: {
metadata: metadata,
- acl: "private"
- }
+ acl: "private",
+ },
)
end
def temporary_upload_path(file_name)
- folder_prefix = s3_bucket_folder_path.nil? ? upload_path : File.join(s3_bucket_folder_path, upload_path)
- FileStore::BaseStore.temporary_upload_path(
- file_name, folder_prefix: folder_prefix
- )
+ folder_prefix =
+ s3_bucket_folder_path.nil? ? upload_path : File.join(s3_bucket_folder_path, upload_path)
+ FileStore::BaseStore.temporary_upload_path(file_name, folder_prefix: folder_prefix)
end
def object_from_path(path)
@@ -264,13 +288,15 @@ module FileStore
end
def s3_bucket
- raise Discourse::SiteSettingMissing.new("s3_upload_bucket") if SiteSetting.Upload.s3_upload_bucket.blank?
+ if SiteSetting.Upload.s3_upload_bucket.blank?
+ raise Discourse::SiteSettingMissing.new("s3_upload_bucket")
+ end
SiteSetting.Upload.s3_upload_bucket.downcase
end
def list_missing_uploads(skip_optimized: false)
if SiteSetting.enable_s3_inventory
- require 's3_inventory'
+ require "s3_inventory"
S3Inventory.new(s3_helper, :upload).backfill_etags_and_list_missing
S3Inventory.new(s3_helper, :optimized).backfill_etags_and_list_missing unless skip_optimized
else
@@ -326,7 +352,6 @@ module FileStore
s3_options: FileStore::ToS3Migration.s3_options_from_site_settings,
migrate_to_multisite: Rails.configuration.multisite,
).migrate
-
ensure
FileUtils.rm(public_upload_path) if File.symlink?(public_upload_path)
FileUtils.mv(old_upload_path, public_upload_path) if old_upload_path
@@ -349,7 +374,8 @@ module FileStore
if force_download && filename
opts[:response_content_disposition] = ActionDispatch::Http::ContentDisposition.format(
- disposition: "attachment", filename: filename
+ disposition: "attachment",
+ filename: filename,
)
end
@@ -375,11 +401,11 @@ module FileStore
def list_missing(model, prefix)
connection = ActiveRecord::Base.connection.raw_connection
- connection.exec('CREATE TEMP TABLE verified_ids(val integer PRIMARY KEY)')
+ connection.exec("CREATE TEMP TABLE verified_ids(val integer PRIMARY KEY)")
marker = nil
files = s3_helper.list(prefix, marker)
- while files.count > 0 do
+ while files.count > 0
verified_ids = []
files.each do |f|
@@ -388,23 +414,25 @@ module FileStore
marker = f.key
end
- verified_id_clause = verified_ids.map { |id| "('#{PG::Connection.escape_string(id.to_s)}')" }.join(",")
+ verified_id_clause =
+ verified_ids.map { |id| "('#{PG::Connection.escape_string(id.to_s)}')" }.join(",")
connection.exec("INSERT INTO verified_ids VALUES #{verified_id_clause}")
files = s3_helper.list(prefix, marker)
end
- missing_uploads = model.joins('LEFT JOIN verified_ids ON verified_ids.val = id').where("verified_ids.val IS NULL")
+ missing_uploads =
+ model.joins("LEFT JOIN verified_ids ON verified_ids.val = id").where(
+ "verified_ids.val IS NULL",
+ )
missing_count = missing_uploads.count
if missing_count > 0
- missing_uploads.find_each do |upload|
- puts upload.url
- end
+ missing_uploads.find_each { |upload| puts upload.url }
puts "#{missing_count} of #{model.count} #{model.name.underscore.pluralize} are missing"
end
ensure
- connection.exec('DROP TABLE verified_ids') unless connection.nil?
+ connection.exec("DROP TABLE verified_ids") unless connection.nil?
end
end
end
diff --git a/lib/file_store/to_s3_migration.rb b/lib/file_store/to_s3_migration.rb
index 0d6c098327f..b99c911a6b9 100644
--- a/lib/file_store/to_s3_migration.rb
+++ b/lib/file_store/to_s3_migration.rb
@@ -1,16 +1,20 @@
# frozen_string_literal: true
-require 'aws-sdk-s3'
+require "aws-sdk-s3"
module FileStore
ToS3MigrationError = Class.new(RuntimeError)
class ToS3Migration
- MISSING_UPLOADS_RAKE_TASK_NAME ||= 'posts:missing_uploads'
+ MISSING_UPLOADS_RAKE_TASK_NAME ||= "posts:missing_uploads"
UPLOAD_CONCURRENCY ||= 20
- def initialize(s3_options:, dry_run: false, migrate_to_multisite: false, skip_etag_verify: false)
-
+ def initialize(
+ s3_options:,
+ dry_run: false,
+ migrate_to_multisite: false,
+ skip_etag_verify: false
+ )
@s3_bucket = s3_options[:bucket]
@s3_client_options = s3_options[:client_options]
@dry_run = dry_run
@@ -22,20 +26,18 @@ module FileStore
def self.s3_options_from_site_settings
{
client_options: S3Helper.s3_options(SiteSetting),
- bucket: SiteSetting.Upload.s3_upload_bucket
+ bucket: SiteSetting.Upload.s3_upload_bucket,
}
end
def self.s3_options_from_env
- unless ENV["DISCOURSE_S3_BUCKET"].present? &&
- ENV["DISCOURSE_S3_REGION"].present? &&
- (
- (
- ENV["DISCOURSE_S3_ACCESS_KEY_ID"].present? &&
- ENV["DISCOURSE_S3_SECRET_ACCESS_KEY"].present?
- ) || ENV["DISCOURSE_S3_USE_IAM_PROFILE"].present?
- )
-
+ unless ENV["DISCOURSE_S3_BUCKET"].present? && ENV["DISCOURSE_S3_REGION"].present? &&
+ (
+ (
+ ENV["DISCOURSE_S3_ACCESS_KEY_ID"].present? &&
+ ENV["DISCOURSE_S3_SECRET_ACCESS_KEY"].present?
+ ) || ENV["DISCOURSE_S3_USE_IAM_PROFILE"].present?
+ )
raise ToS3MigrationError.new(<<~TEXT)
Please provide the following environment variables:
- DISCOURSE_S3_BUCKET
@@ -53,13 +55,10 @@ module FileStore
if ENV["DISCOURSE_S3_USE_IAM_PROFILE"].blank?
opts[:access_key_id] = ENV["DISCOURSE_S3_ACCESS_KEY_ID"]
- opts[:secret_access_key] = ENV["DISCOURSE_S3_SECRET_ACCESS_KEY"]
+ opts[:secret_access_key] = ENV["DISCOURSE_S3_SECRET_ACCESS_KEY"]
end
- {
- client_options: opts,
- bucket: ENV["DISCOURSE_S3_BUCKET"]
- }
+ { client_options: opts, bucket: ENV["DISCOURSE_S3_BUCKET"] }
end
def migrate
@@ -75,7 +74,8 @@ module FileStore
base_url = File.join(SiteSetting.Upload.s3_base_url, prefix)
count = Upload.by_users.where("url NOT LIKE '#{base_url}%'").count
if count > 0
- error_message = "#{count} of #{Upload.count} uploads are not migrated to S3. #{failure_message}"
+ error_message =
+ "#{count} of #{Upload.count} uploads are not migrated to S3. #{failure_message}"
raise_or_log(error_message, should_raise)
success = false
end
@@ -88,7 +88,9 @@ module FileStore
success = false
end
- Discourse::Application.load_tasks unless Rake::Task.task_defined?(MISSING_UPLOADS_RAKE_TASK_NAME)
+ unless Rake::Task.task_defined?(MISSING_UPLOADS_RAKE_TASK_NAME)
+ Discourse::Application.load_tasks
+ end
Rake::Task[MISSING_UPLOADS_RAKE_TASK_NAME]
count = DB.query_single(<<~SQL, Post::MISSING_UPLOADS, Post::MISSING_UPLOADS_IGNORED).first
SELECT COUNT(1)
@@ -109,10 +111,14 @@ module FileStore
success = false
end
- count = Post.where('baked_version <> ? OR baked_version IS NULL', Post::BAKED_VERSION).count
+ count = Post.where("baked_version <> ? OR baked_version IS NULL", Post::BAKED_VERSION).count
if count > 0
log("#{count} posts still require rebaking and will be rebaked during regular job")
- log("To speed up migrations of posts we recommend you run 'rake posts:rebake_uncooked_posts'") if count > 100
+ if count > 100
+ log(
+ "To speed up migrations of posts we recommend you run 'rake posts:rebake_uncooked_posts'",
+ )
+ end
success = false
else
log("No posts require rebaking")
@@ -153,8 +159,10 @@ module FileStore
Upload.migrate_to_new_scheme
if !uploads_migrated_to_new_scheme?
- raise ToS3MigrationError.new("Some uploads could not be migrated to the new scheme. " \
- "You need to fix this manually.")
+ raise ToS3MigrationError.new(
+ "Some uploads could not be migrated to the new scheme. " \
+ "You need to fix this manually.",
+ )
end
end
@@ -174,10 +182,12 @@ module FileStore
log " - Listing local files"
local_files = []
- IO.popen("cd #{public_directory} && find uploads/#{@current_db}/original -type f").each do |file|
- local_files << file.chomp
- putc "." if local_files.size % 1000 == 0
- end
+ IO
+ .popen("cd #{public_directory} && find uploads/#{@current_db}/original -type f")
+ .each do |file|
+ local_files << file.chomp
+ putc "." if local_files.size % 1000 == 0
+ end
log " => #{local_files.size} files"
log " - Listing S3 files"
@@ -203,19 +213,20 @@ module FileStore
failed = []
lock = Mutex.new
- upload_threads = UPLOAD_CONCURRENCY.times.map do
- Thread.new do
- while obj = queue.pop
- if s3.put_object(obj[:options]).etag[obj[:etag]]
- putc "."
- lock.synchronize { synced += 1 }
- else
- putc "X"
- lock.synchronize { failed << obj[:path] }
+ upload_threads =
+ UPLOAD_CONCURRENCY.times.map do
+ Thread.new do
+ while obj = queue.pop
+ if s3.put_object(obj[:options]).etag[obj[:etag]]
+ putc "."
+ lock.synchronize { synced += 1 }
+ else
+ putc "X"
+ lock.synchronize { failed << obj[:path] }
+ end
end
end
end
- end
local_files.each do |file|
path = File.join(public_directory, file)
@@ -242,17 +253,17 @@ module FileStore
if upload&.original_filename
options[:content_disposition] = ActionDispatch::Http::ContentDisposition.format(
- disposition: "attachment", filename: upload.original_filename
+ disposition: "attachment",
+ filename: upload.original_filename,
)
end
- if upload&.secure
- options[:acl] = "private"
- end
+ options[:acl] = "private" if upload&.secure
elsif !FileHelper.is_inline_image?(name)
upload = Upload.find_by(url: "/#{file}")
options[:content_disposition] = ActionDispatch::Http::ContentDisposition.format(
- disposition: "attachment", filename: upload&.original_filename || name
+ disposition: "attachment",
+ filename: upload&.original_filename || name,
)
end
@@ -292,26 +303,25 @@ module FileStore
[
[
"src=\"/uploads/#{@current_db}/original/(\\dX/(?:[a-f0-9]/)*[a-f0-9]{40}[a-z0-9\\.]*)",
- "src=\"#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1"
+ "src=\"#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1",
],
[
"src='/uploads/#{@current_db}/original/(\\dX/(?:[a-f0-9]/)*[a-f0-9]{40}[a-z0-9\\.]*)",
- "src='#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1"
+ "src='#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1",
],
[
"href=\"/uploads/#{@current_db}/original/(\\dX/(?:[a-f0-9]/)*[a-f0-9]{40}[a-z0-9\\.]*)",
- "href=\"#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1"
+ "href=\"#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1",
],
[
"href='/uploads/#{@current_db}/original/(\\dX/(?:[a-f0-9]/)*[a-f0-9]{40}[a-z0-9\\.]*)",
- "href='#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1"
+ "href='#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1",
],
[
"\\[img\\]/uploads/#{@current_db}/original/(\\dX/(?:[a-f0-9]/)*[a-f0-9]{40}[a-z0-9\\.]*)\\[/img\\]",
- "[img]#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1[/img]"
- ]
+ "[img]#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1[/img]",
+ ],
].each do |from_url, to_url|
-
if @dry_run
log "REPLACING '#{from_url}' WITH '#{to_url}'"
else
@@ -321,16 +331,22 @@ module FileStore
unless @dry_run
# Legacy inline image format
- Post.where("raw LIKE '%![](/uploads/default/original/%)%'").each do |post|
- regexp = /!\[\](\/uploads\/#{@current_db}\/original\/(\dX\/(?:[a-f0-9]\/)*[a-f0-9]{40}[a-z0-9\.]*))/
-
- post.raw.scan(regexp).each do |upload_url, _|
- upload = Upload.get_from_url(upload_url)
- post.raw = post.raw.gsub("![](#{upload_url})", "![](#{upload.short_url})")
+ Post
+ .where("raw LIKE '%![](/uploads/default/original/%)%'")
+ .each do |post|
+ regexp =
+ /!\[\](\/uploads\/#{@current_db}\/original\/(\dX\/(?:[a-f0-9]\/)*[a-f0-9]{40}[a-z0-9\.]*))/
+
+ post
+ .raw
+ .scan(regexp)
+ .each do |upload_url, _|
+ upload = Upload.get_from_url(upload_url)
+ post.raw = post.raw.gsub("![](#{upload_url})", "![](#{upload.short_url})")
+ end
+
+ post.save!(validate: false)
end
-
- post.save!(validate: false)
- end
end
if Discourse.asset_host.present?
@@ -373,7 +389,6 @@ module FileStore
migration_successful?(should_raise: true)
log "Done!"
-
ensure
Jobs.run_later!
end
diff --git a/lib/filter_best_posts.rb b/lib/filter_best_posts.rb
index a243156b231..2ee63d35b55 100644
--- a/lib/filter_best_posts.rb
+++ b/lib/filter_best_posts.rb
@@ -1,16 +1,13 @@
# frozen_string_literal: true
class FilterBestPosts
-
attr_accessor :filtered_posts, :posts
def initialize(topic, filtered_posts, limit, options = {})
@filtered_posts = filtered_posts
@topic = topic
@limit = limit
- options.each do |key, value|
- self.instance_variable_set("@#{key}".to_sym, value)
- end
+ options.each { |key, value| self.instance_variable_set("@#{key}".to_sym, value) }
filter
end
@@ -31,37 +28,41 @@ class FilterBestPosts
def filter_posts_liked_by_moderators
return unless @only_moderator_liked
- liked_by_moderators = PostAction.where(post_id: @filtered_posts.pluck(:id), post_action_type_id: PostActionType.types[:like])
- liked_by_moderators = liked_by_moderators.joins(:user).where('users.moderator').pluck(:post_id)
+ liked_by_moderators =
+ PostAction.where(
+ post_id: @filtered_posts.pluck(:id),
+ post_action_type_id: PostActionType.types[:like],
+ )
+ liked_by_moderators = liked_by_moderators.joins(:user).where("users.moderator").pluck(:post_id)
@filtered_posts = @filtered_posts.where(id: liked_by_moderators)
end
def setup_posts
- @posts = @filtered_posts.order('percent_rank asc, sort_order asc').where("post_number > 1")
+ @posts = @filtered_posts.order("percent_rank asc, sort_order asc").where("post_number > 1")
@posts = @posts.includes(:reply_to_user).includes(:topic).joins(:user).limit(@limit)
end
def filter_posts_based_on_trust_level
- return unless @min_trust_level.try('>', 0)
+ return unless @min_trust_level.try(">", 0)
@posts =
- if @bypass_trust_level_score.try('>', 0)
- @posts.where('COALESCE(users.trust_level,0) >= ? OR posts.score >= ?',
+ if @bypass_trust_level_score.try(">", 0)
+ @posts.where(
+ "COALESCE(users.trust_level,0) >= ? OR posts.score >= ?",
@min_trust_level,
- @bypass_trust_level_score
+ @bypass_trust_level_score,
)
else
- @posts.where('COALESCE(users.trust_level,0) >= ?', @min_trust_level)
+ @posts.where("COALESCE(users.trust_level,0) >= ?", @min_trust_level)
end
end
def filter_posts_based_on_score
- return unless @min_score.try('>', 0)
- @posts = @posts.where('posts.score >= ?', @min_score)
+ return unless @min_score.try(">", 0)
+ @posts = @posts.where("posts.score >= ?", @min_score)
end
def sort_posts
@posts = Post.from(@posts, :posts).order(post_number: :asc)
end
-
end
diff --git a/lib/final_destination.rb b/lib/final_destination.rb
index fa5cbcc06d0..893b38e9c58 100644
--- a/lib/final_destination.rb
+++ b/lib/final_destination.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-require 'socket'
-require 'ipaddr'
-require 'excon'
-require 'rate_limiter'
-require 'url_helper'
+require "socket"
+require "ipaddr"
+require "excon"
+require "rate_limiter"
+require "url_helper"
# Determine the final endpoint for a Web URI, following redirects
class FinalDestination
@@ -30,7 +30,8 @@ class FinalDestination
"HTTPS_DOMAIN_#{domain}"
end
- DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15"
+ DEFAULT_USER_AGENT =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15"
attr_reader :status, :cookie, :status_code, :content_type, :ignored
@@ -53,15 +54,11 @@ class FinalDestination
if @limit > 0
ignore_redirects = [Discourse.base_url_no_prefix]
- if @opts[:ignore_redirects]
- ignore_redirects.concat(@opts[:ignore_redirects])
- end
+ ignore_redirects.concat(@opts[:ignore_redirects]) if @opts[:ignore_redirects]
ignore_redirects.each do |ignore_redirect|
ignore_redirect = uri(ignore_redirect)
- if ignore_redirect.present? && ignore_redirect.hostname
- @ignored << ignore_redirect.hostname
- end
+ @ignored << ignore_redirect.hostname if ignore_redirect.present? && ignore_redirect.hostname
end
end
@@ -74,7 +71,14 @@ class FinalDestination
@timeout = @opts[:timeout] || nil
@preserve_fragment_url = @preserve_fragment_url_hosts.any? { |host| hostname_matches?(host) }
@validate_uri = @opts.fetch(:validate_uri) { true }
- @user_agent = @force_custom_user_agent_hosts.any? { |host| hostname_matches?(host) } ? Onebox.options.user_agent : @default_user_agent
+ @user_agent =
+ (
+ if @force_custom_user_agent_hosts.any? { |host| hostname_matches?(host) }
+ Onebox.options.user_agent
+ else
+ @default_user_agent
+ end
+ )
@stop_at_blocked_pages = @opts[:stop_at_blocked_pages]
end
@@ -107,10 +111,10 @@ class FinalDestination
"User-Agent" => @user_agent,
"Accept" => "*/*",
"Accept-Language" => "*",
- "Host" => @uri.hostname
+ "Host" => @uri.hostname,
}
- result['Cookie'] = @cookie if @cookie
+ result["Cookie"] = @cookie if @cookie
result
end
@@ -119,7 +123,12 @@ class FinalDestination
status_code, response_headers = nil
catch(:done) do
- FinalDestination::HTTP.start(@uri.host, @uri.port, use_ssl: @uri.is_a?(URI::HTTPS), open_timeout: timeout) do |http|
+ FinalDestination::HTTP.start(
+ @uri.host,
+ @uri.port,
+ use_ssl: @uri.is_a?(URI::HTTPS),
+ open_timeout: timeout,
+ ) do |http|
http.read_timeout = timeout
http.request_get(@uri.request_uri, request_headers) do |resp|
status_code = resp.code.to_i
@@ -162,7 +171,8 @@ class FinalDestination
location = "#{@uri.scheme}://#{@uri.host}#{location}" if location[0] == "/"
@uri = uri(location)
- if @uri && redirects == @max_redirects && @https_redirect_ignore_limit && same_uri_but_https?(old_uri, @uri)
+ if @uri && redirects == @max_redirects && @https_redirect_ignore_limit &&
+ same_uri_but_https?(old_uri, @uri)
redirects += 1
@https_redirect_ignore_limit = false
end
@@ -177,7 +187,7 @@ class FinalDestination
return if !@uri
extra = nil
- extra = { 'Cookie' => cookie } if cookie
+ extra = { "Cookie" => cookie } if cookie
get(redirects - 1, extra_headers: extra, &blk)
elsif result == :ok
@@ -223,11 +233,16 @@ class FinalDestination
request_start_time = Time.now
response_body = +""
- request_validator = lambda do |chunk, _remaining_bytes, _total_bytes|
- response_body << chunk
- raise Excon::Errors::ExpectationFailed.new("response size too big: #{@uri.to_s}") if response_body.bytesize > MAX_REQUEST_SIZE_BYTES
- raise Excon::Errors::ExpectationFailed.new("connect timeout reached: #{@uri.to_s}") if Time.now - request_start_time > MAX_REQUEST_TIME_SECONDS
- end
+ request_validator =
+ lambda do |chunk, _remaining_bytes, _total_bytes|
+ response_body << chunk
+ if response_body.bytesize > MAX_REQUEST_SIZE_BYTES
+ raise Excon::Errors::ExpectationFailed.new("response size too big: #{@uri.to_s}")
+ end
+ if Time.now - request_start_time > MAX_REQUEST_TIME_SECONDS
+ raise Excon::Errors::ExpectationFailed.new("connect timeout reached: #{@uri.to_s}")
+ end
+ end
# This technique will only use the first resolved IP
# TODO: Can we standardise this by using FinalDestination::HTTP?
@@ -240,18 +255,20 @@ class FinalDestination
request_uri = @uri.dup
request_uri.hostname = resolved_ip unless Rails.env.test? # WebMock doesn't understand the IP-based requests
- response = Excon.public_send(@http_verb,
- request_uri.to_s,
- read_timeout: timeout,
- connect_timeout: timeout,
- headers: { "Host" => @uri.hostname }.merge(headers),
- middlewares: middlewares,
- response_block: request_validator,
- ssl_verify_peer_host: @uri.hostname
- )
+ response =
+ Excon.public_send(
+ @http_verb,
+ request_uri.to_s,
+ read_timeout: timeout,
+ connect_timeout: timeout,
+ headers: { "Host" => @uri.hostname }.merge(headers),
+ middlewares: middlewares,
+ response_block: request_validator,
+ ssl_verify_peer_host: @uri.hostname,
+ )
if @stop_at_blocked_pages
- if blocked_domain?(@uri) || response.headers['Discourse-No-Onebox'] == "1"
+ if blocked_domain?(@uri) || response.headers["Discourse-No-Onebox"] == "1"
@status = :blocked_page
return
end
@@ -282,7 +299,7 @@ class FinalDestination
end
end
- @content_type = response.headers['Content-Type'] if response.headers.has_key?('Content-Type')
+ @content_type = response.headers["Content-Type"] if response.headers.has_key?("Content-Type")
@status = :resolved
return @uri
when 103, 400, 405, 406, 409, 500, 501
@@ -306,11 +323,11 @@ class FinalDestination
end
response_headers = {}
- if cookie_val = small_headers['set-cookie']
+ if cookie_val = small_headers["set-cookie"]
response_headers[:cookies] = cookie_val
end
- if location_val = small_headers['location']
+ if location_val = small_headers["location"]
response_headers[:location] = location_val.join
end
end
@@ -318,21 +335,20 @@ class FinalDestination
unless response_headers
response_headers = {
cookies: response.data[:cookies] || response.headers[:"set-cookie"],
- location: response.headers[:location]
+ location: response.headers[:location],
}
end
- if (300..399).include?(response_status)
- location = response_headers[:location]
- end
+ location = response_headers[:location] if (300..399).include?(response_status)
if cookies = response_headers[:cookies]
- @cookie = Array.wrap(cookies).map { |c| c.split(';').first.strip }.join('; ')
+ @cookie = Array.wrap(cookies).map { |c| c.split(";").first.strip }.join("; ")
end
if location
redirect_uri = uri(location)
- if @uri.host == redirect_uri.host && (redirect_uri.path =~ /\/login/ || redirect_uri.path =~ /\/session/)
+ if @uri.host == redirect_uri.host &&
+ (redirect_uri.path =~ %r{/login} || redirect_uri.path =~ %r{/session})
@status = :resolved
return @uri
end
@@ -342,7 +358,8 @@ class FinalDestination
location = "#{@uri.scheme}://#{@uri.host}#{location}" if location[0] == "/"
@uri = uri(location)
- if @uri && @limit == @max_redirects && @https_redirect_ignore_limit && same_uri_but_https?(old_uri, @uri)
+ if @uri && @limit == @max_redirects && @https_redirect_ignore_limit &&
+ same_uri_but_https?(old_uri, @uri)
@limit += 1
@https_redirect_ignore_limit = false
end
@@ -376,12 +393,18 @@ class FinalDestination
def validate_uri_format
return false unless @uri && @uri.host
- return false unless ['https', 'http'].include?(@uri.scheme)
- return false if @uri.scheme == 'http' && @uri.port != 80
- return false if @uri.scheme == 'https' && @uri.port != 443
+ return false unless %w[https http].include?(@uri.scheme)
+ return false if @uri.scheme == "http" && @uri.port != 80
+ return false if @uri.scheme == "https" && @uri.port != 443
# Disallow IP based crawling
- (IPAddr.new(@uri.hostname) rescue nil).nil?
+ (
+ begin
+ IPAddr.new(@uri.hostname)
+ rescue StandardError
+ nil
+ end
+ ).nil?
end
def hostname
@@ -392,11 +415,11 @@ class FinalDestination
url = uri(url)
if @uri&.hostname.present? && url&.hostname.present?
- hostname_parts = url.hostname.split('.')
- has_wildcard = hostname_parts.first == '*'
+ hostname_parts = url.hostname.split(".")
+ has_wildcard = hostname_parts.first == "*"
if has_wildcard
- @uri.hostname.end_with?(hostname_parts[1..-1].join('.'))
+ @uri.hostname.end_with?(hostname_parts[1..-1].join("."))
else
@uri.hostname == url.hostname
end
@@ -413,7 +436,7 @@ class FinalDestination
Rails.logger.public_send(
log_level,
- "#{RailsMultisite::ConnectionManagement.current_db}: #{message}"
+ "#{RailsMultisite::ConnectionManagement.current_db}: #{message}",
)
end
@@ -425,15 +448,12 @@ class FinalDestination
headers_subset = Struct.new(:location, :set_cookie).new
safe_session(uri) do |http|
- headers = request_headers.merge(
- 'Accept-Encoding' => 'gzip',
- 'Host' => uri.host
- )
+ headers = request_headers.merge("Accept-Encoding" => "gzip", "Host" => uri.host)
req = FinalDestination::HTTP::Get.new(uri.request_uri, headers)
http.request(req) do |resp|
- headers_subset.set_cookie = resp['Set-Cookie']
+ headers_subset.set_cookie = resp["Set-Cookie"]
if @stop_at_blocked_pages
dont_onebox = resp["Discourse-No-Onebox"] == "1"
@@ -444,7 +464,7 @@ class FinalDestination
end
if Net::HTTPRedirection === resp
- headers_subset.location = resp['location']
+ headers_subset.location = resp["location"]
result = :redirect, headers_subset
end
@@ -471,9 +491,7 @@ class FinalDestination
end
result = :ok, headers_subset
else
- catch(:done) do
- yield resp, nil, nil
- end
+ catch(:done) { yield resp, nil, nil }
end
end
end
@@ -490,7 +508,12 @@ class FinalDestination
end
def safe_session(uri)
- FinalDestination::HTTP.start(uri.host, uri.port, use_ssl: (uri.scheme == "https"), open_timeout: timeout) do |http|
+ FinalDestination::HTTP.start(
+ uri.host,
+ uri.port,
+ use_ssl: (uri.scheme == "https"),
+ open_timeout: timeout,
+ ) do |http|
http.read_timeout = timeout
yield http
end
@@ -508,14 +531,14 @@ class FinalDestination
def fetch_canonical_url(body)
return if body.blank?
- canonical_element = Nokogiri::HTML5(body).at("link[rel='canonical']")
+ canonical_element = Nokogiri.HTML5(body).at("link[rel='canonical']")
return if canonical_element.nil?
- canonical_uri = uri(canonical_element['href'])
+ canonical_uri = uri(canonical_element["href"])
return if canonical_uri.blank?
return canonical_uri if canonical_uri.host.present?
parts = [@uri.host, canonical_uri.to_s]
- complete_url = canonical_uri.to_s.starts_with?('/') ? parts.join('') : parts.join('/')
+ complete_url = canonical_uri.to_s.starts_with?("/") ? parts.join("") : parts.join("/")
complete_url = "#{@uri.scheme}://#{complete_url}" if @uri.scheme
uri(complete_url)
@@ -528,8 +551,7 @@ class FinalDestination
def same_uri_but_https?(before, after)
before = before.to_s
after = after.to_s
- before.start_with?("http://") &&
- after.start_with?("https://") &&
+ before.start_with?("http://") && after.start_with?("https://") &&
before.sub("http://", "") == after.sub("https://", "")
end
end
diff --git a/lib/final_destination/resolver.rb b/lib/final_destination/resolver.rb
index f809099d4d2..843a6a313bc 100644
--- a/lib/final_destination/resolver.rb
+++ b/lib/final_destination/resolver.rb
@@ -39,18 +39,19 @@ class FinalDestination::Resolver
def self.ensure_lookup_thread
return if @thread&.alive?
- @thread = Thread.new do
- while true
- @queue.deq
- @error = nil
- begin
- @result = Addrinfo.getaddrinfo(@lookup, 80, nil, :STREAM).map(&:ip_address)
- rescue => e
- @error = e
+ @thread =
+ Thread.new do
+ while true
+ @queue.deq
+ @error = nil
+ begin
+ @result = Addrinfo.getaddrinfo(@lookup, 80, nil, :STREAM).map(&:ip_address)
+ rescue => e
+ @error = e
+ end
+ @parent.wakeup
end
- @parent.wakeup
end
- end
@thread.name = "final-destination_resolver_thread"
end
end
diff --git a/lib/final_destination/ssrf_detector.rb b/lib/final_destination/ssrf_detector.rb
index aeb01d9ec90..0d06306ce8f 100644
--- a/lib/final_destination/ssrf_detector.rb
+++ b/lib/final_destination/ssrf_detector.rb
@@ -2,8 +2,10 @@
class FinalDestination
module SSRFDetector
- class DisallowedIpError < SocketError; end
- class LookupFailedError < SocketError; end
+ class DisallowedIpError < SocketError
+ end
+ class LookupFailedError < SocketError
+ end
def self.standard_private_ranges
@private_ranges ||= [
diff --git a/lib/flag_settings.rb b/lib/flag_settings.rb
index da86d2c1b43..d88c01e35af 100644
--- a/lib/flag_settings.rb
+++ b/lib/flag_settings.rb
@@ -1,13 +1,12 @@
# frozen_string_literal: true
class FlagSettings
-
attr_reader(
:without_custom_types,
:notify_types,
:topic_flag_types,
:auto_action_types,
- :custom_types
+ :custom_types,
)
def initialize
@@ -39,5 +38,4 @@ class FlagSettings
def flag_types
@all_flag_types
end
-
end
diff --git a/lib/freedom_patches/better_handlebars_errors.rb b/lib/freedom_patches/better_handlebars_errors.rb
index c308f744106..a11eb271200 100644
--- a/lib/freedom_patches/better_handlebars_errors.rb
+++ b/lib/freedom_patches/better_handlebars_errors.rb
@@ -3,9 +3,8 @@
module Ember
module Handlebars
class Template
-
# Wrap in an IIFE in development mode to get the correct filename
- def compile_ember_handlebars(string, ember_template = 'Handlebars', options = nil)
+ def compile_ember_handlebars(string, ember_template = "Handlebars", options = nil)
if ::Rails.env.development?
"(function() { try { return Ember.#{ember_template}.compile(#{indent(string).inspect}); } catch(err) { throw err; } })()"
else
diff --git a/lib/freedom_patches/cose_rsapkcs1.rb b/lib/freedom_patches/cose_rsapkcs1.rb
index f6964e1835f..55b639b5a5b 100644
--- a/lib/freedom_patches/cose_rsapkcs1.rb
+++ b/lib/freedom_patches/cose_rsapkcs1.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'cose'
-require 'openssl/signature_algorithm/rsapkcs1'
+require "cose"
+require "openssl/signature_algorithm/rsapkcs1"
# 'cose' gem does not implement all algorithms from the Web Authentication
# (WebAuthn) standard specification. This patch implements one of the missing
@@ -38,11 +38,11 @@ module COSE
when OpenSSL::PKey::RSA
key
else
- raise(COSE::Error, 'Incompatible key for algorithm')
+ raise(COSE::Error, "Incompatible key for algorithm")
end
end
end
- register(RSAPKCS1.new(-257, 'RS256', hash_function: 'SHA256'))
+ register(RSAPKCS1.new(-257, "RS256", hash_function: "SHA256"))
end
end
diff --git a/lib/freedom_patches/fast_pluck.rb b/lib/freedom_patches/fast_pluck.rb
index ef467c56664..b33e7a2723d 100644
--- a/lib/freedom_patches/fast_pluck.rb
+++ b/lib/freedom_patches/fast_pluck.rb
@@ -5,7 +5,6 @@
#
#
class ActiveRecord::Relation
-
# Note: In discourse, the following code is included in lib/sql_builder.rb
#
# class RailsDateTimeDecoder < PG::SimpleDecoder
@@ -43,7 +42,8 @@ class ActiveRecord::Relation
end
def pluck(*column_names)
- if loaded? && (column_names.map(&:to_s) - @klass.attribute_names - @klass.attribute_aliases.keys).empty?
+ if loaded? &&
+ (column_names.map(&:to_s) - @klass.attribute_names - @klass.attribute_aliases.keys).empty?
return records.pluck(*column_names)
end
@@ -55,10 +55,12 @@ class ActiveRecord::Relation
relation.select_values = column_names
- klass.connection.select_raw(relation.arel) do |result, _|
- result.type_map = DB.type_map
- result.nfields == 1 ? result.column_values(0) : result.values
- end
+ klass
+ .connection
+ .select_raw(relation.arel) do |result, _|
+ result.type_map = DB.type_map
+ result.nfields == 1 ? result.column_values(0) : result.values
+ end
end
end
end
diff --git a/lib/freedom_patches/inflector_backport.rb b/lib/freedom_patches/inflector_backport.rb
index 67547cddadb..7b1d02d4048 100644
--- a/lib/freedom_patches/inflector_backport.rb
+++ b/lib/freedom_patches/inflector_backport.rb
@@ -6,7 +6,6 @@
module ActiveSupport
module Inflector
-
LRU_CACHE_SIZE = 200
LRU_CACHES = []
@@ -22,26 +21,30 @@ module ActiveSupport
uncached = "#{method_name}_without_cache"
alias_method uncached, method_name
- m = define_method(method_name) do |*arguments|
- # this avoids recursive locks
- found = true
- data = cache.fetch(arguments) { found = false }
- unless found
- cache[arguments] = data = public_send(uncached, *arguments)
+ m =
+ define_method(method_name) do |*arguments|
+ # this avoids recursive locks
+ found = true
+ data = cache.fetch(arguments) { found = false }
+ cache[arguments] = data = public_send(uncached, *arguments) unless found
+ # so cache is never corrupted
+ data.dup
end
- # so cache is never corrupted
- data.dup
- end
# https://bugs.ruby-lang.org/issues/16897
- if Module.respond_to?(:ruby2_keywords, true)
- ruby2_keywords(m)
- end
+ ruby2_keywords(m) if Module.respond_to?(:ruby2_keywords, true)
end
end
- memoize :pluralize, :singularize, :camelize, :underscore, :humanize,
- :titleize, :tableize, :classify, :foreign_key
+ memoize :pluralize,
+ :singularize,
+ :camelize,
+ :underscore,
+ :humanize,
+ :titleize,
+ :tableize,
+ :classify,
+ :foreign_key
end
end
diff --git a/lib/freedom_patches/ip_addr.rb b/lib/freedom_patches/ip_addr.rb
index e9b118b8d06..9c7053d66c2 100644
--- a/lib/freedom_patches/ip_addr.rb
+++ b/lib/freedom_patches/ip_addr.rb
@@ -1,29 +1,28 @@
# frozen_string_literal: true
class IPAddr
-
def self.handle_wildcards(val)
return if val.blank?
- num_wildcards = val.count('*')
+ num_wildcards = val.count("*")
return val if num_wildcards == 0
# strip ranges like "/16" from the end if present
- v = val.gsub(/\/.*/, '')
+ v = val.gsub(%r{/.*}, "")
- return if v[v.index('*')..-1] =~ /[^\.\*]/
+ return if v[v.index("*")..-1] =~ /[^\.\*]/
- parts = v.split('.')
- (4 - parts.size).times { parts << '*' } # support strings like 192.*
- v = parts.join('.')
+ parts = v.split(".")
+ (4 - parts.size).times { parts << "*" } # support strings like 192.*
+ v = parts.join(".")
- "#{v.tr('*', '0')}/#{32 - (v.count('*') * 8)}"
+ "#{v.tr("*", "0")}/#{32 - (v.count("*") * 8)}"
end
def to_cidr_s
if @addr
- mask = @mask_addr.to_s(2).count('1')
+ mask = @mask_addr.to_s(2).count("1")
if mask == 32
to_s
else
@@ -33,5 +32,4 @@ class IPAddr
nil
end
end
-
end
diff --git a/lib/freedom_patches/mail_disable_starttls.rb b/lib/freedom_patches/mail_disable_starttls.rb
index 45daba893a6..a8a60bda86e 100644
--- a/lib/freedom_patches/mail_disable_starttls.rb
+++ b/lib/freedom_patches/mail_disable_starttls.rb
@@ -11,9 +11,7 @@ module FreedomPatches
def build_smtp_session
super.tap do |smtp|
unless settings[:enable_starttls_auto]
- if smtp.respond_to?(:disable_starttls)
- smtp.disable_starttls
- end
+ smtp.disable_starttls if smtp.respond_to?(:disable_starttls)
end
end
end
diff --git a/lib/freedom_patches/rails4.rb b/lib/freedom_patches/rails4.rb
index 894c3dad904..806813b7c87 100644
--- a/lib/freedom_patches/rails4.rb
+++ b/lib/freedom_patches/rails4.rb
@@ -5,11 +5,13 @@
# Backporting a fix to rails itself may get too complex
module FreedomPatches
module Rails4
-
- def self.distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
- options = {
- scope: :'datetime.distance_in_words',
- }.merge!(options)
+ def self.distance_of_time_in_words(
+ from_time,
+ to_time = 0,
+ include_seconds = false,
+ options = {}
+ )
+ options = { scope: :"datetime.distance_in_words" }.merge!(options)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
@@ -20,49 +22,68 @@ module FreedomPatches
I18n.with_options locale: options[:locale], scope: options[:scope] do |locale|
case distance_in_minutes
when 0..1
- return distance_in_minutes == 0 ?
- locale.t(:less_than_x_minutes, count: 1) :
- locale.t(:x_minutes, count: distance_in_minutes) unless include_seconds
-
- case distance_in_seconds
- when 0..4 then locale.t :less_than_x_seconds, count: 5
- when 5..9 then locale.t :less_than_x_seconds, count: 10
- when 10..19 then locale.t :less_than_x_seconds, count: 20
- when 20..39 then locale.t :half_a_minute
- when 40..59 then locale.t :less_than_x_minutes, count: 1
- else locale.t :x_minutes, count: 1
- end
+ unless include_seconds
+ return(
+ (
+ if distance_in_minutes == 0
+ locale.t(:less_than_x_minutes, count: 1)
+ else
+ locale.t(:x_minutes, count: distance_in_minutes)
+ end
+ )
+ )
+ end
- when 2..44 then locale.t :x_minutes, count: distance_in_minutes
- when 45..89 then locale.t :about_x_hours, count: 1
- when 90..1439 then locale.t :about_x_hours, count: (distance_in_minutes.to_f / 60.0).round
- when 1440..2519 then locale.t :x_days, count: 1
+ case distance_in_seconds
+ when 0..4
+ locale.t :less_than_x_seconds, count: 5
+ when 5..9
+ locale.t :less_than_x_seconds, count: 10
+ when 10..19
+ locale.t :less_than_x_seconds, count: 20
+ when 20..39
+ locale.t :half_a_minute
+ when 40..59
+ locale.t :less_than_x_minutes, count: 1
+ else
+ locale.t :x_minutes, count: 1
+ end
+ when 2..44
+ locale.t :x_minutes, count: distance_in_minutes
+ when 45..89
+ locale.t :about_x_hours, count: 1
+ when 90..1439
+ locale.t :about_x_hours, count: (distance_in_minutes.to_f / 60.0).round
+ when 1440..2519
+ locale.t :x_days, count: 1
# this is were we diverge from Rails
- when 2520..129599 then locale.t :x_days, count: (distance_in_minutes.to_f / 1440.0).round
- when 129600..525599 then locale.t :x_months, count: (distance_in_minutes.to_f / 43200.0).round
- else
+ when 2520..129_599
+ locale.t :x_days, count: (distance_in_minutes.to_f / 1440.0).round
+ when 129_600..525_599
+ locale.t :x_months, count: (distance_in_minutes.to_f / 43200.0).round
+ else
fyear = from_time.year
- fyear += 1 if from_time.month >= 3
- tyear = to_time.year
- tyear -= 1 if to_time.month < 3
- leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count { |x| Date.leap?(x) }
- minute_offset_for_leap_year = leap_years * 1440
- # Discount the leap year days when calculating year distance.
- # e.g. if there are 20 leap year days between 2 dates having the same day
- # and month then the based on 365 days calculation
- # the distance in years will come out to over 80 years when in written
- # english it would read better as about 80 years.
- minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
- remainder = (minutes_with_offset % 525600)
- distance_in_years = (minutes_with_offset / 525600)
- if remainder < 131400
- locale.t(:about_x_years, count: distance_in_years)
- elsif remainder < 394200
- locale.t(:over_x_years, count: distance_in_years)
- else
- locale.t(:almost_x_years, count: distance_in_years + 1)
- end
+ fyear += 1 if from_time.month >= 3
+ tyear = to_time.year
+ tyear -= 1 if to_time.month < 3
+ leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count { |x| Date.leap?(x) }
+ minute_offset_for_leap_year = leap_years * 1440
+ # Discount the leap year days when calculating year distance.
+ # e.g. if there are 20 leap year days between 2 dates having the same day
+ # and month then the based on 365 days calculation
+ # the distance in years will come out to over 80 years when in written
+ # english it would read better as about 80 years.
+ minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
+ remainder = (minutes_with_offset % 525_600)
+ distance_in_years = (minutes_with_offset / 525_600)
+ if remainder < 131_400
+ locale.t(:about_x_years, count: distance_in_years)
+ elsif remainder < 394_200
+ locale.t(:over_x_years, count: distance_in_years)
+ else
+ locale.t(:almost_x_years, count: distance_in_years + 1)
+ end
end
end
end
diff --git a/lib/freedom_patches/rails_multisite.rb b/lib/freedom_patches/rails_multisite.rb
index 99244669d7e..0a78baaf320 100644
--- a/lib/freedom_patches/rails_multisite.rb
+++ b/lib/freedom_patches/rails_multisite.rb
@@ -19,12 +19,10 @@ module RailsMultisite
handler
end
- ActiveRecord::Base.connected_to(role: reading_role) do
- yield(db) if block_given?
- end
+ ActiveRecord::Base.connected_to(role: reading_role) { yield(db) if block_given? }
rescue => e
- STDERR.puts "URGENT: Failed to initialize site #{db}: "\
- "#{e.class} #{e.message}\n#{e.backtrace.join("\n")}"
+ STDERR.puts "URGENT: Failed to initialize site #{db}: " \
+ "#{e.class} #{e.message}\n#{e.backtrace.join("\n")}"
# the show must go on, don't stop startup if multisite fails
end
@@ -34,11 +32,7 @@ module RailsMultisite
class DiscoursePatches
def self.config
- {
- db_lookup: lambda do |env|
- env["PATH_INFO"] == "/srv/status" ? "default" : nil
- end
- }
+ { db_lookup: lambda { |env| env["PATH_INFO"] == "/srv/status" ? "default" : nil } }
end
end
end
diff --git a/lib/freedom_patches/safe_buffer.rb b/lib/freedom_patches/safe_buffer.rb
index 5bc2feb01e4..efc6880b6d9 100644
--- a/lib/freedom_patches/safe_buffer.rb
+++ b/lib/freedom_patches/safe_buffer.rb
@@ -12,7 +12,8 @@ module FreedomPatches
rescue Encoding::CompatibilityError
raise if raise_encoding_err
- encoding_diags = +"internal encoding #{Encoding.default_internal}, external encoding #{Encoding.default_external}"
+ encoding_diags =
+ +"internal encoding #{Encoding.default_internal}, external encoding #{Encoding.default_external}"
if encoding != Encoding::UTF_8
encoding_diags << " my encoding is #{encoding} "
force_encoding("UTF-8")
@@ -20,12 +21,16 @@ module FreedomPatches
encode!("utf-16", "utf-8", invalid: :replace)
encode!("utf-8", "utf-16")
end
- Rails.logger.warn("Encountered a non UTF-8 string in SafeBuffer - #{self} - #{encoding_diags}")
+ Rails.logger.warn(
+ "Encountered a non UTF-8 string in SafeBuffer - #{self} - #{encoding_diags}",
+ )
end
if value.encoding != Encoding::UTF_8
encoding_diags << " attempted to append encoding #{value.encoding} "
value = value.dup.force_encoding("UTF-8").scrub
- Rails.logger.warn("Attempted to concat a non UTF-8 string in SafeBuffer - #{value} - #{encoding_diags}")
+ Rails.logger.warn(
+ "Attempted to concat a non UTF-8 string in SafeBuffer - #{value} - #{encoding_diags}",
+ )
end
concat(value, _raise = true)
end
diff --git a/lib/freedom_patches/safe_migrations.rb b/lib/freedom_patches/safe_migrations.rb
index cdf989fdd5b..61f9fe47540 100644
--- a/lib/freedom_patches/safe_migrations.rb
+++ b/lib/freedom_patches/safe_migrations.rb
@@ -5,7 +5,7 @@
# which rake:multisite_migrate uses
#
# The protection is only needed in Dev and Test
-if ENV['RAILS_ENV'] != "production"
- require_dependency 'migration/safe_migrate'
+if ENV["RAILS_ENV"] != "production"
+ require_dependency "migration/safe_migrate"
Migration::SafeMigrate.patch_active_record!
end
diff --git a/lib/freedom_patches/schema_migration_details.rb b/lib/freedom_patches/schema_migration_details.rb
index 6b72cc8fdcf..c02d9c51ace 100644
--- a/lib/freedom_patches/schema_migration_details.rb
+++ b/lib/freedom_patches/schema_migration_details.rb
@@ -5,9 +5,7 @@ module FreedomPatches
def exec_migration(conn, direction)
rval = nil
- time = Benchmark.measure do
- rval = super
- end
+ time = Benchmark.measure { rval = super }
sql = <<SQL
INSERT INTO schema_migration_details(
@@ -32,16 +30,23 @@ module FreedomPatches
SQL
hostname = Discourse.os_hostname
- sql = ActiveRecord::Base.public_send(:sanitize_sql_array, [sql, {
- version: version || "",
- duration: (time.real * 1000).to_i,
- hostname: hostname,
- name: name,
- git_version: Discourse.git_version,
- created_at: Time.zone.now,
- direction: direction.to_s,
- rails_version: Rails.version
- }])
+ sql =
+ ActiveRecord::Base.public_send(
+ :sanitize_sql_array,
+ [
+ sql,
+ {
+ version: version || "",
+ duration: (time.real * 1000).to_i,
+ hostname: hostname,
+ name: name,
+ git_version: Discourse.git_version,
+ created_at: Time.zone.now,
+ direction: direction.to_s,
+ rails_version: Rails.version,
+ },
+ ],
+ )
conn.execute(sql)
diff --git a/lib/freedom_patches/sprockets_patches.rb b/lib/freedom_patches/sprockets_patches.rb
index d0cb960d306..b9fb4974143 100644
--- a/lib/freedom_patches/sprockets_patches.rb
+++ b/lib/freedom_patches/sprockets_patches.rb
@@ -20,7 +20,10 @@ module FreedomPatches
end
if Rails.env.development? || Rails.env.test?
- Sprockets.register_bundle_metadata_reducer 'application/javascript', :data, proc { +"" }, method(:concat_javascript_sources)
+ Sprockets.register_bundle_metadata_reducer "application/javascript",
+ :data,
+ proc { +"" },
+ method(:concat_javascript_sources)
end
end
end
diff --git a/lib/freedom_patches/translate_accelerator.rb b/lib/freedom_patches/translate_accelerator.rb
index 9fc7bf77493..b13464012b5 100644
--- a/lib/freedom_patches/translate_accelerator.rb
+++ b/lib/freedom_patches/translate_accelerator.rb
@@ -11,7 +11,6 @@
# This patch depends on the convention that locale yml files must be named [locale_name].yml
module I18n
-
# this accelerates translation a tiny bit (halves the time it takes)
class << self
alias_method :translate_no_cache, :translate
@@ -45,10 +44,7 @@ module I18n
# load plural rules from plugins
DiscoursePluginRegistry.locales.each do |plugin_locale, options|
if options[:plural]
- I18n.backend.store_translations(
- plugin_locale,
- i18n: { plural: options[:plural] }
- )
+ I18n.backend.store_translations(plugin_locale, i18n: { plural: options[:plural] })
end
end
end
@@ -57,8 +53,12 @@ module I18n
I18n.backend.load_translations(I18n.load_path.grep(/\.#{Regexp.escape locale}\.yml$/))
if Discourse.allow_dev_populate?
- I18n.backend.load_translations(I18n.load_path.grep(/.*faker.*\/#{Regexp.escape locale}\.yml$/))
- I18n.backend.load_translations(I18n.load_path.grep(/.*faker.*\/#{Regexp.escape locale}\/.*\.yml$/))
+ I18n.backend.load_translations(
+ I18n.load_path.grep(%r{.*faker.*/#{Regexp.escape locale}\.yml$}),
+ )
+ I18n.backend.load_translations(
+ I18n.load_path.grep(%r{.*faker.*/#{Regexp.escape locale}/.*\.yml$}),
+ )
end
@loaded_locales << locale
@@ -93,11 +93,7 @@ module I18n
end
def add_if_matches(translations, results, regexp)
- translations.each do |key, value|
- if key =~ regexp || value =~ regexp
- results[key] = value
- end
- end
+ translations.each { |key, value| results[key] = value if key =~ regexp || value =~ regexp }
end
def ensure_loaded!(locale)
@@ -115,7 +111,8 @@ module I18n
@overrides_enabled = true
end
- class MissingTranslation; end
+ class MissingTranslation
+ end
def translate_no_override(key, options)
# note we skip cache for :format and :count
@@ -129,9 +126,7 @@ module I18n
locale = dup_options.delete(:locale)
end
- if dup_options.present?
- return translate_no_cache(key, **options)
- end
+ return translate_no_cache(key, **options) if dup_options.present?
locale ||= config.locale
locale = locale.to_sym
@@ -139,13 +134,14 @@ module I18n
@cache ||= LruRedux::ThreadSafeCache.new(LRU_CACHE_SIZE)
k = "#{key}#{locale}#{config.backend.object_id}"
- val = @cache.getset(k) do
- begin
- translate_no_cache(key, locale: locale, raise: true).freeze
- rescue I18n::MissingTranslationData
- MissingTranslation
+ val =
+ @cache.getset(k) do
+ begin
+ translate_no_cache(key, locale: locale, raise: true).freeze
+ rescue I18n::MissingTranslationData
+ MissingTranslation
+ end
end
- end
if val != MissingTranslation
val
@@ -170,7 +166,8 @@ module I18n
if !by_site.has_key?(locale)
# Load overrides
- translations_overrides = TranslationOverride.where(locale: locale).pluck(:translation_key, :value)
+ translations_overrides =
+ TranslationOverride.where(locale: locale).pluck(:translation_key, :value)
if translations_overrides.empty?
by_site[locale] = {}
@@ -196,9 +193,9 @@ module I18n
def translate(*args)
execute_reload if @requires_reload
- options = args.last.is_a?(Hash) ? args.pop.dup : {}
- key = args.shift
- locale = (options[:locale] || config.locale).to_sym
+ options = args.last.is_a?(Hash) ? args.pop.dup : {}
+ key = args.shift
+ locale = (options[:locale] || config.locale).to_sym
load_locale(locale) unless @loaded_locales.include?(locale)
@@ -222,9 +219,7 @@ module I18n
options[:overrides] = overrides
# I18n likes to use throw...
- catch(:exception) do
- return backend.translate(locale, key, options)
- end
+ catch(:exception) { return backend.translate(locale, key, options) }
end
end
diff --git a/lib/gaps.rb b/lib/gaps.rb
index 6b6dac16bb1..517f1e99c92 100644
--- a/lib/gaps.rb
+++ b/lib/gaps.rb
@@ -8,7 +8,6 @@
# want to display the gap once.
#
class Gaps
-
attr_reader :before, :after
def initialize(subset, original)
@@ -31,8 +30,7 @@ class Gaps
gaps = {}
current_gap = []
- while
- e1 = @subset[i]
+ while e1 = @subset[i]
e2 = @original[j]
if (e1 == e2)
@@ -52,5 +50,4 @@ class Gaps
@after[@subset[i - 1]] = @original[j..-1] if j < @original.size
end
-
end
diff --git a/lib/git_url.rb b/lib/git_url.rb
index 9d600cd7a7b..9410c1d3f86 100644
--- a/lib/git_url.rb
+++ b/lib/git_url.rb
@@ -10,7 +10,7 @@ module GitUrl
end
if url.start_with?("https://github.com/") && !url.end_with?(".git")
- url = url.gsub(/\/$/, '')
+ url = url.gsub(%r{/$}, "")
url += ".git"
end
diff --git a/lib/global_path.rb b/lib/global_path.rb
index a2f956476da..318aa346f30 100644
--- a/lib/global_path.rb
+++ b/lib/global_path.rb
@@ -10,11 +10,9 @@ module GlobalPath
end
def upload_cdn_path(p)
- if SiteSetting.Upload.s3_cdn_url.present?
- p = Discourse.store.cdn_url(p)
- end
+ p = Discourse.store.cdn_url(p) if SiteSetting.Upload.s3_cdn_url.present?
- (p =~ /^http/ || p =~ /^\/\//) ? p : cdn_path(p)
+ (p =~ /^http/ || p =~ %r{^//}) ? p : cdn_path(p)
end
def cdn_relative_path(path)
diff --git a/lib/group_email_credentials_check.rb b/lib/group_email_credentials_check.rb
index 753429ed820..85e044ab93a 100644
--- a/lib/group_email_credentials_check.rb
+++ b/lib/group_email_credentials_check.rb
@@ -17,7 +17,7 @@ class GroupEmailCredentialsCheck
host: group.smtp_server,
port: group.smtp_port,
username: group.email_username,
- password: group.email_password
+ password: group.email_password,
)
end
end
@@ -30,7 +30,7 @@ class GroupEmailCredentialsCheck
host: group.smtp_server,
port: group.smtp_port,
username: group.email_username,
- password: group.email_password
+ password: group.email_password,
)
end
end
@@ -48,11 +48,13 @@ class GroupEmailCredentialsCheck
group_id: group.id,
group_name: group.name,
group_full_name: group.full_name,
- message: EmailSettingsExceptionHandler.friendly_exception_message(err, group.smtp_server)
+ message: EmailSettingsExceptionHandler.friendly_exception_message(err, group.smtp_server),
}
rescue => err
Discourse.warn_exception(
- err, message: "Unexpected error when checking SMTP credentials for group #{group.id} (#{group.name})."
+ err,
+ message:
+ "Unexpected error when checking SMTP credentials for group #{group.id} (#{group.name}).",
)
nil
end
diff --git a/lib/guardian.rb b/lib/guardian.rb
index e6a4ad76ac1..1a9b2dd52f3 100644
--- a/lib/guardian.rb
+++ b/lib/guardian.rb
@@ -1,14 +1,14 @@
# frozen_string_literal: true
-require 'guardian/category_guardian'
-require 'guardian/ensure_magic'
-require 'guardian/post_guardian'
-require 'guardian/bookmark_guardian'
-require 'guardian/topic_guardian'
-require 'guardian/user_guardian'
-require 'guardian/post_revision_guardian'
-require 'guardian/group_guardian'
-require 'guardian/tag_guardian'
+require "guardian/category_guardian"
+require "guardian/ensure_magic"
+require "guardian/post_guardian"
+require "guardian/bookmark_guardian"
+require "guardian/topic_guardian"
+require "guardian/user_guardian"
+require "guardian/post_revision_guardian"
+require "guardian/group_guardian"
+require "guardian/tag_guardian"
# The guardian is responsible for confirming access to various site resources and operations
class Guardian
@@ -89,7 +89,7 @@ class Guardian
def user
@user.presence
end
- alias :current_user :user
+ alias current_user user
def anonymous?
!authenticated?
@@ -127,7 +127,9 @@ class Guardian
if @category_group_moderator_groups.key?(reviewable_by_group_id)
@category_group_moderator_groups[reviewable_by_group_id]
else
- @category_group_moderator_groups[reviewable_by_group_id] = category_group_moderator_scope.exists?("categories.id": category.id)
+ @category_group_moderator_groups[
+ reviewable_by_group_id
+ ] = category_group_moderator_scope.exists?("categories.id": category.id)
end
end
@@ -136,16 +138,14 @@ class Guardian
end
def is_developer?
- @user &&
- is_admin? &&
- (
- Rails.env.development? ||
- Developer.user_ids.include?(@user.id) ||
+ @user && is_admin? &&
(
- Rails.configuration.respond_to?(:developer_emails) &&
- Rails.configuration.developer_emails.include?(@user.email)
+ Rails.env.development? || Developer.user_ids.include?(@user.id) ||
+ (
+ Rails.configuration.respond_to?(:developer_emails) &&
+ Rails.configuration.developer_emails.include?(@user.email)
+ )
)
- )
end
def is_staged?
@@ -203,12 +203,13 @@ class Guardian
end
def can_moderate?(obj)
- obj && authenticated? && !is_silenced? && (
- is_staff? ||
- (obj.is_a?(Topic) && @user.has_trust_level?(TrustLevel[4]) && can_see_topic?(obj))
- )
+ obj && authenticated? && !is_silenced? &&
+ (
+ is_staff? ||
+ (obj.is_a?(Topic) && @user.has_trust_level?(TrustLevel[4]) && can_see_topic?(obj))
+ )
end
- alias :can_see_flags? :can_moderate?
+ alias can_see_flags? can_moderate?
def can_tag?(topic)
return false if topic.blank?
@@ -229,9 +230,7 @@ class Guardian
end
def can_delete_reviewable_queued_post?(reviewable)
- reviewable.present? &&
- authenticated? &&
- reviewable.created_by_id == @user.id
+ reviewable.present? && authenticated? && reviewable.created_by_id == @user.id
end
def can_see_group?(group)
@@ -243,7 +242,9 @@ class Guardian
return true if is_admin? || group.members_visibility_level == Group.visibility_levels[:public]
return true if is_staff? && group.members_visibility_level == Group.visibility_levels[:staff]
return true if is_staff? && group.members_visibility_level == Group.visibility_levels[:members]
- return true if authenticated? && group.members_visibility_level == Group.visibility_levels[:logged_on_users]
+ if authenticated? && group.members_visibility_level == Group.visibility_levels[:logged_on_users]
+ return true
+ end
return false if user.blank?
return false unless membership = GroupUser.find_by(group_id: group.id, user_id: user.id)
@@ -257,10 +258,19 @@ class Guardian
def can_see_groups?(groups)
return false if groups.blank?
- return true if is_admin? || groups.all? { |g| g.visibility_level == Group.visibility_levels[:public] }
- return true if is_staff? && groups.all? { |g| g.visibility_level == Group.visibility_levels[:staff] }
- return true if is_staff? && groups.all? { |g| g.visibility_level == Group.visibility_levels[:members] }
- return true if authenticated? && groups.all? { |g| g.visibility_level == Group.visibility_levels[:logged_on_users] }
+ if is_admin? || groups.all? { |g| g.visibility_level == Group.visibility_levels[:public] }
+ return true
+ end
+ if is_staff? && groups.all? { |g| g.visibility_level == Group.visibility_levels[:staff] }
+ return true
+ end
+ if is_staff? && groups.all? { |g| g.visibility_level == Group.visibility_levels[:members] }
+ return true
+ end
+ if authenticated? &&
+ groups.all? { |g| g.visibility_level == Group.visibility_levels[:logged_on_users] }
+ return true
+ end
return false if user.blank?
memberships = GroupUser.where(group: groups, user_id: user.id).pluck(:owner)
@@ -277,7 +287,8 @@ class Guardian
return false if groups.blank?
requested_group_ids = groups.map(&:id) # Can't use pluck, groups could be a regular array
- matching_group_ids = Group.where(id: requested_group_ids).members_visible_groups(user).pluck(:id)
+ matching_group_ids =
+ Group.where(id: requested_group_ids).members_visible_groups(user).pluck(:id)
matching_group_ids.sort == requested_group_ids.sort
end
@@ -285,12 +296,10 @@ class Guardian
# Can we impersonate this user?
def can_impersonate?(target)
target &&
-
- # You must be an admin to impersonate
- is_admin? &&
-
- # You may not impersonate other admins unless you are a dev
- (!target.admin? || is_developer?)
+ # You must be an admin to impersonate
+ is_admin? &&
+ # You may not impersonate other admins unless you are a dev
+ (!target.admin? || is_developer?)
# Additionally, you may not impersonate yourself;
# but the two tests for different admin statuses
@@ -313,7 +322,7 @@ class Guardian
def can_suspend?(user)
user && is_staff? && user.regular?
end
- alias :can_deactivate? :can_suspend?
+ alias can_deactivate? can_suspend?
def can_revoke_admin?(admin)
can_administer_user?(admin) && admin.admin?
@@ -337,10 +346,13 @@ class Guardian
return true if title.empty? # A title set to '(none)' in the UI is an empty string
return false if user != @user
- return true if user.badges
- .where(allow_title: true)
- .pluck(:name)
- .any? { |name| Badge.display_name(name) == title }
+ if user
+ .badges
+ .where(allow_title: true)
+ .pluck(:name)
+ .any? { |name| Badge.display_name(name) == title }
+ return true
+ end
user.groups.where(title: title).exists?
end
@@ -349,13 +361,13 @@ class Guardian
return false if !user || !group_id
group = Group.find_by(id: group_id.to_i)
- user.group_ids.include?(group_id.to_i) &&
- (group ? !group.automatic : false)
+ user.group_ids.include?(group_id.to_i) && (group ? !group.automatic : false)
end
def can_use_flair_group?(user, group_id = nil)
return false if !user || !group_id || !user.group_ids.include?(group_id.to_i)
- flair_icon, flair_upload_id = Group.where(id: group_id.to_i).pluck_first(:flair_icon, :flair_upload_id)
+ flair_icon, flair_upload_id =
+ Group.where(id: group_id.to_i).pluck_first(:flair_icon, :flair_upload_id)
flair_icon.present? || flair_upload_id.present?
end
@@ -387,10 +399,9 @@ class Guardian
end
def can_invite_to_forum?(groups = nil)
- authenticated? &&
- (is_staff? || SiteSetting.max_invites_per_day.to_i.positive?) &&
- (is_staff? || @user.has_trust_level?(SiteSetting.min_trust_level_to_allow_invite.to_i)) &&
- (is_admin? || groups.blank? || groups.all? { |g| can_edit_group?(g) })
+ authenticated? && (is_staff? || SiteSetting.max_invites_per_day.to_i.positive?) &&
+ (is_staff? || @user.has_trust_level?(SiteSetting.min_trust_level_to_allow_invite.to_i)) &&
+ (is_admin? || groups.blank? || groups.all? { |g| can_edit_group?(g) })
end
def can_invite_to?(object, groups = nil)
@@ -402,9 +413,7 @@ class Guardian
if object.private_message?
return true if is_admin?
- if [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map)
- return false
- end
+ return false if [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map)
return false if object.reached_recipients_limit? && !is_staff?
end
@@ -441,8 +450,7 @@ class Guardian
end
def can_invite_group_to_private_message?(group, topic)
- can_see_topic?(topic) &&
- can_send_private_message?(group)
+ can_see_topic?(topic) && can_send_private_message?(group)
end
##
@@ -459,8 +467,11 @@ class Guardian
# User is authenticated
authenticated? &&
# User can send PMs, this can be covered by trust levels as well via AUTO_GROUPS
- (is_staff? || from_bot || from_system || \
- (@user.in_any_groups?(SiteSetting.personal_message_enabled_groups_map)) || notify_moderators)
+ (
+ is_staff? || from_bot || from_system ||
+ (@user.in_any_groups?(SiteSetting.personal_message_enabled_groups_map)) ||
+ notify_moderators
+ )
end
##
@@ -480,14 +491,14 @@ class Guardian
# User is authenticated and can send PMs, this can be covered by trust levels as well via AUTO_GROUPS
(can_send_private_messages?(notify_moderators: notify_moderators) || group_is_messageable) &&
- # User disabled private message
- (is_staff? || target_is_group || target.user_option.allow_private_messages) &&
- # Can't send PMs to suspended users
- (is_staff? || target_is_group || !target.suspended?) &&
- # Check group messageable level
- (from_system || target_is_user || group_is_messageable || notify_moderators) &&
- # Silenced users can only send PM to staff
- (!is_silenced? || target.staff?)
+ # User disabled private message
+ (is_staff? || target_is_group || target.user_option.allow_private_messages) &&
+ # Can't send PMs to suspended users
+ (is_staff? || target_is_group || !target.suspended?) &&
+ # Check group messageable level
+ (from_system || target_is_user || group_is_messageable || notify_moderators) &&
+ # Silenced users can only send PM to staff
+ (!is_silenced? || target.staff?)
end
def can_send_private_messages_to_email?
@@ -503,17 +514,18 @@ class Guardian
def can_export_entity?(entity)
return false if anonymous?
return true if is_admin?
- return entity != 'user_list' if is_moderator?
+ return entity != "user_list" if is_moderator?
# Regular users can only export their archives
return false unless entity == "user_archive"
- UserExport.where(user_id: @user.id, created_at: (Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)).count == 0
+ UserExport.where(
+ user_id: @user.id,
+ created_at: (Time.zone.now.beginning_of_day..Time.zone.now.end_of_day),
+ ).count == 0
end
def can_mute_user?(target_user)
- can_mute_users? &&
- @user.id != target_user.id &&
- !target_user.staff?
+ can_mute_users? && @user.id != target_user.id && !target_user.staff?
end
def can_mute_users?
@@ -546,20 +558,15 @@ class Guardian
return true if theme_ids.blank?
if allowed_theme_ids = Theme.allowed_remote_theme_ids
- if (theme_ids - allowed_theme_ids).present?
- return false
- end
+ return false if (theme_ids - allowed_theme_ids).present?
end
- if include_preview && is_staff? && (theme_ids - Theme.theme_ids).blank?
- return true
- end
+ return true if include_preview && is_staff? && (theme_ids - Theme.theme_ids).blank?
parent = theme_ids.first
components = theme_ids[1..-1] || []
- Theme.user_theme_ids.include?(parent) &&
- (components - Theme.components_for(parent)).empty?
+ Theme.user_theme_ids.include?(parent) && (components - Theme.components_for(parent)).empty?
end
def can_publish_page?(topic)
@@ -608,7 +615,6 @@ class Guardian
private
def is_my_own?(obj)
-
unless anonymous?
return obj.user_id == @user.id if obj.respond_to?(:user_id) && obj.user_id && @user.id
return obj.user == @user if obj.respond_to?(:user)
@@ -650,9 +656,8 @@ class Guardian
end
def category_group_moderator_scope
- Category
- .joins("INNER JOIN group_users ON group_users.group_id = categories.reviewable_by_group_id")
- .where("group_users.user_id = ?", user.id)
+ Category.joins(
+ "INNER JOIN group_users ON group_users.group_id = categories.reviewable_by_group_id",
+ ).where("group_users.user_id = ?", user.id)
end
-
end
diff --git a/lib/guardian/category_guardian.rb b/lib/guardian/category_guardian.rb
index 35bf8d30afe..e437455dfc5 100644
--- a/lib/guardian/category_guardian.rb
+++ b/lib/guardian/category_guardian.rb
@@ -2,40 +2,31 @@
#mixin for all guardian methods dealing with category permissions
module CategoryGuardian
-
# Creating Method
def can_create_category?(parent = nil)
- is_admin? ||
- (
- SiteSetting.moderators_manage_categories_and_groups &&
- is_moderator?
- )
+ is_admin? || (SiteSetting.moderators_manage_categories_and_groups && is_moderator?)
end
# Editing Method
def can_edit_category?(category)
is_admin? ||
- (
- SiteSetting.moderators_manage_categories_and_groups &&
- is_moderator? &&
- can_see_category?(category)
- )
+ (
+ SiteSetting.moderators_manage_categories_and_groups && is_moderator? &&
+ can_see_category?(category)
+ )
end
def can_edit_serialized_category?(category_id:, read_restricted:)
is_admin? ||
- (
- SiteSetting.moderators_manage_categories_and_groups &&
- is_moderator? &&
- can_see_serialized_category?(category_id: category_id, read_restricted: read_restricted)
- )
+ (
+ SiteSetting.moderators_manage_categories_and_groups && is_moderator? &&
+ can_see_serialized_category?(category_id: category_id, read_restricted: read_restricted)
+ )
end
def can_delete_category?(category)
- can_edit_category?(category) &&
- category.topic_count <= 0 &&
- !category.uncategorized? &&
- !category.has_children?
+ can_edit_category?(category) && category.topic_count <= 0 && !category.uncategorized? &&
+ !category.has_children?
end
def can_see_serialized_category?(category_id:, read_restricted: true)
@@ -84,6 +75,7 @@ module CategoryGuardian
end
def topic_featured_link_allowed_category_ids
- @topic_featured_link_allowed_category_ids = Category.where(topic_featured_link_allowed: true).pluck(:id)
+ @topic_featured_link_allowed_category_ids =
+ Category.where(topic_featured_link_allowed: true).pluck(:id)
end
end
diff --git a/lib/guardian/ensure_magic.rb b/lib/guardian/ensure_magic.rb
index bff9f402dca..62cece83b61 100644
--- a/lib/guardian/ensure_magic.rb
+++ b/lib/guardian/ensure_magic.rb
@@ -2,13 +2,14 @@
# Support for ensure_{blah}! methods.
module EnsureMagic
-
def method_missing(method, *args, &block)
if method.to_s =~ /^ensure_(.*)\!$/
can_method = :"#{Regexp.last_match[1]}?"
if respond_to?(can_method)
- raise Discourse::InvalidAccess.new("#{can_method} failed") unless send(can_method, *args, &block)
+ unless send(can_method, *args, &block)
+ raise Discourse::InvalidAccess.new("#{can_method} failed")
+ end
return
end
end
@@ -20,5 +21,4 @@ module EnsureMagic
def ensure_can_see!(obj)
raise Discourse::InvalidAccess.new("Can't see #{obj}") unless can_see?(obj)
end
-
end
diff --git a/lib/guardian/group_guardian.rb b/lib/guardian/group_guardian.rb
index b3e571776c9..7b153615a1b 100644
--- a/lib/guardian/group_guardian.rb
+++ b/lib/guardian/group_guardian.rb
@@ -2,14 +2,9 @@
#mixin for all guardian methods dealing with group permissions
module GroupGuardian
-
# Creating Method
def can_create_group?
- is_admin? ||
- (
- SiteSetting.moderators_manage_categories_and_groups &&
- is_moderator?
- )
+ is_admin? || (SiteSetting.moderators_manage_categories_and_groups && is_moderator?)
end
# Edit authority for groups means membership changes only.
@@ -17,17 +12,15 @@ module GroupGuardian
# table and thus do not allow membership changes.
def can_edit_group?(group)
!group.automatic &&
- (can_admin_group?(group) || group.users.where('group_users.owner').include?(user))
+ (can_admin_group?(group) || group.users.where("group_users.owner").include?(user))
end
def can_admin_group?(group)
is_admin? ||
- (
- SiteSetting.moderators_manage_categories_and_groups &&
- is_moderator? &&
- can_see?(group) &&
- group.id != Group::AUTO_GROUPS[:admins]
- )
+ (
+ SiteSetting.moderators_manage_categories_and_groups && is_moderator? && can_see?(group) &&
+ group.id != Group::AUTO_GROUPS[:admins]
+ )
end
def can_see_group_messages?(group)
diff --git a/lib/guardian/post_guardian.rb b/lib/guardian/post_guardian.rb
index 35e70305d25..6ca1256896d 100644
--- a/lib/guardian/post_guardian.rb
+++ b/lib/guardian/post_guardian.rb
@@ -2,26 +2,24 @@
# mixin for all guardian methods dealing with post permissions
module PostGuardian
-
def unrestricted_link_posting?
authenticated? && @user.has_trust_level?(TrustLevel[SiteSetting.min_trust_to_post_links])
end
def link_posting_access
if unrestricted_link_posting?
- 'full'
+ "full"
elsif SiteSetting.allowed_link_domains.present?
- 'limited'
+ "limited"
else
- 'none'
+ "none"
end
end
def can_post_link?(host: nil)
return false if host.blank?
- unrestricted_link_posting? ||
- SiteSetting.allowed_link_domains.split('|').include?(host)
+ unrestricted_link_posting? || SiteSetting.allowed_link_domains.split("|").include?(host)
end
# Can the user act on the post in a particular way.
@@ -30,47 +28,55 @@ module PostGuardian
return false unless (can_see_post.nil? && can_see_post?(post)) || can_see_post
# no warnings except for staff
- return false if action_key == :notify_user && (post.user.blank? || (!is_staff? && opts[:is_warning].present? && opts[:is_warning] == 'true'))
+ if action_key == :notify_user &&
+ (
+ post.user.blank? ||
+ (!is_staff? && opts[:is_warning].present? && opts[:is_warning] == "true")
+ )
+ return false
+ end
taken = opts[:taken_actions].try(:keys).to_a
- is_flag = PostActionType.notify_flag_types[action_key] || PostActionType.custom_types[action_key]
+ is_flag =
+ PostActionType.notify_flag_types[action_key] || PostActionType.custom_types[action_key]
already_taken_this_action = taken.any? && taken.include?(PostActionType.types[action_key])
- already_did_flagging = taken.any? && (taken & PostActionType.notify_flag_types.values).any?
-
- result = if authenticated? && post && [email protected]?
-
- # Silenced users can't flag
- return false if is_flag && @user.silenced?
-
- # Hidden posts can't be flagged
- return false if is_flag && post.hidden?
-
- # post made by staff, but we don't allow staff flags
- return false if is_flag &&
- (!SiteSetting.allow_flagging_staff?) &&
- post&.user&.staff?
-
- if action_key == :notify_user && [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map)
- return false
+ already_did_flagging = taken.any? && (taken & PostActionType.notify_flag_types.values).any?
+
+ result =
+ if authenticated? && post && [email protected]?
+ # Silenced users can't flag
+ return false if is_flag && @user.silenced?
+
+ # Hidden posts can't be flagged
+ return false if is_flag && post.hidden?
+
+ # post made by staff, but we don't allow staff flags
+ return false if is_flag && (!SiteSetting.allow_flagging_staff?) && post&.user&.staff?
+
+ if action_key == :notify_user &&
+ [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map)
+ return false
+ end
+
+ # we allow flagging for trust level 1 and higher
+ # always allowed for private messages
+ (
+ is_flag && not(already_did_flagging) &&
+ (
+ @user.has_trust_level?(TrustLevel[SiteSetting.min_trust_to_flag_posts]) ||
+ post.topic.private_message?
+ )
+ ) ||
+ # not a flagging action, and haven't done it already
+ not(is_flag || already_taken_this_action) &&
+ # nothing except flagging on archived topics
+ not(post.topic&.archived?) &&
+ # nothing except flagging on deleted posts
+ not(post.trashed?) &&
+ # don't like your own stuff
+ not(action_key == :like && (post.user.blank? || is_my_own?(post)))
end
- # we allow flagging for trust level 1 and higher
- # always allowed for private messages
- (is_flag && not(already_did_flagging) && (@user.has_trust_level?(TrustLevel[SiteSetting.min_trust_to_flag_posts]) || post.topic.private_message?)) ||
-
- # not a flagging action, and haven't done it already
- not(is_flag || already_taken_this_action) &&
-
- # nothing except flagging on archived topics
- not(post.topic&.archived?) &&
-
- # nothing except flagging on deleted posts
- not(post.trashed?) &&
-
- # don't like your own stuff
- not(action_key == :like && (post.user.blank? || is_my_own?(post)))
- end
-
!!result
end
@@ -94,12 +100,16 @@ module PostGuardian
end
def can_delete_all_posts?(user)
- is_staff? &&
- user &&
- !user.admin? &&
- (is_admin? ||
- ((user.first_post_created_at.nil? || user.first_post_created_at >= SiteSetting.delete_user_max_post_age.days.ago) &&
- user.post_count <= SiteSetting.delete_all_posts_max.to_i))
+ is_staff? && user && !user.admin? &&
+ (
+ is_admin? ||
+ (
+ (
+ user.first_post_created_at.nil? ||
+ user.first_post_created_at >= SiteSetting.delete_user_max_post_age.days.ago
+ ) && user.post_count <= SiteSetting.delete_all_posts_max.to_i
+ )
+ )
end
def can_create_post?(topic)
@@ -108,53 +118,43 @@ module PostGuardian
key = topic_memoize_key(topic)
@can_create_post ||= {}
- @can_create_post.fetch(key) do
- @can_create_post[key] = can_create_post_in_topic?(topic)
- end
+ @can_create_post.fetch(key) { @can_create_post[key] = can_create_post_in_topic?(topic) }
end
def can_edit_post?(post)
- if Discourse.static_doc_topic_ids.include?(post.topic_id) && !is_admin?
- return false
- end
+ return false if Discourse.static_doc_topic_ids.include?(post.topic_id) && !is_admin?
return true if is_admin?
# Must be staff to edit a locked post
return false if post.locked? && !is_staff?
- return can_create_post?(post.topic) if (
- is_staff? ||
- (
- SiteSetting.trusted_users_can_edit_others? &&
- @user.has_trust_level?(TrustLevel[4])
- ) ||
- is_category_group_moderator?(post.topic&.category)
- )
-
- if post.topic&.archived? || post.user_deleted || post.deleted_at
- return false
+ if (
+ is_staff? ||
+ (SiteSetting.trusted_users_can_edit_others? && @user.has_trust_level?(TrustLevel[4])) ||
+ is_category_group_moderator?(post.topic&.category)
+ )
+ return can_create_post?(post.topic)
end
+ return false if post.topic&.archived? || post.user_deleted || post.deleted_at
+
# Editing a shared draft.
- return true if (
- can_see_post?(post) &&
- can_create_post?(post.topic) &&
- post.topic.category_id == SiteSetting.shared_drafts_category.to_i &&
- can_see_category?(post.topic.category) &&
- can_see_shared_draft?
- )
+ if (
+ can_see_post?(post) && can_create_post?(post.topic) &&
+ post.topic.category_id == SiteSetting.shared_drafts_category.to_i &&
+ can_see_category?(post.topic.category) && can_see_shared_draft?
+ )
+ return true
+ end
if post.wiki && (@user.trust_level >= SiteSetting.min_trust_to_edit_wiki_post.to_i)
return can_create_post?(post.topic)
end
- if @user.trust_level < SiteSetting.min_trust_to_edit_post
- return false
- end
+ return false if @user.trust_level < SiteSetting.min_trust_to_edit_post
if is_my_own?(post)
-
return false if @user.silenced?
return can_edit_hidden_post?(post) if post.hidden?
@@ -175,7 +175,8 @@ module PostGuardian
def can_edit_hidden_post?(post)
return false if post.nil?
- post.hidden_at.nil? || post.hidden_at < SiteSetting.cooldown_minutes_after_hiding_posts.minutes.ago
+ post.hidden_at.nil? ||
+ post.hidden_at < SiteSetting.cooldown_minutes_after_hiding_posts.minutes.ago
end
def can_delete_post_or_topic?(post)
@@ -195,7 +196,12 @@ module PostGuardian
# You can delete your own posts
if is_my_own?(post)
- return false if (SiteSetting.max_post_deletions_per_minute < 1 || SiteSetting.max_post_deletions_per_day < 1)
+ if (
+ SiteSetting.max_post_deletions_per_minute < 1 ||
+ SiteSetting.max_post_deletions_per_day < 1
+ )
+ return false
+ end
return true if !post.user_deleted?
end
@@ -208,7 +214,9 @@ module PostGuardian
return false if post.is_first_post?
return false if !is_admin? || !can_edit_post?(post)
return false if !post.deleted_at
- return false if post.deleted_by_id == @user.id && post.deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
+ if post.deleted_by_id == @user.id && post.deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
+ return false
+ end
true
end
@@ -220,7 +228,12 @@ module PostGuardian
return true if can_moderate_topic?(topic) && !!post.deleted_at
if is_my_own?(post)
- return false if (SiteSetting.max_post_deletions_per_minute < 1 || SiteSetting.max_post_deletions_per_day < 1)
+ if (
+ SiteSetting.max_post_deletions_per_minute < 1 ||
+ SiteSetting.max_post_deletions_per_day < 1
+ )
+ return false
+ end
return true if post.user_deleted && !post.deleted_at
end
@@ -230,14 +243,17 @@ module PostGuardian
def can_delete_post_action?(post_action)
return false unless is_my_own?(post_action) && !post_action.is_private_message?
- post_action.created_at > SiteSetting.post_undo_action_window_mins.minutes.ago && !post_action.post&.topic&.archived?
+ post_action.created_at > SiteSetting.post_undo_action_window_mins.minutes.ago &&
+ !post_action.post&.topic&.archived?
end
def can_see_post?(post)
return false if post.blank?
return true if is_admin?
return false unless can_see_post_topic?(post)
- return false unless post.user == @user || Topic.visible_post_types(@user).include?(post.post_type)
+ unless post.user == @user || Topic.visible_post_types(@user).include?(post.post_type)
+ return false
+ end
return true if is_moderator? || is_category_group_moderator?(post.topic.category)
return true if !post.trashed? || can_see_deleted_post?(post)
false
@@ -257,9 +273,7 @@ module PostGuardian
return true if post.wiki || SiteSetting.edit_history_visible_to_public
end
- authenticated? &&
- (is_staff? || @user.id == post.user_id) &&
- can_see_post?(post)
+ authenticated? && (is_staff? || @user.id == post.user_id) && can_see_post?(post)
end
def can_change_post_owner?
@@ -315,13 +329,18 @@ module PostGuardian
private
def can_create_post_in_topic?(topic)
- return false if !SiteSetting.enable_system_message_replies? && topic.try(:subtype) == "system_message"
+ if !SiteSetting.enable_system_message_replies? && topic.try(:subtype) == "system_message"
+ return false
+ end
- (!SpamRule::AutoSilence.prevent_posting?(@user) || (!!topic.try(:private_message?) && topic.allowed_users.include?(@user))) && (
- !topic ||
- !topic.category ||
- Category.post_create_allowed(self).where(id: topic.category.id).count == 1
- )
+ (
+ !SpamRule::AutoSilence.prevent_posting?(@user) ||
+ (!!topic.try(:private_message?) && topic.allowed_users.include?(@user))
+ ) &&
+ (
+ !topic || !topic.category ||
+ Category.post_create_allowed(self).where(id: topic.category.id).count == 1
+ )
end
def topic_memoize_key(topic)
@@ -336,8 +355,6 @@ module PostGuardian
key = topic_memoize_key(topic)
@can_see_post_topic ||= {}
- @can_see_post_topic.fetch(key) do
- @can_see_post_topic[key] = can_see_topic?(topic)
- end
+ @can_see_post_topic.fetch(key) { @can_see_post_topic[key] = can_see_topic?(topic) }
end
end
diff --git a/lib/guardian/post_revision_guardian.rb b/lib/guardian/post_revision_guardian.rb
index 4372728b955..1e61b19e746 100644
--- a/lib/guardian/post_revision_guardian.rb
+++ b/lib/guardian/post_revision_guardian.rb
@@ -2,7 +2,6 @@
# mixin for all Guardian methods dealing with post_revisions permissions
module PostRevisionGuardian
-
def can_see_post_revision?(post_revision)
return false unless post_revision
return false if post_revision.hidden && !can_view_hidden_post_revisions?
@@ -21,5 +20,4 @@ module PostRevisionGuardian
def can_view_hidden_post_revisions?
is_staff?
end
-
end
diff --git a/lib/guardian/tag_guardian.rb b/lib/guardian/tag_guardian.rb
index 5a4be92ab43..db1ec7688ce 100644
--- a/lib/guardian/tag_guardian.rb
+++ b/lib/guardian/tag_guardian.rb
@@ -3,11 +3,13 @@
#mixin for all guardian methods dealing with tagging permissions
module TagGuardian
def can_create_tag?
- SiteSetting.tagging_enabled && @user.has_trust_level_or_staff?(SiteSetting.min_trust_to_create_tag)
+ SiteSetting.tagging_enabled &&
+ @user.has_trust_level_or_staff?(SiteSetting.min_trust_to_create_tag)
end
def can_tag_topics?
- SiteSetting.tagging_enabled && @user.has_trust_level_or_staff?(SiteSetting.min_trust_level_to_tag_topics)
+ SiteSetting.tagging_enabled &&
+ @user.has_trust_level_or_staff?(SiteSetting.min_trust_level_to_tag_topics)
end
def can_tag_pms?
@@ -16,7 +18,8 @@ module TagGuardian
return true if @user == Discourse.system_user
group_ids = SiteSetting.pm_tags_allowed_for_groups_map
- group_ids.include?(Group::AUTO_GROUPS[:everyone]) || @user.group_users.exists?(group_id: group_ids)
+ group_ids.include?(Group::AUTO_GROUPS[:everyone]) ||
+ @user.group_users.exists?(group_id: group_ids)
end
def can_admin_tags?
@@ -28,12 +31,13 @@ module TagGuardian
end
def hidden_tag_names
- @hidden_tag_names ||= begin
- if SiteSetting.tagging_enabled && !is_staff?
- DiscourseTagging.hidden_tag_names(self)
- else
- []
+ @hidden_tag_names ||=
+ begin
+ if SiteSetting.tagging_enabled && !is_staff?
+ DiscourseTagging.hidden_tag_names(self)
+ else
+ []
+ end
end
- end
end
end
diff --git a/lib/guardian/topic_guardian.rb b/lib/guardian/topic_guardian.rb
index c487de68978..05fb6ad041d 100644
--- a/lib/guardian/topic_guardian.rb
+++ b/lib/guardian/topic_guardian.rb
@@ -3,13 +3,11 @@
#mixin for all guardian methods dealing with topic permissions
module TopicGuardian
def can_remove_allowed_users?(topic, target_user = nil)
- is_staff? ||
- (topic.user == @user && @user.has_trust_level?(TrustLevel[2])) ||
- (
- topic.allowed_users.count > 1 &&
- topic.user != target_user &&
- !!(target_user && user == target_user)
- )
+ is_staff? || (topic.user == @user && @user.has_trust_level?(TrustLevel[2])) ||
+ (
+ topic.allowed_users.count > 1 && topic.user != target_user &&
+ !!(target_user && user == target_user)
+ )
end
def can_review_topic?(topic)
@@ -49,10 +47,10 @@ module TopicGuardian
# Creating Methods
def can_create_topic?(parent)
is_staff? ||
- (user &&
- user.trust_level >= SiteSetting.min_trust_to_create_topic.to_i &&
- can_create_post?(parent) &&
- Category.topic_create_allowed(self).limit(1).count == 1)
+ (
+ user && user.trust_level >= SiteSetting.min_trust_to_create_topic.to_i &&
+ can_create_post?(parent) && Category.topic_create_allowed(self).limit(1).count == 1
+ )
end
def can_create_topic_on_category?(category)
@@ -60,11 +58,18 @@ module TopicGuardian
category_id = Category === category ? category.id : category
can_create_topic?(nil) &&
- (!category || Category.topic_create_allowed(self).where(id: category_id).count == 1)
+ (!category || Category.topic_create_allowed(self).where(id: category_id).count == 1)
end
def can_move_topic_to_category?(category)
- category = Category === category ? category : Category.find(category || SiteSetting.uncategorized_category_id)
+ category =
+ (
+ if Category === category
+ category
+ else
+ Category.find(category || SiteSetting.uncategorized_category_id)
+ end
+ )
is_staff? || (can_create_topic_on_category?(category) && !category.require_topic_approval?)
end
@@ -75,7 +80,9 @@ module TopicGuardian
return false if topic.trashed?
return true if is_admin?
- trusted = (authenticated? && user.has_trust_level?(TrustLevel[4])) || is_moderator? || can_perform_action_available_to_group_moderators?(topic)
+ trusted =
+ (authenticated? && user.has_trust_level?(TrustLevel[4])) || is_moderator? ||
+ can_perform_action_available_to_group_moderators?(topic)
(!(topic.closed? || topic.archived?) || trusted) && can_create_post?(topic)
end
@@ -97,45 +104,40 @@ module TopicGuardian
# except for a tiny edge case where the topic is uncategorized and you are trying
# to fix it but uncategorized is disabled
if (
- SiteSetting.allow_uncategorized_topics ||
- topic.category_id != SiteSetting.uncategorized_category_id
- )
+ SiteSetting.allow_uncategorized_topics ||
+ topic.category_id != SiteSetting.uncategorized_category_id
+ )
return false if !can_create_topic_on_category?(topic.category)
end
# Editing a shared draft.
- return true if (
- !topic.archived &&
- !topic.private_message? &&
- topic.category_id == SiteSetting.shared_drafts_category.to_i &&
- can_see_category?(topic.category) &&
- can_see_shared_draft? &&
- can_create_post?(topic)
- )
+ if (
+ !topic.archived && !topic.private_message? &&
+ topic.category_id == SiteSetting.shared_drafts_category.to_i &&
+ can_see_category?(topic.category) && can_see_shared_draft? && can_create_post?(topic)
+ )
+ return true
+ end
# TL4 users can edit archived topics, but can not edit private messages
- return true if (
- SiteSetting.trusted_users_can_edit_others? &&
- topic.archived &&
- !topic.private_message? &&
- user.has_trust_level?(TrustLevel[4]) &&
- can_create_post?(topic)
- )
+ if (
+ SiteSetting.trusted_users_can_edit_others? && topic.archived && !topic.private_message? &&
+ user.has_trust_level?(TrustLevel[4]) && can_create_post?(topic)
+ )
+ return true
+ end
# TL3 users can not edit archived topics and private messages
- return true if (
- SiteSetting.trusted_users_can_edit_others? &&
- !topic.archived &&
- !topic.private_message? &&
- user.has_trust_level?(TrustLevel[3]) &&
- can_create_post?(topic)
- )
+ if (
+ SiteSetting.trusted_users_can_edit_others? && !topic.archived && !topic.private_message? &&
+ user.has_trust_level?(TrustLevel[3]) && can_create_post?(topic)
+ )
+ return true
+ end
return false if topic.archived
- is_my_own?(topic) &&
- !topic.edit_time_limit_expired?(user) &&
- !first_post&.locked? &&
+ is_my_own?(topic) && !topic.edit_time_limit_expired?(user) && !first_post&.locked? &&
(!first_post&.hidden? || can_edit_hidden_post?(first_post))
end
@@ -149,9 +151,13 @@ module TopicGuardian
def can_delete_topic?(topic)
!topic.trashed? &&
- (is_staff? || (is_my_own?(topic) && topic.posts_count <= 1 && topic.created_at && topic.created_at > 24.hours.ago) || is_category_group_moderator?(topic.category)) &&
- !topic.is_category_topic? &&
- !Discourse.static_doc_topic_ids.include?(topic.id)
+ (
+ is_staff? ||
+ (
+ is_my_own?(topic) && topic.posts_count <= 1 && topic.created_at &&
+ topic.created_at > 24.hours.ago
+ ) || is_category_group_moderator?(topic.category)
+ ) && !topic.is_category_topic? && !Discourse.static_doc_topic_ids.include?(topic.id)
end
def can_permanently_delete_topic?(topic)
@@ -165,15 +171,21 @@ module TopicGuardian
# All other posts that were deleted still must be permanently deleted
# before the topic can be deleted with the exception of small action
# posts that will be deleted right before the topic is.
- all_posts_count = Post.with_deleted
- .where(topic_id: topic.id)
- .where(post_type: [Post.types[:regular], Post.types[:moderator_action], Post.types[:whisper]])
- .count
+ all_posts_count =
+ Post
+ .with_deleted
+ .where(topic_id: topic.id)
+ .where(
+ post_type: [Post.types[:regular], Post.types[:moderator_action], Post.types[:whisper]],
+ )
+ .count
return false if all_posts_count > 1
return false if !is_admin? || !can_see_topic?(topic)
return false if !topic.deleted_at
- return false if topic.deleted_by_id == @user.id && topic.deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
+ if topic.deleted_by_id == @user.id && topic.deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
+ return false
+ end
true
end
@@ -181,7 +193,7 @@ module TopicGuardian
can_moderate?(topic) || can_perform_action_available_to_group_moderators?(topic)
end
- alias :can_create_unlisted_topic? :can_toggle_topic_visibility?
+ alias can_create_unlisted_topic? can_toggle_topic_visibility?
def can_convert_topic?(topic)
return false unless @user.in_any_groups?(SiteSetting.personal_message_enabled_groups_map)
@@ -228,13 +240,16 @@ module TopicGuardian
# Filter out topics with shared drafts if user cannot see shared drafts
if !can_see_shared_draft?
- default_scope = default_scope.left_outer_joins(:shared_draft).where("shared_drafts.id IS NULL")
+ default_scope =
+ default_scope.left_outer_joins(:shared_draft).where("shared_drafts.id IS NULL")
end
all_topics_scope =
if authenticated?
Topic.unscoped.merge(
- secured_regular_topic_scope(default_scope, topic_ids: topic_ids).or(private_message_topic_scope(default_scope))
+ secured_regular_topic_scope(default_scope, topic_ids: topic_ids).or(
+ private_message_topic_scope(default_scope),
+ ),
)
else
Topic.unscoped.merge(secured_regular_topic_scope(default_scope, topic_ids: topic_ids))
@@ -256,7 +271,10 @@ module TopicGuardian
category = topic.category
can_see_category?(category) &&
- (!category.read_restricted || !is_staged? || secure_category_ids.include?(category.id) || topic.user == user)
+ (
+ !category.read_restricted || !is_staged? || secure_category_ids.include?(category.id) ||
+ topic.user == user
+ )
end
def can_get_access_to_topic?(topic)
@@ -266,9 +284,17 @@ module TopicGuardian
def filter_allowed_categories(records)
return records if is_admin? && !SiteSetting.suppress_secured_categories_from_admin
- records = allowed_category_ids.size == 0 ?
- records.where('topics.category_id IS NULL') :
- records.where('topics.category_id IS NULL or topics.category_id IN (?)', allowed_category_ids)
+ records =
+ (
+ if allowed_category_ids.size == 0
+ records.where("topics.category_id IS NULL")
+ else
+ records.where(
+ "topics.category_id IS NULL or topics.category_id IN (?)",
+ allowed_category_ids,
+ )
+ end
+ )
records.references(:categories)
end
@@ -276,7 +302,10 @@ module TopicGuardian
def can_edit_featured_link?(category_id)
return false unless SiteSetting.topic_featured_link_enabled
return false unless @user.trust_level >= TrustLevel.levels[:basic]
- Category.where(id: category_id || SiteSetting.uncategorized_category_id, topic_featured_link_allowed: true).exists?
+ Category.where(
+ id: category_id || SiteSetting.uncategorized_category_id,
+ topic_featured_link_allowed: true,
+ ).exists?
end
def can_update_bumped_at?
@@ -292,7 +321,8 @@ module TopicGuardian
return false if topic.private_message? && !can_tag_pms?
return true if can_edit_topic?(topic)
- if topic&.first_post&.wiki && (@user.trust_level >= SiteSetting.min_trust_to_edit_wiki_post.to_i)
+ if topic&.first_post&.wiki &&
+ (@user.trust_level >= SiteSetting.min_trust_to_edit_wiki_post.to_i)
return can_create_post?(topic)
end
@@ -306,12 +336,12 @@ module TopicGuardian
is_category_group_moderator?(topic.category)
end
- alias :can_archive_topic? :can_perform_action_available_to_group_moderators?
- alias :can_close_topic? :can_perform_action_available_to_group_moderators?
- alias :can_open_topic? :can_perform_action_available_to_group_moderators?
- alias :can_split_merge_topic? :can_perform_action_available_to_group_moderators?
- alias :can_edit_staff_notes? :can_perform_action_available_to_group_moderators?
- alias :can_pin_unpin_topic? :can_perform_action_available_to_group_moderators?
+ alias can_archive_topic? can_perform_action_available_to_group_moderators?
+ alias can_close_topic? can_perform_action_available_to_group_moderators?
+ alias can_open_topic? can_perform_action_available_to_group_moderators?
+ alias can_split_merge_topic? can_perform_action_available_to_group_moderators?
+ alias can_edit_staff_notes? can_perform_action_available_to_group_moderators?
+ alias can_pin_unpin_topic? can_perform_action_available_to_group_moderators?
def can_move_posts?(topic)
return false if is_silenced?
@@ -327,12 +357,10 @@ module TopicGuardian
def private_message_topic_scope(scope)
pm_scope = scope.private_messages_for_user(user)
- if is_moderator?
- pm_scope = pm_scope.or(scope.where(<<~SQL))
+ pm_scope = pm_scope.or(scope.where(<<~SQL)) if is_moderator?
topics.subtype = '#{TopicSubtype.moderator_warning}'
OR topics.id IN (#{Topic.has_flag_scope.select(:topic_id).to_sql})
SQL
- end
pm_scope
end
@@ -357,7 +385,8 @@ module TopicGuardian
)
SQL
- secured_scope = secured_scope.or(Topic.unscoped.where(sql, user_id: user.id, topic_ids: topic_ids))
+ secured_scope =
+ secured_scope.or(Topic.unscoped.where(sql, user_id: user.id, topic_ids: topic_ids))
end
scope.listable_topics.merge(secured_scope)
diff --git a/lib/guardian/user_guardian.rb b/lib/guardian/user_guardian.rb
index 675e3431ef7..2879ad036f9 100644
--- a/lib/guardian/user_guardian.rb
+++ b/lib/guardian/user_guardian.rb
@@ -2,9 +2,8 @@
# mixin for all Guardian methods dealing with user permissions
module UserGuardian
-
def can_claim_reviewable_topic?(topic)
- SiteSetting.reviewable_claiming != 'disabled' && can_review_topic?(topic)
+ SiteSetting.reviewable_claiming != "disabled" && can_review_topic?(topic)
end
def can_pick_avatar?(user_avatar, upload)
@@ -63,13 +62,14 @@ module UserGuardian
if is_me?(user)
!SiteSetting.enable_discourse_connect &&
- !user.has_more_posts_than?(SiteSetting.delete_user_self_max_post_count)
+ !user.has_more_posts_than?(SiteSetting.delete_user_self_max_post_count)
else
- is_staff? && (
- user.first_post_created_at.nil? ||
- !user.has_more_posts_than?(User::MAX_STAFF_DELETE_POST_COUNT) ||
- user.first_post_created_at > SiteSetting.delete_user_max_post_age.to_i.days.ago
- )
+ is_staff? &&
+ (
+ user.first_post_created_at.nil? ||
+ !user.has_more_posts_than?(User::MAX_STAFF_DELETE_POST_COUNT) ||
+ user.first_post_created_at > SiteSetting.delete_user_max_post_age.to_i.days.ago
+ )
end
end
@@ -123,9 +123,7 @@ module UserGuardian
return true if !SiteSetting.allow_users_to_hide_profile?
# If a user has hidden their profile, restrict it to them and staff
- if user.user_option.try(:hide_profile_and_presence?)
- return is_me?(user) || is_staff?
- end
+ return is_me?(user) || is_staff? if user.user_option.try(:hide_profile_and_presence?)
true
end
@@ -141,14 +139,13 @@ module UserGuardian
is_staff_or_is_me = is_staff? || is_me?(user)
cache_key = is_staff_or_is_me ? :staff_or_me : :other
- @allowed_user_field_ids[cache_key] ||=
- begin
- if is_staff_or_is_me
- UserField.pluck(:id)
- else
- UserField.where("show_on_profile OR show_on_user_card").pluck(:id)
- end
+ @allowed_user_field_ids[cache_key] ||= begin
+ if is_staff_or_is_me
+ UserField.pluck(:id)
+ else
+ UserField.where("show_on_profile OR show_on_user_card").pluck(:id)
end
+ end
end
def can_feature_topic?(user, topic)
@@ -161,13 +158,14 @@ module UserGuardian
end
def can_see_review_queue?
- is_staff? || (
- SiteSetting.enable_category_group_moderation &&
- Reviewable
- .where(reviewable_by_group_id: @user.group_users.pluck(:group_id))
- .where('category_id IS NULL or category_id IN (?)', allowed_category_ids)
- .exists?
- )
+ is_staff? ||
+ (
+ SiteSetting.enable_category_group_moderation &&
+ Reviewable
+ .where(reviewable_by_group_id: @user.group_users.pluck(:group_id))
+ .where("category_id IS NULL or category_id IN (?)", allowed_category_ids)
+ .exists?
+ )
end
def can_see_summary_stats?(target_user)
@@ -175,11 +173,17 @@ module UserGuardian
end
def can_upload_profile_header?(user)
- (is_me?(user) && user.has_trust_level?(SiteSetting.min_trust_level_to_allow_profile_background.to_i)) || is_staff?
+ (
+ is_me?(user) &&
+ user.has_trust_level?(SiteSetting.min_trust_level_to_allow_profile_background.to_i)
+ ) || is_staff?
end
def can_upload_user_card_background?(user)
- (is_me?(user) && user.has_trust_level?(SiteSetting.min_trust_level_to_allow_user_card_background.to_i)) || is_staff?
+ (
+ is_me?(user) &&
+ user.has_trust_level?(SiteSetting.min_trust_level_to_allow_user_card_background.to_i)
+ ) || is_staff?
end
def can_upload_external?
diff --git a/lib/has_errors.rb b/lib/has_errors.rb
index 907e537d1c0..daa8bb8e8d3 100644
--- a/lib/has_errors.rb
+++ b/lib/has_errors.rb
@@ -33,11 +33,8 @@ module HasErrors
def add_errors_from(obj)
return if obj.blank?
- if obj.is_a?(StandardError)
- return add_error(obj.message)
- end
+ return add_error(obj.message) if obj.is_a?(StandardError)
obj.errors.full_messages.each { |msg| add_error(msg) }
end
-
end
diff --git a/lib/highlight_js.rb b/lib/highlight_js.rb
index 8ad4f26264e..48bd77baf39 100644
--- a/lib/highlight_js.rb
+++ b/lib/highlight_js.rb
@@ -2,12 +2,47 @@
module HighlightJs
HIGHLIGHTJS_DIR ||= "#{Rails.root}/vendor/assets/javascripts/highlightjs/"
- BUNDLED_LANGS = %w(bash c cpp csharp css diff go graphql ini java javascript json kotlin less lua makefile xml markdown objectivec perl php php-template plaintext python python-repl r ruby rust scss shell sql swift typescript vbnet wasm yaml)
+ BUNDLED_LANGS = %w[
+ bash
+ c
+ cpp
+ csharp
+ css
+ diff
+ go
+ graphql
+ ini
+ java
+ javascript
+ json
+ kotlin
+ less
+ lua
+ makefile
+ xml
+ markdown
+ objectivec
+ perl
+ php
+ php-template
+ plaintext
+ python
+ python-repl
+ r
+ ruby
+ rust
+ scss
+ shell
+ sql
+ swift
+ typescript
+ vbnet
+ wasm
+ yaml
+ ]
def self.languages
- langs = Dir.glob(HIGHLIGHTJS_DIR + "languages/*.js").map do |path|
- File.basename(path)[0..-8]
- end
+ langs = Dir.glob(HIGHLIGHTJS_DIR + "languages/*.js").map { |path| File.basename(path)[0..-8] }
langs.sort
end
@@ -26,8 +61,9 @@ module HighlightJs
end
def self.version(lang_string)
- (@lang_string_cache ||= {})[lang_string] ||=
- Digest::SHA1.hexdigest(bundle lang_string.split("|"))
+ (@lang_string_cache ||= {})[lang_string] ||= Digest::SHA1.hexdigest(
+ bundle lang_string.split("|")
+ )
end
def self.path
diff --git a/lib/hijack.rb b/lib/hijack.rb
index 0b39abb7103..eb9b5ce2163 100644
--- a/lib/hijack.rb
+++ b/lib/hijack.rb
@@ -1,19 +1,17 @@
# frozen_string_literal: true
-require 'method_profiler'
+require "method_profiler"
# This module allows us to hijack a request and send it to the client in the deferred job queue
# For cases where we are making remote calls like onebox or proxying files and so on this helps
# free up a unicorn worker while the remote IO is happening
module Hijack
-
def hijack(info: nil, &blk)
controller_class = self.class
- if hijack = request.env['rack.hijack']
-
- request.env['discourse.request_tracker.skip'] = true
- request_tracker = request.env['discourse.request_tracker']
+ if hijack = request.env["rack.hijack"]
+ request.env["discourse.request_tracker.skip"] = true
+ request_tracker = request.env["discourse.request_tracker"]
# in the past unicorn would recycle env, this is not longer the case
env = request.env
@@ -32,7 +30,6 @@ module Hijack
original_headers = response.headers.dup
Scheduler::Defer.later("hijack #{params["controller"]} #{params["action"]} #{info}") do
-
MethodProfiler.start(transfer_timings)
begin
Thread.current[Logster::Logger::LOGSTER_ENV] = env
@@ -47,22 +44,22 @@ module Hijack
instance.response = response
instance.request = request_copy
- original_headers&.each do |k, v|
- instance.response.headers[k] = v
- end
+ original_headers&.each { |k, v| instance.response.headers[k] = v }
view_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
begin
instance.instance_eval(&blk)
rescue => e
# TODO we need to reuse our exception handling in ApplicationController
- Discourse.warn_exception(e, message: "Failed to process hijacked response correctly", env: env)
+ Discourse.warn_exception(
+ e,
+ message: "Failed to process hijacked response correctly",
+ env: env,
+ )
end
view_runtime = Process.clock_gettime(Process::CLOCK_MONOTONIC) - view_start
- unless instance.response_body || response.committed?
- instance.status = 500
- end
+ instance.status = 500 unless instance.response_body || response.committed?
response.commit!
@@ -74,13 +71,11 @@ module Hijack
Discourse::Cors.apply_headers(cors_origins, env, headers)
end
- headers['Content-Type'] ||= response.content_type || "text/plain"
- headers['Content-Length'] = body.bytesize
- headers['Connection'] = "close"
+ headers["Content-Type"] ||= response.content_type || "text/plain"
+ headers["Content-Length"] = body.bytesize
+ headers["Connection"] = "close"
- if env[Auth::DefaultCurrentUserProvider::BAD_TOKEN]
- headers['Discourse-Logged-Out'] = '1'
- end
+ headers["Discourse-Logged-Out"] = "1" if env[Auth::DefaultCurrentUserProvider::BAD_TOKEN]
status_string = Rack::Utils::HTTP_STATUS_CODES[response.status.to_i] || "Unknown"
io.write "#{response.status} #{status_string}\r\n"
@@ -90,9 +85,7 @@ module Hijack
headers["X-Runtime"] = "#{"%0.6f" % duration}"
end
- headers.each do |name, val|
- io.write "#{name}: #{val}\r\n"
- end
+ headers.each { |name, val| io.write "#{name}: #{val}\r\n" }
io.write "\r\n"
io.write body
@@ -100,30 +93,35 @@ module Hijack
# happens if client terminated before we responded, ignore
io = nil
ensure
-
if Rails.configuration.try(:lograge).try(:enabled)
if timings
db_runtime = 0
- if timings[:sql]
- db_runtime = timings[:sql][:duration]
- end
+ db_runtime = timings[:sql][:duration] if timings[:sql]
subscriber = Lograge::LogSubscribers::ActionController.new
- payload = ActiveSupport::HashWithIndifferentAccess.new(
- controller: self.class.name,
- action: action_name,
- params: request.filtered_parameters,
- headers: request.headers,
- format: request.format.ref,
- method: request.request_method,
- path: request.fullpath,
- view_runtime: view_runtime * 1000.0,
- db_runtime: db_runtime * 1000.0,
- timings: timings,
- status: response.status
- )
-
- event = ActiveSupport::Notifications::Event.new("hijack", Time.now, Time.now + timings[:total_duration], "", payload)
+ payload =
+ ActiveSupport::HashWithIndifferentAccess.new(
+ controller: self.class.name,
+ action: action_name,
+ params: request.filtered_parameters,
+ headers: request.headers,
+ format: request.format.ref,
+ method: request.request_method,
+ path: request.fullpath,
+ view_runtime: view_runtime * 1000.0,
+ db_runtime: db_runtime * 1000.0,
+ timings: timings,
+ status: response.status,
+ )
+
+ event =
+ ActiveSupport::Notifications::Event.new(
+ "hijack",
+ Time.now,
+ Time.now + timings[:total_duration],
+ "",
+ payload,
+ )
subscriber.process_action(event)
end
end
@@ -131,10 +129,19 @@ module Hijack
MethodProfiler.clear
Thread.current[Logster::Logger::LOGSTER_ENV] = nil
- io.close if io rescue nil
+ begin
+ io.close if io
+ rescue StandardError
+ nil
+ end
if request_tracker
- status = response.status rescue 500
+ status =
+ begin
+ response.status
+ rescue StandardError
+ 500
+ end
request_tracker.log_request_info(env, [status, headers || {}, []], timings)
end
diff --git a/lib/homepage_constraint.rb b/lib/homepage_constraint.rb
index ef6686d5fdb..78492e4f018 100644
--- a/lib/homepage_constraint.rb
+++ b/lib/homepage_constraint.rb
@@ -6,7 +6,7 @@ class HomePageConstraint
end
def matches?(request)
- return @filter == 'finish_installation' if SiteSetting.has_login_hint?
+ return @filter == "finish_installation" if SiteSetting.has_login_hint?
current_user = CurrentUser.lookup_from_env(request.env)
homepage = current_user&.user_option&.homepage || SiteSetting.anonymous_homepage
diff --git a/lib/html_prettify.rb b/lib/html_prettify.rb
index 06a00099b2b..074a3c8a2a5 100644
--- a/lib/html_prettify.rb
+++ b/lib/html_prettify.rb
@@ -82,14 +82,14 @@ class HtmlPrettify < String
elsif @options.include?(-1)
do_stupefy = true
else
- do_quotes = @options.include?(:quotes)
- do_backticks = @options.include?(:backticks)
- do_backticks = :both if @options.include?(:allbackticks)
- do_dashes = :normal if @options.include?(:dashes)
- do_dashes = :oldschool if @options.include?(:oldschool)
- do_dashes = :inverted if @options.include?(:inverted)
- do_ellipses = @options.include?(:ellipses)
- do_stupefy = @options.include?(:stupefy)
+ do_quotes = @options.include?(:quotes)
+ do_backticks = @options.include?(:backticks)
+ do_backticks = :both if @options.include?(:allbackticks)
+ do_dashes = :normal if @options.include?(:dashes)
+ do_dashes = :oldschool if @options.include?(:oldschool)
+ do_dashes = :inverted if @options.include?(:inverted)
+ do_ellipses = @options.include?(:ellipses)
+ do_stupefy = @options.include?(:stupefy)
end
# Parse the HTML
@@ -110,8 +110,8 @@ class HtmlPrettify < String
tokens.each do |token|
if token.first == :tag
result << token[1]
- if token[1] =~ %r!<(/?)(?:pre|code|kbd|script|math)[\s>]!
- in_pre = ($1 != "/") # Opening or closing tag?
+ if token[1] =~ %r{<(/?)(?:pre|code|kbd|script|math)[\s>]}
+ in_pre = ($1 != "/") # Opening or closing tag?
end
else
t = token[1]
@@ -120,24 +120,23 @@ class HtmlPrettify < String
last_char = t[-1].chr
unless in_pre
-
t.gsub!("&#39;", "'")
t.gsub!("&quot;", '"')
if do_dashes
- t = educate_dashes t if do_dashes == :normal
- t = educate_dashes_oldschool t if do_dashes == :oldschool
- t = educate_dashes_inverted t if do_dashes == :inverted
+ t = educate_dashes t if do_dashes == :normal
+ t = educate_dashes_oldschool t if do_dashes == :oldschool
+ t = educate_dashes_inverted t if do_dashes == :inverted
end
- t = educate_ellipses t if do_ellipses
+ t = educate_ellipses t if do_ellipses
t = educate_fractions t
# Note: backticks need to be processed before quotes.
if do_backticks
t = educate_backticks t
- t = educate_single_backticks t if do_backticks == :both
+ t = educate_single_backticks t if do_backticks == :both
end
if do_quotes
@@ -161,7 +160,7 @@ class HtmlPrettify < String
end
end
- t = stupefy_entities t if do_stupefy
+ t = stupefy_entities t if do_stupefy
end
prev_token_last_char = last_char
@@ -179,8 +178,7 @@ class HtmlPrettify < String
# em-dash HTML entity.
#
def educate_dashes(str)
- str.
- gsub(/--/, entity(:em_dash))
+ str.gsub(/--/, entity(:em_dash))
end
# The string, with each instance of "<tt>--</tt>" translated to an
@@ -188,9 +186,7 @@ class HtmlPrettify < String
# em-dash HTML entity.
#
def educate_dashes_oldschool(str)
- str.
- gsub(/---/, entity(:em_dash)).
- gsub(/--/, entity(:en_dash))
+ str.gsub(/---/, entity(:em_dash)).gsub(/--/, entity(:en_dash))
end
# Return the string, with each instance of "<tt>--</tt>" translated
@@ -204,9 +200,7 @@ class HtmlPrettify < String
# Aaron Swartz for the idea.)
#
def educate_dashes_inverted(str)
- str.
- gsub(/---/, entity(:en_dash)).
- gsub(/--/, entity(:em_dash))
+ str.gsub(/---/, entity(:en_dash)).gsub(/--/, entity(:em_dash))
end
# Return the string, with each instance of "<tt>...</tt>" translated
@@ -214,31 +208,25 @@ class HtmlPrettify < String
# spaces between the dots.
#
def educate_ellipses(str)
- str.
- gsub('...', entity(:ellipsis)).
- gsub('. . .', entity(:ellipsis))
+ str.gsub("...", entity(:ellipsis)).gsub(". . .", entity(:ellipsis))
end
# Return the string, with "<tt>``backticks''</tt>"-style single quotes
# translated into HTML curly quote entities.
#
def educate_backticks(str)
- str.
- gsub("``", entity(:double_left_quote)).
- gsub("''", entity(:double_right_quote))
+ str.gsub("``", entity(:double_left_quote)).gsub("''", entity(:double_right_quote))
end
# Return the string, with "<tt>`backticks'</tt>"-style single quotes
# translated into HTML curly quote entities.
#
def educate_single_backticks(str)
- str.
- gsub("`", entity(:single_left_quote)).
- gsub("'", entity(:single_right_quote))
+ str.gsub("`", entity(:single_left_quote)).gsub("'", entity(:single_right_quote))
end
def educate_fractions(str)
- str.gsub(/(\s+|^)(1\/4|1\/2|3\/4)([,.;\s]|$)/) do
+ str.gsub(%r{(\s+|^)(1/4|1/2|3/4)([,.;\s]|$)}) do
frac =
if $2 == "1/2"
entity(:frac12)
@@ -261,52 +249,45 @@ class HtmlPrettify < String
# Special case if the very first character is a quote followed by
# punctuation at a non-word-break. Close the quotes by brute
# force:
- str.gsub!(/^'(?=#{punct_class}\B)/,
- entity(:single_right_quote))
- str.gsub!(/^"(?=#{punct_class}\B)/,
- entity(:double_right_quote))
+ str.gsub!(/^'(?=#{punct_class}\B)/, entity(:single_right_quote))
+ str.gsub!(/^"(?=#{punct_class}\B)/, entity(:double_right_quote))
# Special case for double sets of quotes, e.g.:
# <p>He said, "'Quoted' words in a larger quote."</p>
- str.gsub!(/"'(?=\w)/,
- "#{entity(:double_left_quote)}#{entity(:single_left_quote)}")
- str.gsub!(/'"(?=\w)/,
- "#{entity(:single_left_quote)}#{entity(:double_left_quote)}")
+ str.gsub!(/"'(?=\w)/, "#{entity(:double_left_quote)}#{entity(:single_left_quote)}")
+ str.gsub!(/'"(?=\w)/, "#{entity(:single_left_quote)}#{entity(:double_left_quote)}")
# Special case for decade abbreviations (the '80s):
- str.gsub!(/'(?=\d\ds)/,
- entity(:single_right_quote))
+ str.gsub!(/'(?=\d\ds)/, entity(:single_right_quote))
close_class = %![^\ \t\r\n\\[\{\(\-]!
dec_dashes = "#{entity(:en_dash)}|#{entity(:em_dash)}"
# Get most opening single quotes:
- str.gsub!(/(\s|&nbsp;|=|--|&[mn]dash;|#{dec_dashes}|&#x201[34];)'(?=\w)/,
- '\1' + entity(:single_left_quote))
+ str.gsub!(
+ /(\s|&nbsp;|=|--|&[mn]dash;|#{dec_dashes}|&#x201[34];)'(?=\w)/,
+ '\1' + entity(:single_left_quote),
+ )
# Single closing quotes:
- str.gsub!(/(#{close_class})'/,
- '\1' + entity(:single_right_quote))
- str.gsub!(/'(\s|s\b|$)/,
- entity(:single_right_quote) + '\1')
+ str.gsub!(/(#{close_class})'/, '\1' + entity(:single_right_quote))
+ str.gsub!(/'(\s|s\b|$)/, entity(:single_right_quote) + '\1')
# Any remaining single quotes should be opening ones:
- str.gsub!(/'/,
- entity(:single_left_quote))
+ str.gsub!(/'/, entity(:single_left_quote))
# Get most opening double quotes:
- str.gsub!(/(\s|&nbsp;|=|--|&[mn]dash;|#{dec_dashes}|&#x201[34];)"(?=\w)/,
- '\1' + entity(:double_left_quote))
+ str.gsub!(
+ /(\s|&nbsp;|=|--|&[mn]dash;|#{dec_dashes}|&#x201[34];)"(?=\w)/,
+ '\1' + entity(:double_left_quote),
+ )
# Double closing quotes:
- str.gsub!(/(#{close_class})"/,
- '\1' + entity(:double_right_quote))
- str.gsub!(/"(\s|s\b|$)/,
- entity(:double_right_quote) + '\1')
+ str.gsub!(/(#{close_class})"/, '\1' + entity(:double_right_quote))
+ str.gsub!(/"(\s|s\b|$)/, entity(:double_right_quote) + '\1')
# Any remaining quotes should be opening ones:
- str.gsub!(/"/,
- entity(:double_left_quote))
+ str.gsub!(/"/, entity(:double_left_quote))
str
end
@@ -320,16 +301,14 @@ class HtmlPrettify < String
new_str = str.dup
{
- en_dash: '-',
- em_dash: '--',
+ en_dash: "-",
+ em_dash: "--",
single_left_quote: "'",
single_right_quote: "'",
double_left_quote: '"',
double_right_quote: '"',
- ellipsis: '...'
- }.each do |k, v|
- new_str.gsub!(/#{entity(k)}/, v)
- end
+ ellipsis: "...",
+ }.each { |k, v| new_str.gsub!(/#{entity(k)}/, v) }
new_str
end
@@ -354,14 +333,12 @@ class HtmlPrettify < String
prev_end = 0
scan(tag_soup) do
- tokens << [:text, $1] if $1 != ""
+ tokens << [:text, $1] if $1 != ""
tokens << [:tag, $2]
prev_end = $~.end(0)
end
- if prev_end < size
- tokens << [:text, self[prev_end..-1]]
- end
+ tokens << [:text, self[prev_end..-1]] if prev_end < size
tokens
end
@@ -385,5 +362,4 @@ class HtmlPrettify < String
def entity(key)
@entities[key]
end
-
end
diff --git a/lib/html_to_markdown.rb b/lib/html_to_markdown.rb
index 2d2783d4671..67626fd76e7 100644
--- a/lib/html_to_markdown.rb
+++ b/lib/html_to_markdown.rb
@@ -3,12 +3,11 @@
require "securerandom"
class HtmlToMarkdown
-
def initialize(html, opts = {})
@opts = opts
# we're only interested in <body>
- @doc = Nokogiri::HTML5(html).at("body")
+ @doc = Nokogiri.HTML5(html).at("body")
remove_not_allowed!(@doc)
remove_hidden!(@doc)
@@ -17,9 +16,7 @@ class HtmlToMarkdown
end
def to_markdown
- traverse(@doc)
- .gsub(/\n{2,}/, "\n\n")
- .strip
+ traverse(@doc).gsub(/\n{2,}/, "\n\n").strip
end
private
@@ -50,31 +47,33 @@ class HtmlToMarkdown
loop do
changed = false
- doc.css("br.#{klass}").each do |br|
- parent = br.parent
+ doc
+ .css("br.#{klass}")
+ .each do |br|
+ parent = br.parent
- if block?(parent)
- br.remove_class(klass)
- else
- before, after = parent.children.slice_when { |n| n == br }.to_a
+ if block?(parent)
+ br.remove_class(klass)
+ else
+ before, after = parent.children.slice_when { |n| n == br }.to_a
- if before.size > 1
- b = doc.document.create_element(parent.name)
- before[0...-1].each { |c| b.add_child(c) }
- parent.previous = b if b.inner_html.present?
- end
+ if before.size > 1
+ b = doc.document.create_element(parent.name)
+ before[0...-1].each { |c| b.add_child(c) }
+ parent.previous = b if b.inner_html.present?
+ end
- if after.present?
- a = doc.document.create_element(parent.name)
- after.each { |c| a.add_child(c) }
- parent.next = a if a.inner_html.present?
- end
+ if after.present?
+ a = doc.document.create_element(parent.name)
+ after.each { |c| a.add_child(c) }
+ parent.next = a if a.inner_html.present?
+ end
- parent.replace(br)
+ parent.replace(br)
- changed = true
+ changed = true
+ end
end
- end
break if !changed
end
@@ -85,17 +84,21 @@ class HtmlToMarkdown
def remove_whitespaces!(node)
return true if "pre" == node.name
- node.children.chunk { |n| is_inline?(n) }.each do |inline, nodes|
- if inline
- collapse_spaces!(nodes) && remove_trailing_space!(nodes)
- else
- nodes.each { |n| remove_whitespaces!(n) }
+ node
+ .children
+ .chunk { |n| is_inline?(n) }
+ .each do |inline, nodes|
+ if inline
+ collapse_spaces!(nodes) && remove_trailing_space!(nodes)
+ else
+ nodes.each { |n| remove_whitespaces!(n) }
+ end
end
- end
end
def is_inline?(node)
- node.text? || ("br" != node.name && node.description&.inline? && node.children.all? { |n| is_inline?(n) })
+ node.text? ||
+ ("br" != node.name && node.description&.inline? && node.children.all? { |n| is_inline?(n) })
end
def collapse_spaces!(nodes, was_space = true)
@@ -141,15 +144,16 @@ class HtmlToMarkdown
send(visitor, node) if respond_to?(visitor, true)
end
- ALLOWED_IMG_SRCS ||= %w{http:// https:// www.}
+ ALLOWED_IMG_SRCS ||= %w[http:// https:// www.]
def allowed_hrefs
- @allowed_hrefs ||= begin
- hrefs = SiteSetting.allowed_href_schemes.split("|").map { |scheme| "#{scheme}:" }.to_set
- ALLOWED_IMG_SRCS.each { |src| hrefs << src }
- hrefs << "mailto:"
- hrefs.to_a
- end
+ @allowed_hrefs ||=
+ begin
+ hrefs = SiteSetting.allowed_href_schemes.split("|").map { |scheme| "#{scheme}:" }.to_set
+ ALLOWED_IMG_SRCS.each { |src| hrefs << src }
+ hrefs << "mailto:"
+ hrefs.to_a
+ end
end
def visit_a(node)
@@ -176,11 +180,9 @@ class HtmlToMarkdown
end
end
- ALLOWED ||= %w{kbd del ins small big sub sup dl dd dt mark}
+ ALLOWED ||= %w[kbd del ins small big sub sup dl dd dt mark]
ALLOWED.each do |tag|
- define_method("visit_#{tag}") do |node|
- "<#{tag}>#{traverse(node)}</#{tag}>"
- end
+ define_method("visit_#{tag}") { |node| "<#{tag}>#{traverse(node)}</#{tag}>" }
end
def visit_blockquote(node)
@@ -191,7 +193,7 @@ class HtmlToMarkdown
"\n\n#{text}\n\n"
end
- BLOCKS ||= %w{div tr}
+ BLOCKS ||= %w[div tr]
BLOCKS.each do |tag|
define_method("visit_#{tag}") do |node|
prefix = block?(node.previous_element) ? "" : "\n"
@@ -203,12 +205,8 @@ class HtmlToMarkdown
"\n\n#{traverse(node)}\n\n"
end
- TRAVERSABLES ||= %w{aside font span thead tbody tfooter u}
- TRAVERSABLES.each do |tag|
- define_method("visit_#{tag}") do |node|
- traverse(node)
- end
- end
+ TRAVERSABLES ||= %w[aside font span thead tbody tfooter u]
+ TRAVERSABLES.each { |tag| define_method("visit_#{tag}") { |node| traverse(node) } }
def visit_tt(node)
"`#{traverse(node)}`"
@@ -245,18 +243,10 @@ class HtmlToMarkdown
visit_abbr(node)
end
- (1..6).each do |n|
- define_method("visit_h#{n}") do |node|
- "#{"#" * n} #{traverse(node)}"
- end
- end
+ (1..6).each { |n| define_method("visit_h#{n}") { |node| "#{"#" * n} #{traverse(node)}" } }
- CELLS ||= %w{th td}
- CELLS.each do |tag|
- define_method("visit_#{tag}") do |node|
- "#{traverse(node)} "
- end
- end
+ CELLS ||= %w[th td]
+ CELLS.each { |tag| define_method("visit_#{tag}") { |node| "#{traverse(node)} " } }
def visit_table(node)
if rows = extract_rows(node)
@@ -264,7 +254,8 @@ class HtmlToMarkdown
text = "| " + headers.map { |td| traverse(td).gsub(/\n/, "<br>") }.join(" | ") + " |\n"
text << "| " + (["-"] * headers.size).join(" | ") + " |\n"
rows[1..-1].each do |row|
- text << "| " + row.css("td").map { |td| traverse(td).gsub(/\n/, "<br>") }.join(" | ") + " |\n"
+ text << "| " + row.css("td").map { |td| traverse(td).gsub(/\n/, "<br>") }.join(" | ") +
+ " |\n"
end
"\n\n#{text}\n\n"
else
@@ -280,7 +271,7 @@ class HtmlToMarkdown
rows
end
- LISTS ||= %w{ul ol}
+ LISTS ||= %w[ul ol]
LISTS.each do |tag|
define_method("visit_#{tag}") do |node|
prefix = block?(node.previous_element) ? "" : "\n"
@@ -304,12 +295,12 @@ class HtmlToMarkdown
"#{marker}#{text}#{suffix}"
end
- EMPHASES ||= %w{i em}
+ EMPHASES ||= %w[i em]
EMPHASES.each do |tag|
define_method("visit_#{tag}") do |node|
text = traverse(node)
- return "" if text.empty?
+ return "" if text.empty?
return " " if text.blank?
return "<#{tag}>#{text}</#{tag}>" if text["\n"] || (text["*"] && text["_"])
@@ -321,12 +312,12 @@ class HtmlToMarkdown
end
end
- STRONGS ||= %w{b strong}
+ STRONGS ||= %w[b strong]
STRONGS.each do |tag|
define_method("visit_#{tag}") do |node|
text = traverse(node)
- return "" if text.empty?
+ return "" if text.empty?
return " " if text.blank?
return "<#{tag}>#{text}</#{tag}>" if text["\n"] || (text["*"] && text["_"])
@@ -338,12 +329,12 @@ class HtmlToMarkdown
end
end
- STRIKES ||= %w{s strike}
+ STRIKES ||= %w[s strike]
STRIKES.each do |tag|
define_method("visit_#{tag}") do |node|
text = traverse(node)
- return "" if text.empty?
+ return "" if text.empty?
return " " if text.blank?
return "<#{tag}>#{text}</#{tag}>" if text["\n"] || text["~~"]
@@ -358,7 +349,19 @@ class HtmlToMarkdown
node.text
end
- HTML5_BLOCK_ELEMENTS ||= %w[article aside details dialog figcaption figure footer header main nav section]
+ HTML5_BLOCK_ELEMENTS ||= %w[
+ article
+ aside
+ details
+ dialog
+ figcaption
+ figure
+ footer
+ header
+ main
+ nav
+ section
+ ]
def block?(node)
return false if !node
node.description&.block? || HTML5_BLOCK_ELEMENTS.include?(node.name)
diff --git a/lib/http_language_parser.rb b/lib/http_language_parser.rb
index debfddc604d..a2e24ca0aae 100644
--- a/lib/http_language_parser.rb
+++ b/lib/http_language_parser.rb
@@ -4,10 +4,10 @@ module HttpLanguageParser
def self.parse(header)
# Rails I18n uses underscores between the locale and the region; the request
# headers use hyphens.
- require 'http_accept_language' unless defined? HttpAcceptLanguage
- available_locales = I18n.available_locales.map { |locale| locale.to_s.tr('_', '-') }
+ require "http_accept_language" unless defined?(HttpAcceptLanguage)
+ available_locales = I18n.available_locales.map { |locale| locale.to_s.tr("_", "-") }
parser = HttpAcceptLanguage::Parser.new(header)
- matched = parser.language_region_compatible_from(available_locales)&.tr('-', '_')
+ matched = parser.language_region_compatible_from(available_locales)&.tr("-", "_")
matched || SiteSetting.default_locale
end
end
diff --git a/lib/i18n/backend/discourse_i18n.rb b/lib/i18n/backend/discourse_i18n.rb
index 1511e67e961..4b1e24e9ec6 100644
--- a/lib/i18n/backend/discourse_i18n.rb
+++ b/lib/i18n/backend/discourse_i18n.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'i18n/backend/pluralization'
+require "i18n/backend/pluralization"
module I18n
module Backend
@@ -22,9 +22,7 @@ module I18n
# force explicit loading
def load_translations(*filenames)
unless filenames.empty?
- self.class.sort_locale_files(filenames.flatten).each do |filename|
- load_file(filename)
- end
+ self.class.sort_locale_files(filenames.flatten).each { |filename| load_file(filename) }
end
end
@@ -90,10 +88,12 @@ module I18n
if overrides
if options[:count]
if !existing_translations
- I18n.fallbacks[locale].drop(1).each do |fallback|
- existing_translations = super(fallback, key, scope, options)
- break if existing_translations.present?
- end
+ I18n.fallbacks[locale]
+ .drop(1)
+ .each do |fallback|
+ existing_translations = super(fallback, key, scope, options)
+ break if existing_translations.present?
+ end
end
if existing_translations
@@ -106,9 +106,11 @@ module I18n
result = {}
- remapped_translations.merge(overrides).each do |k, v|
- result[k.split('.').last.to_sym] = v if k != key && k.start_with?(key)
- end
+ remapped_translations
+ .merge(overrides)
+ .each do |k, v|
+ result[k.split(".").last.to_sym] = v if k != key && k.start_with?(key)
+ end
return result if result.size > 0
end
end
diff --git a/lib/i18n/duplicate_key_finder.rb b/lib/i18n/duplicate_key_finder.rb
index 65b0f33d0e9..4abd6300ff9 100644
--- a/lib/i18n/duplicate_key_finder.rb
+++ b/lib/i18n/duplicate_key_finder.rb
@@ -3,7 +3,6 @@
require "locale_file_walker"
class DuplicateKeyFinder < LocaleFileWalker
-
def find_duplicates(path)
@keys_with_count = Hash.new { 0 }
handle_document(Psych.parse_file(path))
@@ -14,6 +13,6 @@ class DuplicateKeyFinder < LocaleFileWalker
def handle_scalar(node, depth, parents)
super
- @keys_with_count[parents.join('.')] += 1
+ @keys_with_count[parents.join(".")] += 1
end
end
diff --git a/lib/i18n/locale_file_checker.rb b/lib/i18n/locale_file_checker.rb
index 4d0088ab8c6..de9eae3056c 100644
--- a/lib/i18n/locale_file_checker.rb
+++ b/lib/i18n/locale_file_checker.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'i18n/i18n_interpolation_keys_finder'
-require 'yaml'
+require "i18n/i18n_interpolation_keys_finder"
+require "yaml"
class LocaleFileChecker
TYPE_MISSING_INTERPOLATION_KEYS = 1
@@ -17,7 +17,8 @@ class LocaleFileChecker
locale_files.each do |locale_path|
next unless reference_path = reference_file(locale_path)
- @relative_locale_path = Pathname.new(locale_path).relative_path_from(Pathname.new(Rails.root)).to_s
+ @relative_locale_path =
+ Pathname.new(locale_path).relative_path_from(Pathname.new(Rails.root)).to_s
@locale_yaml = YAML.load_file(locale_path)
@reference_yaml = YAML.load_file(reference_path)
@@ -34,14 +35,14 @@ class LocaleFileChecker
private
- YML_DIRS = ["config/locales", "plugins/**/locales"]
+ YML_DIRS = %w[config/locales plugins/**/locales]
PLURALS_FILE = "config/locales/plurals.rb"
REFERENCE_LOCALE = "en"
- REFERENCE_PLURAL_KEYS = ["one", "other"]
+ REFERENCE_PLURAL_KEYS = %w[one other]
# Some languages should always use %{count} in pluralized strings.
# https://meta.discourse.org/t/always-use-count-variable-when-translating-pluralized-strings/83969
- FORCE_PLURAL_COUNT_LOCALES = ["bs", "fr", "lt", "lv", "ru", "sl", "sr", "uk"]
+ FORCE_PLURAL_COUNT_LOCALES = %w[bs fr lt lv ru sl sr uk]
def locale_files
YML_DIRS.map { |dir| Dir["#{Rails.root}/#{dir}/{client,server}.#{@locale}.yml"] }.flatten
@@ -92,8 +93,17 @@ class LocaleFileChecker
missing_keys.delete("count")
end
- add_error(keys, TYPE_MISSING_INTERPOLATION_KEYS, missing_keys, pluralized: pluralized) unless missing_keys.empty?
- add_error(keys, TYPE_UNSUPPORTED_INTERPOLATION_KEYS, unsupported_keys, pluralized: pluralized) unless unsupported_keys.empty?
+ unless missing_keys.empty?
+ add_error(keys, TYPE_MISSING_INTERPOLATION_KEYS, missing_keys, pluralized: pluralized)
+ end
+ unless unsupported_keys.empty?
+ add_error(
+ keys,
+ TYPE_UNSUPPORTED_INTERPOLATION_KEYS,
+ unsupported_keys,
+ pluralized: pluralized,
+ )
+ end
end
end
@@ -123,12 +133,15 @@ class LocaleFileChecker
actual_plural_keys = parent.is_a?(Hash) ? parent.keys : []
missing_plural_keys = expected_plural_keys - actual_plural_keys
- add_error(keys, TYPE_MISSING_PLURAL_KEYS, missing_plural_keys, pluralized: true) unless missing_plural_keys.empty?
+ unless missing_plural_keys.empty?
+ add_error(keys, TYPE_MISSING_PLURAL_KEYS, missing_plural_keys, pluralized: true)
+ end
end
end
def check_message_format
- mf_locale, mf_filename = JsLocaleHelper.find_message_format_locale([@locale], fallback_to_english: true)
+ mf_locale, mf_filename =
+ JsLocaleHelper.find_message_format_locale([@locale], fallback_to_english: true)
traverse_hash(@locale_yaml, []) do |keys, value|
next unless keys.last.ends_with?("_MF")
@@ -158,17 +171,18 @@ class LocaleFileChecker
end
def reference_value_pluralized?(value)
- value.is_a?(Hash) &&
- value.keys.sort == REFERENCE_PLURAL_KEYS &&
+ value.is_a?(Hash) && value.keys.sort == REFERENCE_PLURAL_KEYS &&
value.keys.all? { |k| value[k].is_a?(String) }
end
def plural_keys
- @plural_keys ||= begin
- eval(File.read("#{Rails.root}/#{PLURALS_FILE}")).map do |locale, value| # rubocop:disable Security/Eval
- [locale.to_s, value[:i18n][:plural][:keys].map(&:to_s)]
- end.to_h
- end
+ @plural_keys ||=
+ begin
+ # rubocop:disable Security/Eval
+ eval(File.read("#{Rails.root}/#{PLURALS_FILE}"))
+ .map { |locale, value| [locale.to_s, value[:i18n][:plural][:keys].map(&:to_s)] }
+ .to_h
+ end
end
def add_error(keys, type, details, pluralized:)
@@ -180,10 +194,6 @@ class LocaleFileChecker
joined_key = keys[1..-1].join(".")
end
- @errors[@relative_locale_path] << {
- key: joined_key,
- type: type,
- details: details.to_s
- }
+ @errors[@relative_locale_path] << { key: joined_key, type: type, details: details.to_s }
end
end
diff --git a/lib/i18n/locale_file_walker.rb b/lib/i18n/locale_file_walker.rb
index facc7235c02..94c27dc3368 100644
--- a/lib/i18n/locale_file_walker.rb
+++ b/lib/i18n/locale_file_walker.rb
@@ -22,7 +22,11 @@ class LocaleFileWalker
def handle_node(node, depth, parents, consecutive_scalars)
if node_is_scalar = node.is_a?(Psych::Nodes::Scalar)
- valid_scalar?(depth, consecutive_scalars) ? handle_scalar(node, depth, parents) : handle_value(node.value, parents)
+ if valid_scalar?(depth, consecutive_scalars)
+ handle_scalar(node, depth, parents)
+ else
+ handle_value(node.value, parents)
+ end
elsif node.is_a?(Psych::Nodes::Alias)
handle_alias(node, depth, parents)
elsif node.is_a?(Psych::Nodes::Mapping)
diff --git a/lib/image_sizer.rb b/lib/image_sizer.rb
index ddb86396d58..29118b39402 100644
--- a/lib/image_sizer.rb
+++ b/lib/image_sizer.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module ImageSizer
-
# Resize an image to the aspect ratio we want
def self.resize(width, height, opts = {})
return if width.blank? || height.blank?
@@ -12,7 +11,7 @@ module ImageSizer
w = width.to_f
h = height.to_f
- return [w.floor, h.floor] if w <= max_width && h <= max_height
+ return w.floor, h.floor if w <= max_width && h <= max_height
ratio = [max_width / w, max_height / h].min
[(w * ratio).floor, (h * ratio).floor]
@@ -27,11 +26,10 @@ module ImageSizer
w = width.to_f
h = height.to_f
- return [w.floor, h.floor] if w <= max_width && h <= max_height
+ return w.floor, h.floor if w <= max_width && h <= max_height
ratio = max_width / w
[[max_width, w].min.floor, [max_height, (h * ratio)].min.floor]
end
-
end
diff --git a/lib/imap/providers/detector.rb b/lib/imap/providers/detector.rb
index 41f356517e3..7ad50c4ea28 100644
--- a/lib/imap/providers/detector.rb
+++ b/lib/imap/providers/detector.rb
@@ -4,7 +4,7 @@ module Imap
module Providers
class Detector
def self.init_with_detected_provider(config)
- if config[:server] == 'imap.gmail.com'
+ if config[:server] == "imap.gmail.com"
return Imap::Providers::Gmail.new(config[:server], config)
end
Imap::Providers::Generic.new(config[:server], config)
diff --git a/lib/imap/providers/generic.rb b/lib/imap/providers/generic.rb
index 53ec57459d0..59f43d35f2d 100644
--- a/lib/imap/providers/generic.rb
+++ b/lib/imap/providers/generic.rb
@@ -1,10 +1,11 @@
# frozen_string_literal: true
-require 'net/imap'
+require "net/imap"
module Imap
module Providers
- class WriteDisabledError < StandardError; end
+ class WriteDisabledError < StandardError
+ end
class TrashedMailResponse
attr_accessor :trashed_emails, :trash_uid_validity
@@ -50,12 +51,16 @@ module Imap
end
def disconnect!
- imap.logout rescue nil
+ begin
+ imap.logout
+ rescue StandardError
+ nil
+ end
imap.disconnect
end
def can?(capability)
- @capabilities ||= imap.responses['CAPABILITY'][-1] || imap.capability
+ @capabilities ||= imap.responses["CAPABILITY"][-1] || imap.capability
@capabilities.include?(capability)
end
@@ -67,22 +72,23 @@ module Imap
elsif opts[:to]
imap.uid_search("UID 1:#{opts[:to]}")
else
- imap.uid_search('ALL')
+ imap.uid_search("ALL")
end
end
def labels
- @labels ||= begin
- labels = {}
-
- list_mailboxes.each do |name|
- if tag = to_tag(name)
- labels[tag] = name
+ @labels ||=
+ begin
+ labels = {}
+
+ list_mailboxes.each do |name|
+ if tag = to_tag(name)
+ labels[tag] = name
+ end
end
- end
- labels
- end
+ labels
+ end
end
def open_mailbox(mailbox_name, write: false)
@@ -98,9 +104,7 @@ module Imap
@open_mailbox_name = mailbox_name
@open_mailbox_write = write
- {
- uid_validity: imap.responses['UIDVALIDITY'][-1]
- }
+ { uid_validity: imap.responses["UIDVALIDITY"][-1] }
end
def emails(uids, fields, opts = {})
@@ -114,9 +118,7 @@ module Imap
fetched.map do |email|
attributes = {}
- fields.each do |field|
- attributes[field] = email.attr[field]
- end
+ fields.each { |field| attributes[field] = email.attr[field] }
attributes
end
@@ -131,11 +133,11 @@ module Imap
def to_tag(label)
label = DiscourseTagging.clean_tag(label.to_s)
- label if label != 'inbox' && label != 'sent'
+ label if label != "inbox" && label != "sent"
end
def tag_to_flag(tag)
- :Seen if tag == 'seen'
+ :Seen if tag == "seen"
end
def tag_to_label(tag)
@@ -150,24 +152,25 @@ module Imap
def list_mailboxes_with_attributes(attr_filter = nil)
# Basically, list all mailboxes in the root of the server.
# ref: https://tools.ietf.org/html/rfc3501#section-6.3.8
- imap.list('', '*').reject do |m|
-
- # Noselect cannot be selected with the SELECT command.
- # technically we could use this for readonly mode when
- # SiteSetting.imap_write is disabled...maybe a later TODO
- # ref: https://tools.ietf.org/html/rfc3501#section-7.2.2
- m.attr.include?(:Noselect)
- end.select do |m|
-
- # There are Special-Use mailboxes denoted by an attribute. For
- # example, some common ones are \Trash or \Sent.
- # ref: https://tools.ietf.org/html/rfc6154
- if attr_filter
- m.attr.include? attr_filter
- else
- true
+ imap
+ .list("", "*")
+ .reject do |m|
+ # Noselect cannot be selected with the SELECT command.
+ # technically we could use this for readonly mode when
+ # SiteSetting.imap_write is disabled...maybe a later TODO
+ # ref: https://tools.ietf.org/html/rfc3501#section-7.2.2
+ m.attr.include?(:Noselect)
+ end
+ .select do |m|
+ # There are Special-Use mailboxes denoted by an attribute. For
+ # example, some common ones are \Trash or \Sent.
+ # ref: https://tools.ietf.org/html/rfc6154
+ if attr_filter
+ m.attr.include? attr_filter
+ else
+ true
+ end
end
- end
end
def filter_mailboxes(mailboxes)
@@ -186,16 +189,20 @@ module Imap
# Look for the special Trash XLIST attribute.
def trash_mailbox
- Discourse.cache.fetch("imap_trash_mailbox_#{account_digest}", expires_in: 30.minutes) do
- list_mailboxes(:Trash).first
- end
+ Discourse
+ .cache
+ .fetch("imap_trash_mailbox_#{account_digest}", expires_in: 30.minutes) do
+ list_mailboxes(:Trash).first
+ end
end
# Look for the special Junk XLIST attribute.
def spam_mailbox
- Discourse.cache.fetch("imap_spam_mailbox_#{account_digest}", expires_in: 30.minutes) do
- list_mailboxes(:Junk).first
- end
+ Discourse
+ .cache
+ .fetch("imap_spam_mailbox_#{account_digest}", expires_in: 30.minutes) do
+ list_mailboxes(:Junk).first
+ end
end
# open the trash mailbox for inspection or writing. after the yield we
@@ -232,14 +239,19 @@ module Imap
def find_trashed_by_message_ids(message_ids)
trashed_emails = []
- trash_uid_validity = open_trash_mailbox do
- trashed_email_uids = find_uids_by_message_ids(message_ids)
- if trashed_email_uids.any?
- trashed_emails = emails(trashed_email_uids, ["UID", "ENVELOPE"]).map do |e|
- BasicMail.new(message_id: Email::MessageIdService.message_id_clean(e['ENVELOPE'].message_id), uid: e['UID'])
+ trash_uid_validity =
+ open_trash_mailbox do
+ trashed_email_uids = find_uids_by_message_ids(message_ids)
+ if trashed_email_uids.any?
+ trashed_emails =
+ emails(trashed_email_uids, %w[UID ENVELOPE]).map do |e|
+ BasicMail.new(
+ message_id: Email::MessageIdService.message_id_clean(e["ENVELOPE"].message_id),
+ uid: e["UID"],
+ )
+ end
end
end
- end
TrashedMailResponse.new.tap do |resp|
resp.trashed_emails = trashed_emails
@@ -249,14 +261,19 @@ module Imap
def find_spam_by_message_ids(message_ids)
spam_emails = []
- spam_uid_validity = open_spam_mailbox do
- spam_email_uids = find_uids_by_message_ids(message_ids)
- if spam_email_uids.any?
- spam_emails = emails(spam_email_uids, ["UID", "ENVELOPE"]).map do |e|
- BasicMail.new(message_id: Email::MessageIdService.message_id_clean(e['ENVELOPE'].message_id), uid: e['UID'])
+ spam_uid_validity =
+ open_spam_mailbox do
+ spam_email_uids = find_uids_by_message_ids(message_ids)
+ if spam_email_uids.any?
+ spam_emails =
+ emails(spam_email_uids, %w[UID ENVELOPE]).map do |e|
+ BasicMail.new(
+ message_id: Email::MessageIdService.message_id_clean(e["ENVELOPE"].message_id),
+ uid: e["UID"],
+ )
+ end
end
end
- end
SpamMailResponse.new.tap do |resp|
resp.spam_emails = spam_emails
@@ -265,13 +282,14 @@ module Imap
end
def find_uids_by_message_ids(message_ids)
- header_message_id_terms = message_ids.map do |msgid|
- "HEADER Message-ID '#{Email::MessageIdService.message_id_rfc_format(msgid)}'"
- end
+ header_message_id_terms =
+ message_ids.map do |msgid|
+ "HEADER Message-ID '#{Email::MessageIdService.message_id_rfc_format(msgid)}'"
+ end
# OR clauses are written in Polish notation...so the query looks like this:
# OR OR HEADER Message-ID XXXX HEADER Message-ID XXXX HEADER Message-ID XXXX
- or_clauses = 'OR ' * (header_message_id_terms.length - 1)
+ or_clauses = "OR " * (header_message_id_terms.length - 1)
query = "#{or_clauses}#{header_message_id_terms.join(" ")}"
imap.uid_search(query)
@@ -280,17 +298,16 @@ module Imap
def trash(uid)
# MOVE is way easier than doing the COPY \Deleted EXPUNGE dance ourselves.
# It is supported by Gmail and Outlook.
- if can?('MOVE')
+ if can?("MOVE")
trash_move(uid)
else
-
# default behaviour for IMAP servers is to add the \Deleted flag
# then EXPUNGE the mailbox which permanently deletes these messages
# https://tools.ietf.org/html/rfc3501#section-6.4.3
#
# TODO: We may want to add the option at some point to copy to some
# other mailbox first before doing this (e.g. Trash)
- store(uid, 'FLAGS', [], ["\\Deleted"])
+ store(uid, "FLAGS", [], ["\\Deleted"])
imap.expunge
end
end
diff --git a/lib/imap/providers/gmail.rb b/lib/imap/providers/gmail.rb
index 7ac51f73042..fc888d66eda 100644
--- a/lib/imap/providers/gmail.rb
+++ b/lib/imap/providers/gmail.rb
@@ -8,61 +8,58 @@ module Imap
# all UIDs in a thread must have the \\Inbox label removed.
#
class Gmail < Generic
- X_GM_LABELS = 'X-GM-LABELS'
- X_GM_THRID = 'X-GM-THRID'
+ X_GM_LABELS = "X-GM-LABELS"
+ X_GM_THRID = "X-GM-THRID"
def imap
@imap ||= super.tap { |imap| apply_gmail_patch(imap) }
end
def emails(uids, fields, opts = {})
-
# gmail has a special header for labels
- if fields.include?('LABELS')
- fields[fields.index('LABELS')] = X_GM_LABELS
- end
+ fields[fields.index("LABELS")] = X_GM_LABELS if fields.include?("LABELS")
emails = super(uids, fields, opts)
emails.each do |email|
- email['LABELS'] = Array(email['LABELS'])
+ email["LABELS"] = Array(email["LABELS"])
if email[X_GM_LABELS]
- email['LABELS'] << Array(email.delete(X_GM_LABELS))
- email['LABELS'].flatten!
+ email["LABELS"] << Array(email.delete(X_GM_LABELS))
+ email["LABELS"].flatten!
end
- email['LABELS'] << '\\Inbox' if @open_mailbox_name == 'INBOX'
+ email["LABELS"] << '\\Inbox' if @open_mailbox_name == "INBOX"
- email['LABELS'].uniq!
+ email["LABELS"].uniq!
end
emails
end
def store(uid, attribute, old_set, new_set)
- attribute = X_GM_LABELS if attribute == 'LABELS'
+ attribute = X_GM_LABELS if attribute == "LABELS"
super(uid, attribute, old_set, new_set)
end
def to_tag(label)
# Label `\\Starred` is Gmail equivalent of :Flagged (both present)
- return 'starred' if label == :Flagged
- return if label == '[Gmail]/All Mail'
+ return "starred" if label == :Flagged
+ return if label == "[Gmail]/All Mail"
- label = label.to_s.gsub('[Gmail]/', '')
+ label = label.to_s.gsub("[Gmail]/", "")
super(label)
end
def tag_to_flag(tag)
- return :Flagged if tag == 'starred'
+ return :Flagged if tag == "starred"
super(tag)
end
def tag_to_label(tag)
- return '\\Important' if tag == 'important'
- return '\\Starred' if tag == 'starred'
+ return '\\Important' if tag == "important"
+ return '\\Starred' if tag == "starred"
super(tag)
end
@@ -73,11 +70,14 @@ module Imap
thread_id = thread_id_from_uid(uid)
emails_to_archive = emails_in_thread(thread_id)
emails_to_archive.each do |email|
- labels = email['LABELS']
+ labels = email["LABELS"]
new_labels = labels.reject { |l| l == "\\Inbox" }
store(email["UID"], "LABELS", labels, new_labels)
end
- ImapSyncLog.log("Thread ID #{thread_id} (UID #{uid}) archived in Gmail mailbox for #{@username}", :debug)
+ ImapSyncLog.log(
+ "Thread ID #{thread_id} (UID #{uid}) archived in Gmail mailbox for #{@username}",
+ :debug,
+ )
end
# Though Gmail considers the email thread unarchived if the first email
@@ -87,36 +87,38 @@ module Imap
thread_id = thread_id_from_uid(uid)
emails_to_unarchive = emails_in_thread(thread_id)
emails_to_unarchive.each do |email|
- labels = email['LABELS']
+ labels = email["LABELS"]
new_labels = labels.dup
- if !new_labels.include?("\\Inbox")
- new_labels << "\\Inbox"
- end
+ new_labels << "\\Inbox" if !new_labels.include?("\\Inbox")
store(email["UID"], "LABELS", labels, new_labels)
end
- ImapSyncLog.log("Thread ID #{thread_id} (UID #{uid}) unarchived in Gmail mailbox for #{@username}", :debug)
+ ImapSyncLog.log(
+ "Thread ID #{thread_id} (UID #{uid}) unarchived in Gmail mailbox for #{@username}",
+ :debug,
+ )
end
def thread_id_from_uid(uid)
fetched = imap.uid_fetch(uid, [X_GM_THRID])
- if !fetched
- raise "Thread not found for UID #{uid}!"
- end
+ raise "Thread not found for UID #{uid}!" if !fetched
fetched.last.attr[X_GM_THRID]
end
def emails_in_thread(thread_id)
uids_to_fetch = imap.uid_search("#{X_GM_THRID} #{thread_id}")
- emails(uids_to_fetch, ["UID", "LABELS"])
+ emails(uids_to_fetch, %w[UID LABELS])
end
def trash_move(uid)
thread_id = thread_id_from_uid(uid)
- email_uids_to_trash = emails_in_thread(thread_id).map { |e| e['UID'] }
+ email_uids_to_trash = emails_in_thread(thread_id).map { |e| e["UID"] }
imap.uid_move(email_uids_to_trash, trash_mailbox)
- ImapSyncLog.log("Thread ID #{thread_id} (UID #{uid}) trashed in Gmail mailbox for #{@username}", :debug)
+ ImapSyncLog.log(
+ "Thread ID #{thread_id} (UID #{uid}) trashed in Gmail mailbox for #{@username}",
+ :debug,
+ )
{ trash_uid_validity: open_trash_mailbox, email_uids_to_trash: email_uids_to_trash }
end
@@ -124,16 +126,15 @@ module Imap
# used for the dropdown in the UI where we allow the user to select the
# IMAP mailbox to sync with.
def filter_mailboxes(mailboxes_with_attributes)
- mailboxes_with_attributes.reject do |mb|
- (mb.attr & [:Drafts, :Sent, :Junk, :Flagged, :Trash]).any?
- end.map(&:name)
+ mailboxes_with_attributes
+ .reject { |mb| (mb.attr & %i[Drafts Sent Junk Flagged Trash]).any? }
+ .map(&:name)
end
private
def apply_gmail_patch(imap)
- class << imap.instance_variable_get('@parser')
-
+ class << imap.instance_variable_get("@parser")
# Modified version of the original `msg_att` from here:
# https://github.com/ruby/ruby/blob/1cc8ff001da217d0e98d13fe61fbc9f5547ef722/lib/net/imap.rb#L2346
#
@@ -172,15 +173,14 @@ module Imap
when /\A(?:MODSEQ)\z/ni
name, val = modseq_data
- # Adding support for GMail extended attributes.
+ # Adding support for GMail extended attributes.
when /\A(?:X-GM-LABELS)\z/ni
name, val = label_data
when /\A(?:X-GM-MSGID)\z/ni
name, val = uid_data
when /\A(?:X-GM-THRID)\z/ni
name, val = uid_data
- # End custom support for Gmail.
-
+ # End custom support for Gmail.
else
parse_error("unknown attribute `%s' for {%d}", token.value, n)
end
diff --git a/lib/imap/sync.rb b/lib/imap/sync.rb
index be5b32fb0d4..0d9220131ea 100644
--- a/lib/imap/sync.rb
+++ b/lib/imap/sync.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'net/imap'
+require "net/imap"
module Imap
class Sync
@@ -23,13 +23,13 @@ module Imap
end
def can_idle?
- SiteSetting.enable_imap_idle && @provider.can?('IDLE')
+ SiteSetting.enable_imap_idle && @provider.can?("IDLE")
end
def process(idle: false, import_limit: nil, old_emails_limit: nil, new_emails_limit: nil)
- raise 'disconnected' if disconnected?
+ raise "disconnected" if disconnected?
- import_limit ||= SiteSetting.imap_batch_import_email
+ import_limit ||= SiteSetting.imap_batch_import_email
old_emails_limit ||= SiteSetting.imap_polling_old_emails
new_emails_limit ||= SiteSetting.imap_polling_new_emails
@@ -43,30 +43,42 @@ module Imap
# If UID validity changes, the whole mailbox must be synchronized (all
# emails are considered new and will be associated to existent topics
# in Email::Receiver by matching Message-Ids).
- ImapSyncLog.warn("UIDVALIDITY = #{@status[:uid_validity]} does not match expected #{@group.imap_uid_validity}, invalidating IMAP cache and resyncing emails for mailbox #{@group.imap_mailbox_name}", @group)
+ ImapSyncLog.warn(
+ "UIDVALIDITY = #{@status[:uid_validity]} does not match expected #{@group.imap_uid_validity}, invalidating IMAP cache and resyncing emails for mailbox #{@group.imap_mailbox_name}",
+ @group,
+ )
@group.imap_last_uid = 0
end
if idle && !can_idle?
- ImapSyncLog.warn("IMAP server for group cannot IDLE or imap idle site setting is disabled", @group)
+ ImapSyncLog.warn(
+ "IMAP server for group cannot IDLE or imap idle site setting is disabled",
+ @group,
+ )
idle = false
end
if idle
- raise 'IMAP IDLE is disabled' if !SiteSetting.enable_imap_idle
+ raise "IMAP IDLE is disabled" if !SiteSetting.enable_imap_idle
# Thread goes into sleep and it is better to return any connection
# back to the pool.
ActiveRecord::Base.connection_handler.clear_active_connections!
idle_polling_mins = SiteSetting.imap_polling_period_mins.minutes.to_i
- ImapSyncLog.debug("Going IDLE for #{idle_polling_mins} seconds to wait for more work", @group, db: false)
+ ImapSyncLog.debug(
+ "Going IDLE for #{idle_polling_mins} seconds to wait for more work",
+ @group,
+ db: false,
+ )
- @provider.imap.idle(idle_polling_mins) do |resp|
- if resp.kind_of?(Net::IMAP::UntaggedResponse) && resp.name == 'EXISTS'
- @provider.imap.idle_done
+ @provider
+ .imap
+ .idle(idle_polling_mins) do |resp|
+ if resp.kind_of?(Net::IMAP::UntaggedResponse) && resp.name == "EXISTS"
+ @provider.imap.idle_done
+ end
end
- end
end
# Fetching UIDs of old (already imported into Discourse, but might need
@@ -82,7 +94,10 @@ module Imap
# Sometimes, new_uids contains elements from old_uids.
new_uids = new_uids - old_uids
- ImapSyncLog.debug("Remote email server has #{old_uids.size} old emails and #{new_uids.size} new emails", @group)
+ ImapSyncLog.debug(
+ "Remote email server has #{old_uids.size} old emails and #{new_uids.size} new emails",
+ @group,
+ )
all_old_uids_size = old_uids.size
all_new_uids_size = new_uids.size
@@ -90,7 +105,7 @@ module Imap
@group.update_columns(
imap_last_error: nil,
imap_old_emails: all_old_uids_size,
- imap_new_emails: all_new_uids_size
+ imap_new_emails: all_new_uids_size,
)
import_mode = import_limit > -1 && new_uids.size > import_limit
@@ -112,10 +127,10 @@ module Imap
end
def update_topic(email, incoming_email, opts = {})
- return if !incoming_email ||
- incoming_email.imap_sync ||
- !incoming_email.topic ||
- incoming_email.post&.post_number != 1
+ if !incoming_email || incoming_email.imap_sync || !incoming_email.topic ||
+ incoming_email.post&.post_number != 1
+ return
+ end
update_topic_archived_state(email, incoming_email, opts)
update_topic_tags(email, incoming_email, opts)
@@ -125,33 +140,41 @@ module Imap
def process_old_uids(old_uids)
ImapSyncLog.debug("Syncing #{old_uids.size} randomly-selected old emails", @group)
- emails = old_uids.empty? ? [] : @provider.emails(old_uids, ['UID', 'FLAGS', 'LABELS', 'ENVELOPE'])
+ emails = old_uids.empty? ? [] : @provider.emails(old_uids, %w[UID FLAGS LABELS ENVELOPE])
emails.each do |email|
- incoming_email = IncomingEmail.find_by(
- imap_uid_validity: @status[:uid_validity],
- imap_uid: email['UID'],
- imap_group_id: @group.id
- )
+ incoming_email =
+ IncomingEmail.find_by(
+ imap_uid_validity: @status[:uid_validity],
+ imap_uid: email["UID"],
+ imap_group_id: @group.id,
+ )
if incoming_email.present?
update_topic(email, incoming_email, mailbox_name: @group.imap_mailbox_name)
else
# try finding email by message-id instead, we may be able to set the uid etc.
- incoming_email = IncomingEmail.where(
- message_id: Email::MessageIdService.message_id_clean(email['ENVELOPE'].message_id),
- imap_uid: nil,
- imap_uid_validity: nil
- ).where("to_addresses LIKE ?", "%#{@group.email_username}%").first
+ incoming_email =
+ IncomingEmail
+ .where(
+ message_id: Email::MessageIdService.message_id_clean(email["ENVELOPE"].message_id),
+ imap_uid: nil,
+ imap_uid_validity: nil,
+ )
+ .where("to_addresses LIKE ?", "%#{@group.email_username}%")
+ .first
if incoming_email
incoming_email.update(
imap_uid_validity: @status[:uid_validity],
- imap_uid: email['UID'],
- imap_group_id: @group.id
+ imap_uid: email["UID"],
+ imap_group_id: @group.id,
)
update_topic(email, incoming_email, mailbox_name: @group.imap_mailbox_name)
else
- ImapSyncLog.warn("Could not find old email (UIDVALIDITY = #{@status[:uid_validity]}, UID = #{email['UID']})", @group)
+ ImapSyncLog.warn(
+ "Could not find old email (UIDVALIDITY = #{@status[:uid_validity]}, UID = #{email["UID"]})",
+ @group,
+ )
end
end
end
@@ -165,15 +188,18 @@ module Imap
# if they have been deleted and if so delete the associated post/topic. then the remaining we
# can just remove the imap details from the IncomingEmail table and if they end up back in the
# original mailbox then they will be picked up in a future resync.
- existing_incoming = IncomingEmail.includes(:post).where(
- imap_group_id: @group.id, imap_uid_validity: @status[:uid_validity]
- ).where.not(imap_uid: nil)
+ existing_incoming =
+ IncomingEmail
+ .includes(:post)
+ .where(imap_group_id: @group.id, imap_uid_validity: @status[:uid_validity])
+ .where.not(imap_uid: nil)
existing_uids = existing_incoming.map(&:imap_uid)
missing_uids = existing_uids - old_uids
- missing_message_ids = existing_incoming.select do |incoming|
- missing_uids.include?(incoming.imap_uid)
- end.map(&:message_id)
+ missing_message_ids =
+ existing_incoming
+ .select { |incoming| missing_uids.include?(incoming.imap_uid) }
+ .map(&:message_id)
return if missing_message_ids.empty?
@@ -183,7 +209,8 @@ module Imap
potential_spam = []
response = @provider.find_trashed_by_message_ids(missing_message_ids)
existing_incoming.each do |incoming|
- matching_trashed = response.trashed_emails.find { |email| email.message_id == incoming.message_id }
+ matching_trashed =
+ response.trashed_emails.find { |email| email.message_id == incoming.message_id }
if !matching_trashed
potential_spam << incoming
@@ -194,13 +221,22 @@ module Imap
# not exist, and this sync is just updating the old UIDs to the new ones
# in the trash, and we don't need to re-destroy the post
if incoming.post
- ImapSyncLog.debug("Deleting post ID #{incoming.post_id}, topic id #{incoming.topic_id}; email has been deleted on the IMAP server.", @group)
+ ImapSyncLog.debug(
+ "Deleting post ID #{incoming.post_id}, topic id #{incoming.topic_id}; email has been deleted on the IMAP server.",
+ @group,
+ )
PostDestroyer.new(Discourse.system_user, incoming.post).destroy
end
# the email has moved mailboxes, we don't want to try trashing again next time
- ImapSyncLog.debug("Updating incoming ID #{incoming.id} uid data FROM [UID #{incoming.imap_uid} | UIDVALIDITY #{incoming.imap_uid_validity}] TO [UID #{matching_trashed.uid} | UIDVALIDITY #{response.trash_uid_validity}] (TRASHED)", @group)
- incoming.update(imap_uid_validity: response.trash_uid_validity, imap_uid: matching_trashed.uid)
+ ImapSyncLog.debug(
+ "Updating incoming ID #{incoming.id} uid data FROM [UID #{incoming.imap_uid} | UIDVALIDITY #{incoming.imap_uid_validity}] TO [UID #{matching_trashed.uid} | UIDVALIDITY #{response.trash_uid_validity}] (TRASHED)",
+ @group,
+ )
+ incoming.update(
+ imap_uid_validity: response.trash_uid_validity,
+ imap_uid: matching_trashed.uid,
+ )
end
# This can be done because Message-ID is unique on a mail server between mailboxes,
@@ -208,12 +244,16 @@ module Imap
# the new UID from the spam.
response = @provider.find_spam_by_message_ids(missing_message_ids)
potential_spam.each do |incoming|
- matching_spam = response.spam_emails.find { |email| email.message_id == incoming.message_id }
+ matching_spam =
+ response.spam_emails.find { |email| email.message_id == incoming.message_id }
# if the email is not in the trash or spam then we don't know where it is... could
# be in any mailbox on the server or could be permanently deleted.
if !matching_spam
- ImapSyncLog.debug("Email for incoming ID #{incoming.id} (#{incoming.message_id}) could not be found in the group mailbox, trash, or spam. It could be in another mailbox or permanently deleted.", @group)
+ ImapSyncLog.debug(
+ "Email for incoming ID #{incoming.id} (#{incoming.message_id}) could not be found in the group mailbox, trash, or spam. It could be in another mailbox or permanently deleted.",
+ @group,
+ )
incoming.update(imap_missing: true)
next
end
@@ -222,12 +262,18 @@ module Imap
# not exist, and this sync is just updating the old UIDs to the new ones
# in the spam, and we don't need to re-destroy the post
if incoming.post
- ImapSyncLog.debug("Deleting post ID #{incoming.post_id}, topic id #{incoming.topic_id}; email has been moved to spam on the IMAP server.", @group)
+ ImapSyncLog.debug(
+ "Deleting post ID #{incoming.post_id}, topic id #{incoming.topic_id}; email has been moved to spam on the IMAP server.",
+ @group,
+ )
PostDestroyer.new(Discourse.system_user, incoming.post).destroy
end
# the email has moved mailboxes, we don't want to try marking as spam again next time
- ImapSyncLog.debug("Updating incoming ID #{incoming.id} uid data FROM [UID #{incoming.imap_uid} | UIDVALIDITY #{incoming.imap_uid_validity}] TO [UID #{matching_spam.uid} | UIDVALIDITY #{response.spam_uid_validity}] (SPAM)", @group)
+ ImapSyncLog.debug(
+ "Updating incoming ID #{incoming.id} uid data FROM [UID #{incoming.imap_uid} | UIDVALIDITY #{incoming.imap_uid_validity}] TO [UID #{matching_spam.uid} | UIDVALIDITY #{response.spam_uid_validity}] (SPAM)",
+ @group,
+ )
incoming.update(imap_uid_validity: response.spam_uid_validity, imap_uid: matching_spam.uid)
end
end
@@ -235,7 +281,7 @@ module Imap
def process_new_uids(new_uids, import_mode, all_old_uids_size, all_new_uids_size)
ImapSyncLog.debug("Syncing #{new_uids.size} new emails (oldest first)", @group)
- emails = @provider.emails(new_uids, ['UID', 'FLAGS', 'LABELS', 'RFC822'])
+ emails = @provider.emails(new_uids, %w[UID FLAGS LABELS RFC822])
processed = 0
# TODO (maybe): We might need something here to exclusively handle
@@ -247,29 +293,33 @@ module Imap
# (for example replies must be processed after the original email
# to have a topic where the reply can be posted).
begin
- receiver = Email::Receiver.new(
- email['RFC822'],
- allow_auto_generated: true,
- import_mode: import_mode,
- destinations: [@group],
- imap_uid_validity: @status[:uid_validity],
- imap_uid: email['UID'],
- imap_group_id: @group.id,
- source: :imap
- )
+ receiver =
+ Email::Receiver.new(
+ email["RFC822"],
+ allow_auto_generated: true,
+ import_mode: import_mode,
+ destinations: [@group],
+ imap_uid_validity: @status[:uid_validity],
+ imap_uid: email["UID"],
+ imap_group_id: @group.id,
+ source: :imap,
+ )
receiver.process!
update_topic(email, receiver.incoming_email, mailbox_name: @group.imap_mailbox_name)
rescue Email::Receiver::ProcessingError => e
- ImapSyncLog.warn("Could not process (UIDVALIDITY = #{@status[:uid_validity]}, UID = #{email['UID']}): #{e.message}", @group)
+ ImapSyncLog.warn(
+ "Could not process (UIDVALIDITY = #{@status[:uid_validity]}, UID = #{email["UID"]}): #{e.message}",
+ @group,
+ )
end
processed += 1
@group.update_columns(
imap_uid_validity: @status[:uid_validity],
- imap_last_uid: email['UID'],
+ imap_last_uid: email["UID"],
imap_old_emails: all_old_uids_size + processed,
- imap_new_emails: all_new_uids_size - processed
+ imap_new_emails: all_new_uids_size - processed,
)
end
end
@@ -281,7 +331,10 @@ module Imap
if to_sync.size > 0
@provider.open_mailbox(@group.imap_mailbox_name, write: true)
to_sync.each do |incoming_email|
- ImapSyncLog.debug("Updating email on IMAP server for incoming email ID = #{incoming_email.id}, UID = #{incoming_email.imap_uid}", @group)
+ ImapSyncLog.debug(
+ "Updating email on IMAP server for incoming email ID = #{incoming_email.id}, UID = #{incoming_email.imap_uid}",
+ @group,
+ )
update_email(incoming_email)
incoming_email.update(imap_sync: false)
end
@@ -292,7 +345,7 @@ module Imap
topic = incoming_email.topic
topic_is_archived = topic.group_archived_messages.size > 0
- email_is_archived = !email['LABELS'].include?('\\Inbox') && !email['LABELS'].include?('INBOX')
+ email_is_archived = !email["LABELS"].include?('\\Inbox') && !email["LABELS"].include?("INBOX")
if topic_is_archived && !email_is_archived
ImapSyncLog.debug("Unarchiving topic ID #{topic.id}, email was unarchived", @group)
@@ -322,10 +375,10 @@ module Imap
tags.add(@provider.to_tag(opts[:mailbox_name])) if opts[:mailbox_name]
# Flags and labels
- email['FLAGS'].each { |flag| tags.add(@provider.to_tag(flag)) }
- email['LABELS'].each { |label| tags.add(@provider.to_tag(label)) }
+ email["FLAGS"].each { |flag| tags.add(@provider.to_tag(flag)) }
+ email["LABELS"].each { |label| tags.add(@provider.to_tag(label)) }
- tags.subtract([nil, ''])
+ tags.subtract([nil, ""])
return if !tagging_enabled?
@@ -354,11 +407,11 @@ module Imap
#
# A) the email has been deleted/moved to a different mailbox in the provider
# B) the UID does not belong to the provider
- email = @provider.emails(incoming_email.imap_uid, ['FLAGS', 'LABELS']).first
+ email = @provider.emails(incoming_email.imap_uid, %w[FLAGS LABELS]).first
return if !email.present?
- labels = email['LABELS']
- flags = email['FLAGS']
+ labels = email["LABELS"]
+ flags = email["FLAGS"]
new_labels = []
new_flags = []
@@ -367,7 +420,10 @@ module Imap
if !topic
# no need to do anything further here, we will recognize the UIDs in the
# mail server email thread have been trashed on next sync
- ImapSyncLog.debug("Trashing UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})", @group)
+ ImapSyncLog.debug(
+ "Trashing UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})",
+ @group,
+ )
return @provider.trash(incoming_email.imap_uid)
end
@@ -380,12 +436,18 @@ module Imap
# at the same time.
new_labels << "\\Inbox"
- ImapSyncLog.debug("Unarchiving UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})", @group)
+ ImapSyncLog.debug(
+ "Unarchiving UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})",
+ @group,
+ )
# some providers need special handling for unarchiving too
@provider.unarchive(incoming_email.imap_uid)
else
- ImapSyncLog.debug("Archiving UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})", @group)
+ ImapSyncLog.debug(
+ "Archiving UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})",
+ @group,
+ )
# some providers need special handling for archiving. this way we preserve
# any new tag-labels, and archive, even though it may cause extra requests
@@ -397,13 +459,14 @@ module Imap
if tagging_enabled?
tags = topic.tags.pluck(:name)
new_flags = tags.map { |tag| @provider.tag_to_flag(tag) }.reject(&:blank?)
- new_labels = new_labels.concat(tags.map { |tag| @provider.tag_to_label(tag) }.reject(&:blank?))
+ new_labels =
+ new_labels.concat(tags.map { |tag| @provider.tag_to_label(tag) }.reject(&:blank?))
end
# regardless of whether the topic needs to be archived we still update
# the flags and the labels
- @provider.store(incoming_email.imap_uid, 'FLAGS', flags, new_flags)
- @provider.store(incoming_email.imap_uid, 'LABELS', labels, new_labels)
+ @provider.store(incoming_email.imap_uid, "FLAGS", flags, new_flags)
+ @provider.store(incoming_email.imap_uid, "LABELS", labels, new_labels)
end
def tagging_enabled?
diff --git a/lib/import/normalize.rb b/lib/import/normalize.rb
index c9c6dc74998..8b9b98b8e06 100644
--- a/lib/import/normalize.rb
+++ b/lib/import/normalize.rb
@@ -3,13 +3,14 @@
# markdown normalizer to be used by importers
#
#
-require 'htmlentities'
-module Import; end
+require "htmlentities"
+module Import
+end
module Import::Normalize
def self.normalize_code_blocks(code, lang = nil)
coder = HTMLEntities.new
- code.gsub(/<pre>\s*<code>\n?(.*?)\n?<\/code>\s*<\/pre>/m) {
+ code.gsub(%r{<pre>\s*<code>\n?(.*?)\n?</code>\s*</pre>}m) do
"\n```#{lang}\n#{coder.decode($1)}\n```\n"
- }
+ end
end
end
diff --git a/lib/import_export.rb b/lib/import_export.rb
index 13d2b5eddf3..feb4d936015 100644
--- a/lib/import_export.rb
+++ b/lib/import_export.rb
@@ -10,9 +10,11 @@ require "import_export/translation_overrides_exporter"
require "json"
module ImportExport
-
def self.import(filename)
- data = ActiveSupport::HashWithIndifferentAccess.new(File.open(filename, "r:UTF-8") { |f| JSON.parse(f.read) })
+ data =
+ ActiveSupport::HashWithIndifferentAccess.new(
+ File.open(filename, "r:UTF-8") { |f| JSON.parse(f.read) },
+ )
ImportExport::Importer.new(data).perform
end
diff --git a/lib/import_export/base_exporter.rb b/lib/import_export/base_exporter.rb
index 989b7220e4d..2effbd2d9fe 100644
--- a/lib/import_export/base_exporter.rb
+++ b/lib/import_export/base_exporter.rb
@@ -4,22 +4,72 @@ module ImportExport
class BaseExporter
attr_reader :export_data, :categories
- CATEGORY_ATTRS = [:id, :name, :color, :created_at, :user_id, :slug, :description, :text_color,
- :auto_close_hours, :position, :parent_category_id, :auto_close_based_on_last_post,
- :topic_template, :all_topics_wiki, :permissions_params]
-
- GROUP_ATTRS = [:id, :name, :created_at, :automatic_membership_email_domains, :primary_group,
- :title, :grant_trust_level, :incoming_email, :bio_raw, :allow_membership_requests,
- :full_name, :default_notification_level, :visibility_level, :public_exit,
- :public_admission, :membership_request_template, :messageable_level, :mentionable_level,
- :members_visibility_level, :publish_read_state]
-
- USER_ATTRS = [:id, :email, :username, :name, :created_at, :trust_level, :active, :last_emailed_at, :custom_fields]
-
- TOPIC_ATTRS = [:id, :title, :created_at, :views, :category_id, :closed, :archived, :archetype]
-
- POST_ATTRS = [:id, :user_id, :post_number, :raw, :created_at, :reply_to_post_number, :hidden,
- :hidden_reason_id, :wiki]
+ CATEGORY_ATTRS = %i[
+ id
+ name
+ color
+ created_at
+ user_id
+ slug
+ description
+ text_color
+ auto_close_hours
+ position
+ parent_category_id
+ auto_close_based_on_last_post
+ topic_template
+ all_topics_wiki
+ permissions_params
+ ]
+
+ GROUP_ATTRS = %i[
+ id
+ name
+ created_at
+ automatic_membership_email_domains
+ primary_group
+ title
+ grant_trust_level
+ incoming_email
+ bio_raw
+ allow_membership_requests
+ full_name
+ default_notification_level
+ visibility_level
+ public_exit
+ public_admission
+ membership_request_template
+ messageable_level
+ mentionable_level
+ members_visibility_level
+ publish_read_state
+ ]
+
+ USER_ATTRS = %i[
+ id
+ email
+ username
+ name
+ created_at
+ trust_level
+ active
+ last_emailed_at
+ custom_fields
+ ]
+
+ TOPIC_ATTRS = %i[id title created_at views category_id closed archived archetype]
+
+ POST_ATTRS = %i[
+ id
+ user_id
+ post_number
+ raw
+ created_at
+ reply_to_post_number
+ hidden
+ hidden_reason_id
+ wiki
+ ]
def categories
@categories ||= Category.all.to_a
@@ -29,7 +79,10 @@ module ImportExport
data = []
categories.each do |cat|
- data << CATEGORY_ATTRS.inject({}) { |h, a| h[a] = cat.public_send(a); h }
+ data << CATEGORY_ATTRS.inject({}) do |h, a|
+ h[a] = cat.public_send(a)
+ h
+ end
end
data
@@ -47,7 +100,11 @@ module ImportExport
groups = groups.where(name: group_names) if group_names.present?
groups.find_each do |group|
- attrs = GROUP_ATTRS.inject({}) { |h, a| h[a] = group.public_send(a); h }
+ attrs =
+ GROUP_ATTRS.inject({}) do |h, a|
+ h[a] = group.public_send(a)
+ h
+ end
attrs[:user_ids] = group.users.pluck(:id)
data << attrs
end
@@ -87,9 +144,7 @@ module ImportExport
def export_group_users
user_ids = []
- @export_data[:groups].each do |g|
- user_ids += g[:user_ids]
- end
+ @export_data[:groups].each { |g| user_ids += g[:user_ids] }
user_ids.uniq!
return User.none if user_ids.empty?
@@ -110,22 +165,24 @@ module ImportExport
@topics.each do |topic|
puts topic.title
- topic_data = TOPIC_ATTRS.inject({}) do |h, a|
- h[a] = topic.public_send(a)
- h
- end
+ topic_data =
+ TOPIC_ATTRS.inject({}) do |h, a|
+ h[a] = topic.public_send(a)
+ h
+ end
topic_data[:posts] = []
topic.ordered_posts.find_each do |post|
- attributes = POST_ATTRS.inject({}) do |h, a|
- h[a] = post.public_send(a)
- h
- end
+ attributes =
+ POST_ATTRS.inject({}) do |h, a|
+ h[a] = post.public_send(a)
+ h
+ end
attributes[:raw] = attributes[:raw].gsub(
'src="/uploads',
- "src=\"#{Discourse.base_url_no_prefix}/uploads"
+ "src=\"#{Discourse.base_url_no_prefix}/uploads",
)
topic_data[:posts] << attributes
@@ -147,7 +204,7 @@ module ImportExport
return if @export_data[:topics].blank?
topic_ids = @export_data[:topics].pluck(:id)
- users = User.joins(:posts).where('posts.topic_id IN (?)', topic_ids).distinct
+ users = User.joins(:posts).where("posts.topic_id IN (?)", topic_ids).distinct
export_users(users)
end
@@ -164,14 +221,17 @@ module ImportExport
users.find_each do |u|
next if u.id == Discourse::SYSTEM_USER_ID
- x = USER_ATTRS.inject({}) do |h, a|
- h[a] = u.public_send(a)
- h
- end
+ x =
+ USER_ATTRS.inject({}) do |h, a|
+ h[a] = u.public_send(a)
+ h
+ end
- x.merge(bio_raw: u.user_profile.bio_raw,
- website: u.user_profile.website,
- location: u.user_profile.location)
+ x.merge(
+ bio_raw: u.user_profile.bio_raw,
+ website: u.user_profile.website,
+ location: u.user_profile.location,
+ )
data << x
end
@@ -179,7 +239,11 @@ module ImportExport
end
def export_translation_overrides
- @export_data[:translation_overrides] = TranslationOverride.all.select(:locale, :translation_key, :value)
+ @export_data[:translation_overrides] = TranslationOverride.all.select(
+ :locale,
+ :translation_key,
+ :value,
+ )
self
end
@@ -189,13 +253,12 @@ module ImportExport
end
def save_to_file(filename = nil)
- output_basename = filename || File.join("#{default_filename_prefix}-#{Time.now.strftime("%Y-%m-%d-%H%M%S")}.json")
- File.open(output_basename, "w:UTF-8") do |f|
- f.write(@export_data.to_json)
- end
+ output_basename =
+ filename ||
+ File.join("#{default_filename_prefix}-#{Time.now.strftime("%Y-%m-%d-%H%M%S")}.json")
+ File.open(output_basename, "w:UTF-8") { |f| f.write(@export_data.to_json) }
puts "Export saved to #{output_basename}"
output_basename
end
-
end
end
diff --git a/lib/import_export/category_exporter.rb b/lib/import_export/category_exporter.rb
index 85f857a6aa5..843c417d5e3 100644
--- a/lib/import_export/category_exporter.rb
+++ b/lib/import_export/category_exporter.rb
@@ -5,15 +5,10 @@ require "import_export/topic_exporter"
module ImportExport
class CategoryExporter < BaseExporter
-
def initialize(category_ids)
- @categories = Category.where(id: category_ids).or(Category.where(parent_category_id: category_ids)).to_a
- @export_data = {
- categories: [],
- groups: [],
- topics: [],
- users: []
- }
+ @categories =
+ Category.where(id: category_ids).or(Category.where(parent_category_id: category_ids)).to_a
+ @export_data = { categories: [], groups: [], topics: [], users: [] }
end
def perform
@@ -26,9 +21,12 @@ module ImportExport
def export_topics_and_users
all_category_ids = @categories.pluck(:id)
description_topic_ids = @categories.pluck(:topic_id)
- topic_exporter = ImportExport::TopicExporter.new(Topic.where(category_id: all_category_ids).pluck(:id) - description_topic_ids)
+ topic_exporter =
+ ImportExport::TopicExporter.new(
+ Topic.where(category_id: all_category_ids).pluck(:id) - description_topic_ids,
+ )
topic_exporter.perform
- @export_data[:users] = topic_exporter.export_data[:users]
+ @export_data[:users] = topic_exporter.export_data[:users]
@export_data[:topics] = topic_exporter.export_data[:topics]
self
end
@@ -36,6 +34,5 @@ module ImportExport
def default_filename_prefix
"category-export"
end
-
end
end
diff --git a/lib/import_export/category_structure_exporter.rb b/lib/import_export/category_structure_exporter.rb
index ce33de39d39..edaf89b3793 100644
--- a/lib/import_export/category_structure_exporter.rb
+++ b/lib/import_export/category_structure_exporter.rb
@@ -2,14 +2,10 @@
module ImportExport
class CategoryStructureExporter < BaseExporter
-
def initialize(include_group_users = false)
@include_group_users = include_group_users
- @export_data = {
- groups: [],
- categories: []
- }
+ @export_data = { groups: [], categories: [] }
@export_data[:users] = [] if @include_group_users
end
@@ -25,6 +21,5 @@ module ImportExport
def default_filename_prefix
"category-structure-export"
end
-
end
end
diff --git a/lib/import_export/group_exporter.rb b/lib/import_export/group_exporter.rb
index 893320cfbbb..a0ed870641d 100644
--- a/lib/import_export/group_exporter.rb
+++ b/lib/import_export/group_exporter.rb
@@ -2,13 +2,10 @@
module ImportExport
class GroupExporter < BaseExporter
-
def initialize(include_group_users = false)
@include_group_users = include_group_users
- @export_data = {
- groups: []
- }
+ @export_data = { groups: [] }
@export_data[:users] = [] if @include_group_users
end
@@ -23,6 +20,5 @@ module ImportExport
def default_filename_prefix
"groups-export"
end
-
end
end
diff --git a/lib/import_export/importer.rb b/lib/import_export/importer.rb
index c9d03030a15..1498831e46e 100644
--- a/lib/import_export/importer.rb
+++ b/lib/import_export/importer.rb
@@ -1,10 +1,9 @@
# frozen_string_literal: true
-require File.join(Rails.root, 'script', 'import_scripts', 'base.rb')
+require File.join(Rails.root, "script", "import_scripts", "base.rb")
module ImportExport
class Importer < ImportScripts::Base
-
def initialize(data)
@users = data[:users]
@groups = data[:groups]
@@ -66,7 +65,11 @@ module ImportExport
external_id = g.delete(:id)
new_group = Group.find_by_name(g[:name]) || Group.create!(g)
user_ids.each do |external_user_id|
- new_group.add(User.find(new_user_id(external_user_id))) rescue ActiveRecord::RecordNotUnique
+ begin
+ new_group.add(User.find(new_user_id(external_user_id)))
+ rescue StandardError
+ ActiveRecord::RecordNotUnique
+ end
end
end
@@ -79,7 +82,11 @@ module ImportExport
puts "Importing categories..."
import_ids = @categories.collect { |c| "#{c[:id]}#{import_source}" }
- existing_categories = CategoryCustomField.where("name = 'import_id' AND value IN (?)", import_ids).select(:category_id, :value).to_a
+ existing_categories =
+ CategoryCustomField
+ .where("name = 'import_id' AND value IN (?)", import_ids)
+ .select(:category_id, :value)
+ .to_a
existing_category_ids = existing_categories.pluck(:value)
levels = category_levels
@@ -100,7 +107,10 @@ module ImportExport
permissions = cat_attrs.delete(:permissions_params)
category = Category.new(cat_attrs)
- category.parent_category_id = new_category_id(cat_attrs[:parent_category_id]) if cat_attrs[:parent_category_id].present?
+ category.parent_category_id =
+ new_category_id(cat_attrs[:parent_category_id]) if cat_attrs[
+ :parent_category_id
+ ].present?
category.user_id = new_user_id(cat_attrs[:user_id])
import_id = "#{id}#{import_source}"
category.custom_fields["import_id"] = import_id
@@ -126,13 +136,14 @@ module ImportExport
def import_topics
return if @topics.blank?
- puts "Importing topics...", ''
+ puts "Importing topics...", ""
@topics.each do |t|
puts ""
print t[:title]
- first_post_attrs = t[:posts].first.merge(t.slice(*(TopicExporter::TOPIC_ATTRS - [:id, :category_id])))
+ first_post_attrs =
+ t[:posts].first.merge(t.slice(*(TopicExporter::TOPIC_ATTRS - %i[id category_id])))
first_post_attrs[:user_id] = new_user_id(first_post_attrs[:user_id])
first_post_attrs[:category] = new_category_id(t[:category_id])
@@ -140,9 +151,7 @@ module ImportExport
import_id = "#{first_post_attrs[:id]}#{import_source}"
first_post = PostCustomField.where(name: "import_id", value: import_id).first&.post
- unless first_post
- first_post = create_post(first_post_attrs, import_id)
- end
+ first_post = create_post(first_post_attrs, import_id) unless first_post
topic_id = first_post.topic_id
@@ -154,11 +163,8 @@ module ImportExport
unless existing
# see ImportScripts::Base
create_post(
- post_data.merge(
- topic_id: topic_id,
- user_id: new_user_id(post_data[:user_id])
- ),
- post_import_id
+ post_data.merge(topic_id: topic_id, user_id: new_user_id(post_data[:user_id])),
+ post_import_id,
)
end
end
@@ -182,51 +188,53 @@ module ImportExport
end
def new_user_id(external_user_id)
- ucf = UserCustomField.where(name: "import_id", value: "#{external_user_id}#{import_source}").first
+ ucf =
+ UserCustomField.where(name: "import_id", value: "#{external_user_id}#{import_source}").first
ucf ? ucf.user_id : Discourse::SYSTEM_USER_ID
end
def new_category_id(external_category_id)
- CategoryCustomField.where(
- name: "import_id",
- value: "#{external_category_id}#{import_source}"
- ).first&.category_id
+ CategoryCustomField
+ .where(name: "import_id", value: "#{external_category_id}#{import_source}")
+ .first
+ &.category_id
end
def import_source
- @_import_source ||= "#{ENV['IMPORT_SOURCE'] || ''}"
+ @_import_source ||= "#{ENV["IMPORT_SOURCE"] || ""}"
end
def category_levels
- @levels ||= begin
- levels = {}
-
- # Incomplete backups may lack definitions for some parent categories
- # which would cause an infinite loop below.
- parent_ids = @categories.map { |category| category[:parent_category_id] }.uniq
- category_ids = @categories.map { |category| category[:id] }.uniq
- (parent_ids - category_ids).each { |id| levels[id] = 0 }
-
- loop do
- changed = false
-
- @categories.each do |category|
- if !levels[category[:id]]
- if !category[:parent_category_id]
- levels[category[:id]] = 1
- elsif levels[category[:parent_category_id]]
- levels[category[:id]] = levels[category[:parent_category_id]] + 1
+ @levels ||=
+ begin
+ levels = {}
+
+ # Incomplete backups may lack definitions for some parent categories
+ # which would cause an infinite loop below.
+ parent_ids = @categories.map { |category| category[:parent_category_id] }.uniq
+ category_ids = @categories.map { |category| category[:id] }.uniq
+ (parent_ids - category_ids).each { |id| levels[id] = 0 }
+
+ loop do
+ changed = false
+
+ @categories.each do |category|
+ if !levels[category[:id]]
+ if !category[:parent_category_id]
+ levels[category[:id]] = 1
+ elsif levels[category[:parent_category_id]]
+ levels[category[:id]] = levels[category[:parent_category_id]] + 1
+ end
+
+ changed = true
end
-
- changed = true
end
+
+ break if !changed
end
- break if !changed
+ levels
end
-
- levels
- end
end
def fix_permissions
@@ -242,14 +250,19 @@ module ImportExport
max_level.times do
@categories.each do |category|
parent_category = categories_by_id[category[:parent_category_id]]
- next if !parent_category || !parent_category[:permissions_params] || parent_category[:permissions_params][:everyone]
+ if !parent_category || !parent_category[:permissions_params] ||
+ parent_category[:permissions_params][:everyone]
+ next
+ end
parent_groups = parent_category[:permissions_params].map(&:first)
child_groups = category[:permissions_params].map(&:first)
only_subcategory_groups = child_groups - parent_groups
if only_subcategory_groups.present?
- parent_category[:permissions_params].merge!(category[:permissions_params].slice(*only_subcategory_groups))
+ parent_category[:permissions_params].merge!(
+ category[:permissions_params].slice(*only_subcategory_groups),
+ )
end
end
end
diff --git a/lib/import_export/topic_exporter.rb b/lib/import_export/topic_exporter.rb
index 64ab80aaf0f..e7a4efd909c 100644
--- a/lib/import_export/topic_exporter.rb
+++ b/lib/import_export/topic_exporter.rb
@@ -4,13 +4,9 @@ require "import_export/base_exporter"
module ImportExport
class TopicExporter < ImportExport::BaseExporter
-
def initialize(topic_ids)
@topics = Topic.where(id: topic_ids).to_a
- @export_data = {
- topics: [],
- users: []
- }
+ @export_data = { topics: [], users: [] }
end
def perform
@@ -24,6 +20,5 @@ module ImportExport
def default_filename_prefix
"topic-export"
end
-
end
end
diff --git a/lib/import_export/translation_overrides_exporter.rb b/lib/import_export/translation_overrides_exporter.rb
index 7094248a99f..19feec10985 100644
--- a/lib/import_export/translation_overrides_exporter.rb
+++ b/lib/import_export/translation_overrides_exporter.rb
@@ -2,11 +2,8 @@
module ImportExport
class TranslationOverridesExporter < BaseExporter
-
def initialize()
- @export_data = {
- translation_overrides: []
- }
+ @export_data = { translation_overrides: [] }
end
def perform
@@ -19,6 +16,5 @@ module ImportExport
def default_filename_prefix
"translation-overrides"
end
-
end
end
diff --git a/lib/inline_oneboxer.rb b/lib/inline_oneboxer.rb
index 6383bbddff4..e3ef92ee849 100644
--- a/lib/inline_oneboxer.rb
+++ b/lib/inline_oneboxer.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class InlineOneboxer
-
MIN_TITLE_LENGTH = 2
def initialize(urls, opts = nil)
@@ -60,26 +59,25 @@ class InlineOneboxer
end
always_allow = SiteSetting.enable_inline_onebox_on_all_domains
- allowed_domains = SiteSetting.allowed_inline_onebox_domains&.split('|') unless always_allow
+ allowed_domains = SiteSetting.allowed_inline_onebox_domains&.split("|") unless always_allow
if always_allow || allowed_domains
- uri = begin
- URI(url)
- rescue URI::Error
- end
-
- if uri.present? &&
- uri.hostname.present? &&
- (always_allow || allowed_domains.include?(uri.hostname)) &&
- !Onebox::DomainChecker.is_blocked?(uri.hostname)
- if SiteSetting.block_onebox_on_redirect
- max_redirects = 0
+ uri =
+ begin
+ URI(url)
+ rescue URI::Error
end
- title = RetrieveTitle.crawl(
- url,
- max_redirects: max_redirects,
- initial_https_redirect_ignore_limit: SiteSetting.block_onebox_on_redirect
- )
+
+ if uri.present? && uri.hostname.present? &&
+ (always_allow || allowed_domains.include?(uri.hostname)) &&
+ !Onebox::DomainChecker.is_blocked?(uri.hostname)
+ max_redirects = 0 if SiteSetting.block_onebox_on_redirect
+ title =
+ RetrieveTitle.crawl(
+ url,
+ max_redirects: max_redirects,
+ initial_https_redirect_ignore_limit: SiteSetting.block_onebox_on_redirect,
+ )
title = nil if title && title.length < MIN_TITLE_LENGTH
return onebox_for(url, title, opts)
end
@@ -95,23 +93,20 @@ class InlineOneboxer
if title && opts[:post_number]
title += " - "
if opts[:post_author]
- title += I18n.t(
- "inline_oneboxer.topic_page_title_post_number_by_user",
- post_number: opts[:post_number],
- username: opts[:post_author]
- )
+ title +=
+ I18n.t(
+ "inline_oneboxer.topic_page_title_post_number_by_user",
+ post_number: opts[:post_number],
+ username: opts[:post_author],
+ )
else
- title += I18n.t(
- "inline_oneboxer.topic_page_title_post_number",
- post_number: opts[:post_number]
- )
+ title +=
+ I18n.t("inline_oneboxer.topic_page_title_post_number", post_number: opts[:post_number])
end
end
title = title && Emoji.gsub_emoji_to_unicode(title)
- if title.present?
- title = WordWatcher.censor_text(title)
- end
+ title = WordWatcher.censor_text(title) if title.present?
onebox = { url: url, title: title }
diff --git a/lib/js_locale_helper.rb b/lib/js_locale_helper.rb
index 009b75698f4..2b8db855754 100644
--- a/lib/js_locale_helper.rb
+++ b/lib/js_locale_helper.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module JsLocaleHelper
-
def self.plugin_client_files(locale_str)
files = Dir["#{Rails.root}/plugins/*/config/locales/client*.#{locale_str}.yml"]
I18n::Backend::DiscourseI18n.sort_locale_files(files)
@@ -10,9 +9,7 @@ module JsLocaleHelper
def self.reloadable_plugins(locale_sym, ctx)
return unless Rails.env.development?
I18n.fallbacks[locale_sym].each do |locale|
- plugin_client_files(locale.to_s).each do |file|
- ctx.depend_on(file)
- end
+ plugin_client_files(locale.to_s).each { |file| ctx.depend_on(file) }
end
end
@@ -44,24 +41,28 @@ module JsLocaleHelper
else
# If we can't find a base file in Discourse, it might only exist in a plugin
# so let's start with a basic object we can merge into
- translations = {
- locale_str => {
- 'js' => {},
- 'admin_js' => {},
- 'wizard_js' => {}
- }
- }
+ translations = { locale_str => { "js" => {}, "admin_js" => {}, "wizard_js" => {} } }
end
# merge translations (plugin translations overwrite default translations)
if translations[locale_str] && plugin_translations(locale_str)
- translations[locale_str]['js'] ||= {}
- translations[locale_str]['admin_js'] ||= {}
- translations[locale_str]['wizard_js'] ||= {}
+ translations[locale_str]["js"] ||= {}
+ translations[locale_str]["admin_js"] ||= {}
+ translations[locale_str]["wizard_js"] ||= {}
- translations[locale_str]['js'].deep_merge!(plugin_translations(locale_str)['js']) if plugin_translations(locale_str)['js']
- translations[locale_str]['admin_js'].deep_merge!(plugin_translations(locale_str)['admin_js']) if plugin_translations(locale_str)['admin_js']
- translations[locale_str]['wizard_js'].deep_merge!(plugin_translations(locale_str)['wizard_js']) if plugin_translations(locale_str)['wizard_js']
+ if plugin_translations(locale_str)["js"]
+ translations[locale_str]["js"].deep_merge!(plugin_translations(locale_str)["js"])
+ end
+ if plugin_translations(locale_str)["admin_js"]
+ translations[locale_str]["admin_js"].deep_merge!(
+ plugin_translations(locale_str)["admin_js"],
+ )
+ end
+ if plugin_translations(locale_str)["wizard_js"]
+ translations[locale_str]["wizard_js"].deep_merge!(
+ plugin_translations(locale_str)["wizard_js"],
+ )
+ end
end
translations
@@ -82,9 +83,7 @@ module JsLocaleHelper
new_hash[key] = new_at_key
end
else
- if checking_hashes.any? { |h| h.include?(key) }
- new_hash.delete(key)
- end
+ new_hash.delete(key) if checking_hashes.any? { |h| h.include?(key) }
end
end
new_hash
@@ -93,16 +92,21 @@ module JsLocaleHelper
def self.load_translations_merged(*locales)
locales = locales.uniq.compact
@loaded_merges ||= {}
- @loaded_merges[locales.join('-')] ||= begin
+ @loaded_merges[locales.join("-")] ||= begin
all_translations = {}
merged_translations = {}
loaded_locales = []
- locales.map(&:to_s).each do |locale|
- all_translations[locale] = load_translations(locale)
- merged_translations[locale] = deep_delete_matches(all_translations[locale][locale], loaded_locales.map { |l| merged_translations[l] })
- loaded_locales << locale
- end
+ locales
+ .map(&:to_s)
+ .each do |locale|
+ all_translations[locale] = load_translations(locale)
+ merged_translations[locale] = deep_delete_matches(
+ all_translations[locale][locale],
+ loaded_locales.map { |l| merged_translations[l] },
+ )
+ loaded_locales << locale
+ end
merged_translations
end
end
@@ -118,13 +122,14 @@ module JsLocaleHelper
locale_sym = locale_str.to_sym
- translations = I18n.with_locale(locale_sym) do
- if locale_sym == :en
- load_translations(locale_sym)
- else
- load_translations_merged(*I18n.fallbacks[locale_sym])
+ translations =
+ I18n.with_locale(locale_sym) do
+ if locale_sym == :en
+ load_translations(locale_sym)
+ else
+ load_translations_merged(*I18n.fallbacks[locale_sym])
+ end
end
- end
Marshal.load(Marshal.dump(translations))
end
@@ -139,16 +144,18 @@ module JsLocaleHelper
result = generate_message_format(message_formats, mf_locale, mf_filename)
translations.keys.each do |l|
- translations[l].keys.each do |k|
- translations[l].delete(k) unless k == "js"
- end
+ translations[l].keys.each { |k| translations[l].delete(k) unless k == "js" }
end
# I18n
result << "I18n.translations = #{translations.to_json};\n"
result << "I18n.locale = '#{locale_str}';\n"
- result << "I18n.fallbackLocale = '#{fallback_locale_str}';\n" if fallback_locale_str && fallback_locale_str != "en"
- result << "I18n.pluralizationRules.#{locale_str} = MessageFormat.locale.#{mf_locale};\n" if mf_locale != "en"
+ if fallback_locale_str && fallback_locale_str != "en"
+ result << "I18n.fallbackLocale = '#{fallback_locale_str}';\n"
+ end
+ if mf_locale != "en"
+ result << "I18n.pluralizationRules.#{locale_str} = MessageFormat.locale.#{mf_locale};\n"
+ end
# moment
result << File.read("#{Rails.root}/vendor/assets/javascripts/moment.js")
@@ -165,10 +172,11 @@ module JsLocaleHelper
has_overrides = false
I18n.fallbacks[main_locale].each do |locale|
- overrides = all_overrides[locale] = TranslationOverride
- .where(locale: locale)
- .where("translation_key LIKE 'js.%' OR translation_key LIKE 'admin_js.%'")
- .pluck(:translation_key, :value, :compiled_js)
+ overrides =
+ all_overrides[locale] = TranslationOverride
+ .where(locale: locale)
+ .where("translation_key LIKE 'js.%' OR translation_key LIKE 'admin_js.%'")
+ .pluck(:translation_key, :value, :compiled_js)
has_overrides ||= overrides.present?
end
@@ -214,19 +222,15 @@ module JsLocaleHelper
return "" if translations.blank?
output = +"if (!I18n.extras) { I18n.extras = {}; }"
- locales.each do |l|
- output << <<~JS
+ locales.each { |l| output << <<~JS }
if (!I18n.extras["#{l}"]) { I18n.extras["#{l}"] = {}; }
Object.assign(I18n.extras["#{l}"], #{translations[l].to_json});
JS
- end
output
end
- MOMENT_LOCALE_MAPPING ||= {
- "hy" => "hy-am"
- }
+ MOMENT_LOCALE_MAPPING ||= { "hy" => "hy-am" }
def self.find_moment_locale(locale_chain, timezone_names: false)
if timezone_names
@@ -240,7 +244,7 @@ module JsLocaleHelper
find_locale(locale_chain, path, type, fallback_to_english: false) do |locale|
locale = MOMENT_LOCALE_MAPPING[locale] if MOMENT_LOCALE_MAPPING.key?(locale)
# moment.js uses a different naming scheme for locale files
- locale.tr('_', '-').downcase
+ locale.tr("_", "-").downcase
end
end
@@ -258,14 +262,14 @@ module JsLocaleHelper
locale = yield(locale) if block_given?
filename = File.join(path, "#{locale}.js")
- return [locale, filename] if File.exist?(filename)
+ return locale, filename if File.exist?(filename)
end
locale_chain.map! { |locale| yield(locale) } if block_given?
# try again, but this time only with the language itself
- locale_chain = locale_chain.map { |l| l.split(/[-_]/)[0] }
- .uniq.reject { |l| locale_chain.include?(l) }
+ locale_chain =
+ locale_chain.map { |l| l.split(/[-_]/)[0] }.uniq.reject { |l| locale_chain.include?(l) }
if locale_chain.any?
locale_data = find_locale(locale_chain, path, type, fallback_to_english: false)
@@ -278,9 +282,9 @@ module JsLocaleHelper
def self.moment_formats
result = +""
- result << moment_format_function('short_date_no_year')
- result << moment_format_function('short_date')
- result << moment_format_function('long_date')
+ result << moment_format_function("short_date_no_year")
+ result << moment_format_function("short_date")
+ result << moment_format_function("long_date")
result << "moment.fn.relativeAge = function(opts){ return Discourse.Formatter.relativeAge(this.toDate(), opts)};\n"
end
@@ -295,7 +299,10 @@ module JsLocaleHelper
end
def self.generate_message_format(message_formats, locale, filename)
- formats = message_formats.map { |k, v| k.inspect << " : " << compile_message_format(filename, locale, v) }.join(", ")
+ formats =
+ message_formats
+ .map { |k, v| k.inspect << " : " << compile_message_format(filename, locale, v) }
+ .join(", ")
result = +"MessageFormat = {locale: {}};\n"
result << "I18n._compiledMFs = {#{formats}};\n"
@@ -318,11 +325,14 @@ module JsLocaleHelper
@mutex = Mutex.new
def self.with_context
@mutex.synchronize do
- yield @ctx ||= begin
- ctx = MiniRacer::Context.new(timeout: 15000, ensure_gc_after_idle: 2000)
- ctx.load("#{Rails.root}/lib/javascripts/messageformat.js")
- ctx
- end
+ yield(
+ @ctx ||=
+ begin
+ ctx = MiniRacer::Context.new(timeout: 15_000, ensure_gc_after_idle: 2000)
+ ctx.load("#{Rails.root}/lib/javascripts/messageformat.js")
+ ctx
+ end
+ )
end
end
@@ -339,13 +349,15 @@ module JsLocaleHelper
def self.remove_message_formats!(translations, locale)
message_formats = {}
- I18n.fallbacks[locale].map(&:to_s).each do |l|
- next unless translations.key?(l)
+ I18n.fallbacks[locale]
+ .map(&:to_s)
+ .each do |l|
+ next unless translations.key?(l)
- %w{js admin_js}.each do |k|
- message_formats.merge!(strip_out_message_formats!(translations[l][k]))
+ %w[js admin_js].each do |k|
+ message_formats.merge!(strip_out_message_formats!(translations[l][k]))
+ end
end
- end
message_formats
end
@@ -353,7 +365,9 @@ module JsLocaleHelper
if hash.is_a?(Hash)
hash.each do |key, value|
if value.is_a?(Hash)
- message_formats.merge!(strip_out_message_formats!(value, join_key(prefix, key), message_formats))
+ message_formats.merge!(
+ strip_out_message_formats!(value, join_key(prefix, key), message_formats),
+ )
elsif key.to_s.end_with?("_MF")
message_formats[join_key(prefix, key)] = value
hash.delete(key)
diff --git a/lib/json_error.rb b/lib/json_error.rb
index ac6ff76edc5..d8867684a06 100644
--- a/lib/json_error.rb
+++ b/lib/json_error.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module JsonError
-
def create_errors_json(obj, opts = nil)
opts ||= {}
@@ -32,7 +31,7 @@ module JsonError
return { errors: [message] } if message.present?
end
- return { errors: [I18n.t('not_found')] } if obj.is_a?(HasErrors) && obj.not_found
+ return { errors: [I18n.t("not_found")] } if obj.is_a?(HasErrors) && obj.not_found
# Log a warning (unless obj is nil)
Rails.logger.warn("create_errors_json called with unrecognized type: #{obj.inspect}") if obj
@@ -42,7 +41,6 @@ module JsonError
end
def self.generic_error
- { errors: [I18n.t('js.generic_error')] }
+ { errors: [I18n.t("js.generic_error")] }
end
-
end
diff --git a/lib/letter_avatar.rb b/lib/letter_avatar.rb
index 1a8524f338a..88cea034a0a 100644
--- a/lib/letter_avatar.rb
+++ b/lib/letter_avatar.rb
@@ -1,15 +1,15 @@
# frozen_string_literal: true
class LetterAvatar
-
class Identity
attr_accessor :color, :letter
def self.from_username(username)
identity = new
- identity.color = LetterAvatar::COLORS[
- Digest::MD5.hexdigest(username)[0...15].to_i(16) % LetterAvatar::COLORS.length
- ]
+ identity.color =
+ LetterAvatar::COLORS[
+ Digest::MD5.hexdigest(username)[0...15].to_i(16) % LetterAvatar::COLORS.length
+ ]
identity.letter = username[0].upcase
identity
end
@@ -19,11 +19,10 @@ class LetterAvatar
VERSION = 5
# CHANGE these values to support more pixel ratios
- FULLSIZE = 120 * 3
+ FULLSIZE = 120 * 3
POINTSIZE = 280
class << self
-
def version
"#{VERSION}_#{image_magick_version}"
end
@@ -72,19 +71,27 @@ class LetterAvatar
filename = fullsize_path(identity)
- instructions = %W{
- -size #{FULLSIZE}x#{FULLSIZE}
+ instructions = %W[
+ -size
+ #{FULLSIZE}x#{FULLSIZE}
xc:#{to_rgb(color)}
- -pointsize #{POINTSIZE}
- -fill #FFFFFFCC
- -font Helvetica
- -gravity Center
- -annotate -0+26 #{letter}
- -depth 8
+ -pointsize
+ #{POINTSIZE}
+ -fill
+ #FFFFFFCC
+ -font
+ Helvetica
+ -gravity
+ Center
+ -annotate
+ -0+26
+ #{letter}
+ -depth
+ 8
#{filename}
- }
+ ]
- Discourse::Utils.execute_command('convert', *instructions)
+ Discourse::Utils.execute_command("convert", *instructions)
## do not optimize image, it will end up larger than original
filename
@@ -110,11 +117,11 @@ class LetterAvatar
begin
skip = File.basename(cache_path)
parent_path = File.dirname(cache_path)
- Dir.entries(parent_path).each do |path|
- unless ['.', '..'].include?(path) || path == skip
- FileUtils.rm_rf(parent_path + "/" + path)
+ Dir
+ .entries(parent_path)
+ .each do |path|
+ FileUtils.rm_rf(parent_path + "/" + path) unless %w[. ..].include?(path) || path == skip
end
- end
rescue Errno::ENOENT
# no worries, folder doesn't exists
end
@@ -127,220 +134,222 @@ class LetterAvatar
# - H: 0 - 360
# - C: 0 - 2
# - L: 0.75 - 1.5
- COLORS = [[198, 125, 40],
- [61, 155, 243],
- [74, 243, 75],
- [238, 89, 166],
- [52, 240, 224],
- [177, 156, 155],
- [240, 120, 145],
- [111, 154, 78],
- [237, 179, 245],
- [237, 101, 95],
- [89, 239, 155],
- [43, 254, 70],
- [163, 212, 245],
- [65, 152, 142],
- [165, 135, 246],
- [181, 166, 38],
- [187, 229, 206],
- [77, 164, 25],
- [179, 246, 101],
- [234, 93, 37],
- [225, 155, 115],
- [142, 140, 188],
- [223, 120, 140],
- [249, 174, 27],
- [244, 117, 225],
- [137, 141, 102],
- [75, 191, 146],
- [188, 239, 142],
- [164, 199, 145],
- [173, 120, 149],
- [59, 195, 89],
- [222, 198, 220],
- [68, 145, 187],
- [236, 204, 179],
- [159, 195, 72],
- [188, 121, 189],
- [166, 160, 85],
- [181, 233, 37],
- [236, 177, 85],
- [121, 147, 160],
- [234, 218, 110],
- [241, 157, 191],
- [62, 200, 234],
- [133, 243, 34],
- [88, 149, 110],
- [59, 228, 248],
- [183, 119, 118],
- [251, 195, 45],
- [113, 196, 122],
- [197, 115, 70],
- [80, 175, 187],
- [103, 231, 238],
- [240, 72, 133],
- [228, 149, 241],
- [180, 188, 159],
- [172, 132, 85],
- [180, 135, 251],
- [236, 194, 58],
- [217, 176, 109],
- [88, 244, 199],
- [186, 157, 239],
- [113, 230, 96],
- [206, 115, 165],
- [244, 178, 163],
- [230, 139, 26],
- [241, 125, 89],
- [83, 160, 66],
- [107, 190, 166],
- [197, 161, 210],
- [198, 203, 245],
- [238, 117, 19],
- [228, 119, 116],
- [131, 156, 41],
- [145, 178, 168],
- [139, 170, 220],
- [233, 95, 125],
- [87, 178, 230],
- [157, 200, 119],
- [237, 140, 76],
- [229, 185, 186],
- [144, 206, 212],
- [236, 209, 158],
- [185, 189, 79],
- [34, 208, 66],
- [84, 238, 129],
- [133, 140, 134],
- [67, 157, 94],
- [168, 179, 25],
- [140, 145, 240],
- [151, 241, 125],
- [67, 162, 107],
- [200, 156, 21],
- [169, 173, 189],
- [226, 116, 189],
- [133, 231, 191],
- [194, 161, 63],
- [241, 77, 99],
- [241, 217, 53],
- [123, 204, 105],
- [210, 201, 119],
- [229, 108, 155],
- [240, 91, 72],
- [187, 115, 210],
- [240, 163, 100],
- [178, 217, 57],
- [179, 135, 116],
- [204, 211, 24],
- [186, 135, 57],
- [223, 176, 135],
- [204, 148, 151],
- [116, 223, 50],
- [95, 195, 46],
- [123, 160, 236],
- [181, 172, 131],
- [142, 220, 202],
- [240, 140, 112],
- [172, 145, 164],
- [228, 124, 45],
- [135, 151, 243],
- [42, 205, 125],
- [192, 233, 116],
- [119, 170, 114],
- [158, 138, 26],
- [73, 190, 183],
- [185, 229, 243],
- [227, 107, 55],
- [196, 205, 202],
- [132, 143, 60],
- [233, 192, 237],
- [62, 150, 220],
- [205, 201, 141],
- [106, 140, 190],
- [161, 131, 205],
- [135, 134, 158],
- [198, 139, 81],
- [115, 171, 32],
- [101, 181, 67],
- [149, 137, 119],
- [37, 142, 183],
- [183, 130, 175],
- [168, 125, 133],
- [124, 142, 87],
- [236, 156, 171],
- [232, 194, 91],
- [219, 200, 69],
- [144, 219, 34],
- [219, 95, 187],
- [145, 154, 217],
- [165, 185, 100],
- [127, 238, 163],
- [224, 178, 198],
- [119, 153, 120],
- [124, 212, 92],
- [172, 161, 105],
- [231, 155, 135],
- [157, 132, 101],
- [122, 185, 146],
- [53, 166, 51],
- [70, 163, 90],
- [150, 190, 213],
- [210, 107, 60],
- [166, 152, 185],
- [159, 194, 159],
- [39, 141, 222],
- [202, 176, 161],
- [95, 140, 229],
- [168, 142, 87],
- [93, 170, 203],
- [159, 142, 54],
- [14, 168, 39],
- [94, 150, 149],
- [187, 206, 136],
- [157, 224, 166],
- [235, 158, 208],
- [109, 232, 216],
- [141, 201, 87],
- [208, 124, 118],
- [142, 125, 214],
- [19, 237, 174],
- [72, 219, 41],
- [234, 102, 111],
- [168, 142, 79],
- [188, 135, 35],
- [95, 155, 143],
- [148, 173, 116],
- [223, 112, 95],
- [228, 128, 236],
- [206, 114, 54],
- [195, 119, 88],
- [235, 140, 94],
- [235, 202, 125],
- [233, 155, 153],
- [214, 214, 238],
- [246, 200, 35],
- [151, 125, 171],
- [132, 145, 172],
- [131, 142, 118],
- [199, 126, 150],
- [61, 162, 123],
- [58, 176, 151],
- [215, 141, 69],
- [225, 154, 220],
- [220, 77, 167],
- [233, 161, 64],
- [130, 221, 137],
- [81, 191, 129],
- [169, 162, 140],
- [174, 177, 222],
- [236, 174, 47],
- [233, 188, 180],
- [69, 222, 172],
- [71, 232, 93],
- [118, 211, 238],
- [157, 224, 83],
- [218, 105, 73],
- [126, 169, 36]]
+ COLORS = [
+ [198, 125, 40],
+ [61, 155, 243],
+ [74, 243, 75],
+ [238, 89, 166],
+ [52, 240, 224],
+ [177, 156, 155],
+ [240, 120, 145],
+ [111, 154, 78],
+ [237, 179, 245],
+ [237, 101, 95],
+ [89, 239, 155],
+ [43, 254, 70],
+ [163, 212, 245],
+ [65, 152, 142],
+ [165, 135, 246],
+ [181, 166, 38],
+ [187, 229, 206],
+ [77, 164, 25],
+ [179, 246, 101],
+ [234, 93, 37],
+ [225, 155, 115],
+ [142, 140, 188],
+ [223, 120, 140],
+ [249, 174, 27],
+ [244, 117, 225],
+ [137, 141, 102],
+ [75, 191, 146],
+ [188, 239, 142],
+ [164, 199, 145],
+ [173, 120, 149],
+ [59, 195, 89],
+ [222, 198, 220],
+ [68, 145, 187],
+ [236, 204, 179],
+ [159, 195, 72],
+ [188, 121, 189],
+ [166, 160, 85],
+ [181, 233, 37],
+ [236, 177, 85],
+ [121, 147, 160],
+ [234, 218, 110],
+ [241, 157, 191],
+ [62, 200, 234],
+ [133, 243, 34],
+ [88, 149, 110],
+ [59, 228, 248],
+ [183, 119, 118],
+ [251, 195, 45],
+ [113, 196, 122],
+ [197, 115, 70],
+ [80, 175, 187],
+ [103, 231, 238],
+ [240, 72, 133],
+ [228, 149, 241],
+ [180, 188, 159],
+ [172, 132, 85],
+ [180, 135, 251],
+ [236, 194, 58],
+ [217, 176, 109],
+ [88, 244, 199],
+ [186, 157, 239],
+ [113, 230, 96],
+ [206, 115, 165],
+ [244, 178, 163],
+ [230, 139, 26],
+ [241, 125, 89],
+ [83, 160, 66],
+ [107, 190, 166],
+ [197, 161, 210],
+ [198, 203, 245],
+ [238, 117, 19],
+ [228, 119, 116],
+ [131, 156, 41],
+ [145, 178, 168],
+ [139, 170, 220],
+ [233, 95, 125],
+ [87, 178, 230],
+ [157, 200, 119],
+ [237, 140, 76],
+ [229, 185, 186],
+ [144, 206, 212],
+ [236, 209, 158],
+ [185, 189, 79],
+ [34, 208, 66],
+ [84, 238, 129],
+ [133, 140, 134],
+ [67, 157, 94],
+ [168, 179, 25],
+ [140, 145, 240],
+ [151, 241, 125],
+ [67, 162, 107],
+ [200, 156, 21],
+ [169, 173, 189],
+ [226, 116, 189],
+ [133, 231, 191],
+ [194, 161, 63],
+ [241, 77, 99],
+ [241, 217, 53],
+ [123, 204, 105],
+ [210, 201, 119],
+ [229, 108, 155],
+ [240, 91, 72],
+ [187, 115, 210],
+ [240, 163, 100],
+ [178, 217, 57],
+ [179, 135, 116],
+ [204, 211, 24],
+ [186, 135, 57],
+ [223, 176, 135],
+ [204, 148, 151],
+ [116, 223, 50],
+ [95, 195, 46],
+ [123, 160, 236],
+ [181, 172, 131],
+ [142, 220, 202],
+ [240, 140, 112],
+ [172, 145, 164],
+ [228, 124, 45],
+ [135, 151, 243],
+ [42, 205, 125],
+ [192, 233, 116],
+ [119, 170, 114],
+ [158, 138, 26],
+ [73, 190, 183],
+ [185, 229, 243],
+ [227, 107, 55],
+ [196, 205, 202],
+ [132, 143, 60],
+ [233, 192, 237],
+ [62, 150, 220],
+ [205, 201, 141],
+ [106, 140, 190],
+ [161, 131, 205],
+ [135, 134, 158],
+ [198, 139, 81],
+ [115, 171, 32],
+ [101, 181, 67],
+ [149, 137, 119],
+ [37, 142, 183],
+ [183, 130, 175],
+ [168, 125, 133],
+ [124, 142, 87],
+ [236, 156, 171],
+ [232, 194, 91],
+ [219, 200, 69],
+ [144, 219, 34],
+ [219, 95, 187],
+ [145, 154, 217],
+ [165, 185, 100],
+ [127, 238, 163],
+ [224, 178, 198],
+ [119, 153, 120],
+ [124, 212, 92],
+ [172, 161, 105],
+ [231, 155, 135],
+ [157, 132, 101],
+ [122, 185, 146],
+ [53, 166, 51],
+ [70, 163, 90],
+ [150, 190, 213],
+ [210, 107, 60],
+ [166, 152, 185],
+ [159, 194, 159],
+ [39, 141, 222],
+ [202, 176, 161],
+ [95, 140, 229],
+ [168, 142, 87],
+ [93, 170, 203],
+ [159, 142, 54],
+ [14, 168, 39],
+ [94, 150, 149],
+ [187, 206, 136],
+ [157, 224, 166],
+ [235, 158, 208],
+ [109, 232, 216],
+ [141, 201, 87],
+ [208, 124, 118],
+ [142, 125, 214],
+ [19, 237, 174],
+ [72, 219, 41],
+ [234, 102, 111],
+ [168, 142, 79],
+ [188, 135, 35],
+ [95, 155, 143],
+ [148, 173, 116],
+ [223, 112, 95],
+ [228, 128, 236],
+ [206, 114, 54],
+ [195, 119, 88],
+ [235, 140, 94],
+ [235, 202, 125],
+ [233, 155, 153],
+ [214, 214, 238],
+ [246, 200, 35],
+ [151, 125, 171],
+ [132, 145, 172],
+ [131, 142, 118],
+ [199, 126, 150],
+ [61, 162, 123],
+ [58, 176, 151],
+ [215, 141, 69],
+ [225, 154, 220],
+ [220, 77, 167],
+ [233, 161, 64],
+ [130, 221, 137],
+ [81, 191, 129],
+ [169, 162, 140],
+ [174, 177, 222],
+ [236, 174, 47],
+ [233, 188, 180],
+ [69, 222, 172],
+ [71, 232, 93],
+ [118, 211, 238],
+ [157, 224, 83],
+ [218, 105, 73],
+ [126, 169, 36],
+ ]
end
diff --git a/lib/markdown_linker.rb b/lib/markdown_linker.rb
index fe48d4f5f2b..bc5bbdd0126 100644
--- a/lib/markdown_linker.rb
+++ b/lib/markdown_linker.rb
@@ -2,7 +2,6 @@
# Helps create links using markdown (where references are at the bottom)
class MarkdownLinker
-
def initialize(base_url)
@base_url = base_url
@index = 1
@@ -19,11 +18,8 @@ class MarkdownLinker
def references
result = +""
- (@rendered..@index - 1).each do |i|
- result << "[#{i}]: #{@markdown_links[i]}\n"
- end
+ (@rendered..@index - 1).each { |i| result << "[#{i}]: #{@markdown_links[i]}\n" }
@rendered = @index
result
end
-
end
diff --git a/lib/mem_info.rb b/lib/mem_info.rb
index 6404fa8733d..c8ea0d0d6c3 100644
--- a/lib/mem_info.rb
+++ b/lib/mem_info.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class MemInfo
-
# Total memory in kb. On Mac OS uses "sysctl", elsewhere expects the system has /proc/meminfo.
# Returns nil if it cannot be determined.
def mem_total
@@ -15,9 +14,8 @@ class MemInfo
s = `grep MemTotal /proc/meminfo`
/(\d+)/.match(s)[0].try(:to_i)
end
- rescue
+ rescue StandardError
nil
end
end
-
end
diff --git a/lib/message_bus_diags.rb b/lib/message_bus_diags.rb
index 16bde3a9a14..b2de1ad80ef 100644
--- a/lib/message_bus_diags.rb
+++ b/lib/message_bus_diags.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class MessageBusDiags
-
@host_info = {}
def self.my_id
@@ -21,7 +20,6 @@ class MessageBusDiags
end
unless @subscribed
-
MessageBus.subscribe "/server-name-reply/#{my_id}" do |msg|
MessageBusDiags.seen_host(msg.data)
end
diff --git a/lib/method_profiler.rb b/lib/method_profiler.rb
index fd6588c6bc7..aa0836278dc 100644
--- a/lib/method_profiler.rb
+++ b/lib/method_profiler.rb
@@ -3,17 +3,16 @@
# see https://samsaffron.com/archive/2017/10/18/fastest-way-to-profile-a-method-in-ruby
class MethodProfiler
def self.patch(klass, methods, name, no_recurse: false)
- patches = methods.map do |method_name|
-
- recurse_protection = ""
- if no_recurse
- recurse_protection = <<~RUBY
+ patches =
+ methods
+ .map do |method_name|
+ recurse_protection = ""
+ recurse_protection = <<~RUBY if no_recurse
return #{method_name}__mp_unpatched(*args, &blk) if @mp_recurse_protect_#{method_name}
@mp_recurse_protect_#{method_name} = true
RUBY
- end
- <<~RUBY
+ <<~RUBY
unless defined?(#{method_name}__mp_unpatched)
alias_method :#{method_name}__mp_unpatched, :#{method_name}
def #{method_name}(*args, &blk)
@@ -33,23 +32,23 @@ class MethodProfiler
end
end
RUBY
- end.join("\n")
+ end
+ .join("\n")
klass.class_eval patches
end
def self.patch_with_debug_sql(klass, methods, name, no_recurse: false)
- patches = methods.map do |method_name|
-
- recurse_protection = ""
- if no_recurse
- recurse_protection = <<~RUBY
+ patches =
+ methods
+ .map do |method_name|
+ recurse_protection = ""
+ recurse_protection = <<~RUBY if no_recurse
return #{method_name}__mp_unpatched_debug_sql(*args, &blk) if @mp_recurse_protect_#{method_name}
@mp_recurse_protect_#{method_name} = true
RUBY
- end
- <<~RUBY
+ <<~RUBY
unless defined?(#{method_name}__mp_unpatched_debug_sql)
alias_method :#{method_name}__mp_unpatched_debug_sql, :#{method_name}
def #{method_name}(*args, &blk)
@@ -77,7 +76,8 @@ class MethodProfiler
end
end
RUBY
- end.join("\n")
+ end
+ .join("\n")
klass.class_eval patches
end
@@ -89,9 +89,8 @@ class MethodProfiler
end
def self.start(transfer = nil)
- Thread.current[:_method_profiler] = transfer || {
- __start: Process.clock_gettime(Process::CLOCK_MONOTONIC)
- }
+ Thread.current[:_method_profiler] = transfer ||
+ { __start: Process.clock_gettime(Process::CLOCK_MONOTONIC) }
end
def self.clear
@@ -116,35 +115,36 @@ class MethodProfiler
# filter_transactions - When true, we do not record timings of transaction
# related commits (BEGIN, COMMIT, ROLLBACK)
def self.output_sql_to_stderr!(filter_transactions: false)
- Rails.logger.warn("Stop! This instrumentation is not intended for use in production outside of debugging scenarios. Please be sure you know what you are doing when enabling this instrumentation.")
+ Rails.logger.warn(
+ "Stop! This instrumentation is not intended for use in production outside of debugging scenarios. Please be sure you know what you are doing when enabling this instrumentation.",
+ )
@@instrumentation_debug_sql_filter_transactions = filter_transactions
- @@instrumentation_setup_debug_sql ||= begin
- MethodProfiler.patch_with_debug_sql(PG::Connection, [
- :exec, :async_exec, :exec_prepared, :send_query_prepared, :query, :exec_params
- ], :sql)
- true
- end
+ @@instrumentation_setup_debug_sql ||=
+ begin
+ MethodProfiler.patch_with_debug_sql(
+ PG::Connection,
+ %i[exec async_exec exec_prepared send_query_prepared query exec_params],
+ :sql,
+ )
+ true
+ end
end
def self.ensure_discourse_instrumentation!
- @@instrumentation_setup ||= begin
- MethodProfiler.patch(PG::Connection, [
- :exec, :async_exec, :exec_prepared, :send_query_prepared, :query, :exec_params
- ], :sql)
-
- MethodProfiler.patch(Redis::Client, [
- :call, :call_pipeline
- ], :redis)
-
- MethodProfiler.patch(Net::HTTP, [
- :request
- ], :net, no_recurse: true)
-
- MethodProfiler.patch(Excon::Connection, [
- :request
- ], :net)
- true
- end
- end
+ @@instrumentation_setup ||=
+ begin
+ MethodProfiler.patch(
+ PG::Connection,
+ %i[exec async_exec exec_prepared send_query_prepared query exec_params],
+ :sql,
+ )
+
+ MethodProfiler.patch(Redis::Client, %i[call call_pipeline], :redis)
+ MethodProfiler.patch(Net::HTTP, [:request], :net, no_recurse: true)
+
+ MethodProfiler.patch(Excon::Connection, [:request], :net)
+ true
+ end
+ end
end
diff --git a/lib/middleware/anonymous_cache.rb b/lib/middleware/anonymous_cache.rb
index ef6bc7e1dd2..553113e7899 100644
--- a/lib/middleware/anonymous_cache.rb
+++ b/lib/middleware/anonymous_cache.rb
@@ -7,17 +7,16 @@ require "http_language_parser"
module Middleware
class AnonymousCache
-
def self.cache_key_segments
@@cache_key_segments ||= {
- m: 'key_is_mobile?',
- c: 'key_is_crawler?',
- o: 'key_is_old_browser?',
- d: 'key_is_modern_mobile_device?',
- b: 'key_has_brotli?',
- t: 'key_cache_theme_ids',
- ca: 'key_compress_anon',
- l: 'key_locale'
+ m: "key_is_mobile?",
+ c: "key_is_crawler?",
+ o: "key_is_old_browser?",
+ d: "key_is_modern_mobile_device?",
+ b: "key_has_brotli?",
+ t: "key_cache_theme_ids",
+ ca: "key_compress_anon",
+ l: "key_locale",
}
end
@@ -46,9 +45,9 @@ module Middleware
# This gives us an API to insert anonymous cache segments
class Helper
- RACK_SESSION = "rack.session"
- USER_AGENT = "HTTP_USER_AGENT"
- ACCEPT_ENCODING = "HTTP_ACCEPT_ENCODING"
+ RACK_SESSION = "rack.session"
+ USER_AGENT = "HTTP_USER_AGENT"
+ ACCEPT_ENCODING = "HTTP_ACCEPT_ENCODING"
DISCOURSE_RENDER = "HTTP_DISCOURSE_RENDER"
REDIS_STORE_SCRIPT = DiscourseRedis::EvalHelper.new <<~LUA
@@ -63,13 +62,11 @@ module Middleware
end
def blocked_crawler?
- @request.get? &&
- [email protected]_with?('robots.txt') &&
- [email protected]_with?('srv/status') &&
- @request[Auth::DefaultCurrentUserProvider::API_KEY].nil? &&
- @env[Auth::DefaultCurrentUserProvider::USER_API_KEY].nil? &&
- CrawlerDetection.is_blocked_crawler?(@env[USER_AGENT])
+ @request.get? && [email protected]? && [email protected]_with?("robots.txt") &&
+ [email protected]_with?("srv/status") &&
+ @request[Auth::DefaultCurrentUserProvider::API_KEY].nil? &&
+ @env[Auth::DefaultCurrentUserProvider::USER_API_KEY].nil? &&
+ CrawlerDetection.is_blocked_crawler?(@env[USER_AGENT])
end
def is_mobile=(val)
@@ -112,10 +109,16 @@ module Middleware
begin
user_agent = @env[USER_AGENT]
- if @env[DISCOURSE_RENDER] == "crawler" || CrawlerDetection.crawler?(user_agent, @env["HTTP_VIA"])
+ if @env[DISCOURSE_RENDER] == "crawler" ||
+ CrawlerDetection.crawler?(user_agent, @env["HTTP_VIA"])
:true
else
- user_agent.downcase.include?("discourse") && !user_agent.downcase.include?("mobile") ? :true : :false
+ if user_agent.downcase.include?("discourse") &&
+ !user_agent.downcase.include?("mobile")
+ :true
+ else
+ :false
+ end
end
end
@is_crawler == :true
@@ -133,13 +136,14 @@ module Middleware
def cache_key
return @cache_key if defined?(@cache_key)
- @cache_key = +"ANON_CACHE_#{@env["HTTP_ACCEPT"]}_#{@env[Rack::RACK_URL_SCHEME]}_#{@env["HTTP_HOST"]}#{@env["REQUEST_URI"]}"
+ @cache_key =
+ +"ANON_CACHE_#{@env["HTTP_ACCEPT"]}_#{@env[Rack::RACK_URL_SCHEME]}_#{@env["HTTP_HOST"]}#{@env["REQUEST_URI"]}"
@cache_key << AnonymousCache.build_cache_key(self)
@cache_key
end
def key_cache_theme_ids
- theme_ids.join(',')
+ theme_ids.join(",")
end
def key_compress_anon
@@ -147,7 +151,7 @@ module Middleware
end
def theme_ids
- ids, _ = @request.cookies['theme_ids']&.split('|')
+ ids, _ = @request.cookies["theme_ids"]&.split("|")
id = ids&.split(",")&.map(&:to_i)&.first
if id && Guardian.new.allow_themes?([id])
Theme.transform_ids(id)
@@ -178,31 +182,31 @@ module Middleware
def no_cache_bypass
request = Rack::Request.new(@env)
- request.cookies['_bypass_cache'].nil? &&
- (request.path != '/srv/status') &&
+ request.cookies["_bypass_cache"].nil? && (request.path != "/srv/status") &&
request[Auth::DefaultCurrentUserProvider::API_KEY].nil? &&
@env[Auth::DefaultCurrentUserProvider::USER_API_KEY].nil?
end
def force_anonymous!
@env[Auth::DefaultCurrentUserProvider::USER_API_KEY] = nil
- @env['HTTP_COOKIE'] = nil
- @env['HTTP_DISCOURSE_LOGGED_IN'] = nil
- @env['rack.request.cookie.hash'] = {}
- @env['rack.request.cookie.string'] = ''
- @env['_bypass_cache'] = nil
+ @env["HTTP_COOKIE"] = nil
+ @env["HTTP_DISCOURSE_LOGGED_IN"] = nil
+ @env["rack.request.cookie.hash"] = {}
+ @env["rack.request.cookie.string"] = ""
+ @env["_bypass_cache"] = nil
request = Rack::Request.new(@env)
- request.delete_param('api_username')
- request.delete_param('api_key')
+ request.delete_param("api_username")
+ request.delete_param("api_key")
end
def logged_in_anon_limiter
- @logged_in_anon_limiter ||= RateLimiter.new(
- nil,
- "logged_in_anon_cache_#{@env["HTTP_HOST"]}/#{@env["REQUEST_URI"]}",
- GlobalSetting.force_anonymous_min_per_10_seconds,
- 10
- )
+ @logged_in_anon_limiter ||=
+ RateLimiter.new(
+ nil,
+ "logged_in_anon_cache_#{@env["HTTP_HOST"]}/#{@env["REQUEST_URI"]}",
+ GlobalSetting.force_anonymous_min_per_10_seconds,
+ 10,
+ )
end
def check_logged_in_rate_limit!
@@ -213,13 +217,11 @@ module Middleware
ADP = "action_dispatch.request.parameters"
def should_force_anonymous?
- if (queue_time = @env['REQUEST_QUEUE_SECONDS']) && get?
+ if (queue_time = @env["REQUEST_QUEUE_SECONDS"]) && get?
if queue_time > GlobalSetting.force_anonymous_min_queue_seconds
return check_logged_in_rate_limit!
elsif queue_time >= MIN_TIME_TO_CHECK
- if !logged_in_anon_limiter.can_perform?
- return check_logged_in_rate_limit!
- end
+ return check_logged_in_rate_limit! if !logged_in_anon_limiter.can_perform?
end
end
@@ -233,7 +235,7 @@ module Middleware
def compress(val)
if val && GlobalSetting.compress_anon_cache
require "lz4-ruby" if !defined?(LZ4)
- LZ4::compress(val)
+ LZ4.compress(val)
else
val
end
@@ -242,7 +244,7 @@ module Middleware
def decompress(val)
if val && GlobalSetting.compress_anon_cache
require "lz4-ruby" if !defined?(LZ4)
- LZ4::uncompress(val)
+ LZ4.uncompress(val)
else
val
end
@@ -273,7 +275,6 @@ module Middleware
status, headers, response = result
if status == 200 && cache_duration
-
if GlobalSetting.anon_cache_store_threshold > 1
count = REDIS_STORE_SCRIPT.eval(Discourse.redis, [cache_key_count], [cache_duration])
@@ -281,25 +282,24 @@ module Middleware
# prudent here, hence the to_i
if count.to_i < GlobalSetting.anon_cache_store_threshold
headers["X-Discourse-Cached"] = "skip"
- return [status, headers, response]
+ return status, headers, response
end
end
- headers_stripped = headers.dup.delete_if { |k, _| ["Set-Cookie", "X-MiniProfiler-Ids"].include? k }
+ headers_stripped =
+ headers.dup.delete_if { |k, _| %w[Set-Cookie X-MiniProfiler-Ids].include? k }
headers_stripped["X-Discourse-Cached"] = "true"
parts = []
- response.each do |part|
- parts << part
- end
+ response.each { |part| parts << part }
if req_params = env[ADP]
headers_stripped[ADP] = {
"action" => req_params["action"],
- "controller" => req_params["controller"]
+ "controller" => req_params["controller"],
}
end
- Discourse.redis.setex(cache_key_body, cache_duration, compress(parts.join))
+ Discourse.redis.setex(cache_key_body, cache_duration, compress(parts.join))
Discourse.redis.setex(cache_key_other, cache_duration, [status, headers_stripped].to_json)
headers["X-Discourse-Cached"] = "store"
@@ -314,20 +314,18 @@ module Middleware
Discourse.redis.del(cache_key_body)
Discourse.redis.del(cache_key_other)
end
-
end
def initialize(app, settings = {})
@app = app
end
- PAYLOAD_INVALID_REQUEST_METHODS = ["GET", "HEAD"]
+ PAYLOAD_INVALID_REQUEST_METHODS = %w[GET HEAD]
def call(env)
if PAYLOAD_INVALID_REQUEST_METHODS.include?(env[Rack::REQUEST_METHOD]) &&
- env[Rack::RACK_INPUT].size > 0
-
- return [413, { "Cache-Control" => "private, max-age=0, must-revalidate" }, []]
+ env[Rack::RACK_INPUT].size > 0
+ return 413, { "Cache-Control" => "private, max-age=0, must-revalidate" }, []
end
helper = Helper.new(env)
@@ -335,7 +333,7 @@ module Middleware
if helper.blocked_crawler?
env["discourse.request_tracker.skip"] = true
- return [403, {}, ["Crawler is not allowed!"]]
+ return 403, {}, ["Crawler is not allowed!"]
end
if helper.should_force_anonymous?
@@ -348,15 +346,15 @@ module Middleware
if max_time > 0 && queue_time.to_f > max_time
return [
429,
- {
- "content-type" => "application/json; charset=utf-8"
- },
- [{
- errors: I18n.t("rate_limiter.slow_down"),
- extras: {
- wait_seconds: 5 + (5 * rand).round(2)
- }
- }.to_json]
+ { "content-type" => "application/json; charset=utf-8" },
+ [
+ {
+ errors: I18n.t("rate_limiter.slow_down"),
+ extras: {
+ wait_seconds: 5 + (5 * rand).round(2),
+ },
+ }.to_json,
+ ]
]
end
end
@@ -368,13 +366,9 @@ module Middleware
@app.call(env)
end
- if force_anon
- result[1]["Set-Cookie"] = "dosp=1; Path=/"
- end
+ result[1]["Set-Cookie"] = "dosp=1; Path=/" if force_anon
result
end
-
end
-
end
diff --git a/lib/middleware/discourse_public_exceptions.rb b/lib/middleware/discourse_public_exceptions.rb
index 9a9ea11571c..b507bc867a3 100644
--- a/lib/middleware/discourse_public_exceptions.rb
+++ b/lib/middleware/discourse_public_exceptions.rb
@@ -4,11 +4,14 @@
# we need to handle certain exceptions here
module Middleware
class DiscoursePublicExceptions < ::ActionDispatch::PublicExceptions
- INVALID_REQUEST_ERRORS = Set.new([
- Rack::QueryParser::InvalidParameterError,
- ActionController::BadRequest,
- ActionDispatch::Http::Parameters::ParseError,
- ])
+ INVALID_REQUEST_ERRORS =
+ Set.new(
+ [
+ Rack::QueryParser::InvalidParameterError,
+ ActionController::BadRequest,
+ ActionDispatch::Http::Parameters::ParseError,
+ ],
+ )
def initialize(path)
super
@@ -35,31 +38,38 @@ module Middleware
begin
request.format
rescue Mime::Type::InvalidMimeType
- return [400, { "Cache-Control" => "private, max-age=0, must-revalidate" }, ["Invalid MIME type"]]
+ return [
+ 400,
+ { "Cache-Control" => "private, max-age=0, must-revalidate" },
+ ["Invalid MIME type"]
+ ]
end
# Or badly formatted multipart requests
begin
request.POST
rescue EOFError
- return [400, { "Cache-Control" => "private, max-age=0, must-revalidate" }, ["Invalid request"]]
+ return [
+ 400,
+ { "Cache-Control" => "private, max-age=0, must-revalidate" },
+ ["Invalid request"]
+ ]
end
if ApplicationController.rescue_with_handler(exception, object: fake_controller)
body = response.body
- if String === body
- body = [body]
- end
- return [response.status, response.headers, body]
+ body = [body] if String === body
+ return response.status, response.headers, body
end
rescue => e
return super if INVALID_REQUEST_ERRORS.include?(e.class)
- Discourse.warn_exception(e, message: "Failed to handle exception in exception app middleware")
+ Discourse.warn_exception(
+ e,
+ message: "Failed to handle exception in exception app middleware",
+ )
end
-
end
super
end
-
end
end
diff --git a/lib/middleware/enforce_hostname.rb b/lib/middleware/enforce_hostname.rb
index 44ac8d7d4a1..f0f604b145b 100644
--- a/lib/middleware/enforce_hostname.rb
+++ b/lib/middleware/enforce_hostname.rb
@@ -18,7 +18,8 @@ module Middleware
requested_hostname = env[Rack::HTTP_HOST]
env[Discourse::REQUESTED_HOSTNAME] = requested_hostname
- env[Rack::HTTP_HOST] = allowed_hostnames.find { |h| h == requested_hostname } || Discourse.current_hostname_with_port
+ env[Rack::HTTP_HOST] = allowed_hostnames.find { |h| h == requested_hostname } ||
+ Discourse.current_hostname_with_port
@app.call(env)
end
diff --git a/lib/middleware/missing_avatars.rb b/lib/middleware/missing_avatars.rb
index f0f2da5d5c1..958aecaa3ee 100644
--- a/lib/middleware/missing_avatars.rb
+++ b/lib/middleware/missing_avatars.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module Middleware
-
# In development mode, it is common to use a database from a production site for testing
# with their data. Unfortunately, you can end up with dozens of missing avatar requests
# due to the files not being present locally. This middleware, only enabled in development
@@ -12,11 +11,11 @@ module Middleware
end
def call(env)
- if (env['REQUEST_PATH'] =~ /^\/uploads\/default\/avatars/)
- path = "#{Rails.root}/public#{env['REQUEST_PATH']}"
+ if (env["REQUEST_PATH"] =~ %r{^/uploads/default/avatars})
+ path = "#{Rails.root}/public#{env["REQUEST_PATH"]}"
unless File.exist?(path)
default_image = "#{Rails.root}/public/images/d-logo-sketch-small.png"
- return [ 200, { 'Content-Type' => 'image/png' }, [ File.read(default_image)] ]
+ return 200, { "Content-Type" => "image/png" }, [File.read(default_image)]
end
end
@@ -24,5 +23,4 @@ module Middleware
[status, headers, response]
end
end
-
end
diff --git a/lib/middleware/omniauth_bypass_middleware.rb b/lib/middleware/omniauth_bypass_middleware.rb
index c794b11aabb..b8c65caac88 100644
--- a/lib/middleware/omniauth_bypass_middleware.rb
+++ b/lib/middleware/omniauth_bypass_middleware.rb
@@ -5,7 +5,8 @@ require "csrf_token_verifier"
# omniauth loves spending lots cycles in its magic middleware stack
# this middleware bypasses omniauth middleware and only hits it when needed
class Middleware::OmniauthBypassMiddleware
- class AuthenticatorDisabled < StandardError; end
+ class AuthenticatorDisabled < StandardError
+ end
def initialize(app, options = {})
@app = app
@@ -15,11 +16,10 @@ class Middleware::OmniauthBypassMiddleware
# if you need to test this and are having ssl issues see:
# http://stackoverflow.com/questions/6756460/openssl-error-using-omniauth-specified-ssl-path-but-didnt-work
# OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE if Rails.env.development?
- @omniauth = OmniAuth::Builder.new(app) do
- Discourse.authenticators.each do |authenticator|
- authenticator.register_middleware(self)
+ @omniauth =
+ OmniAuth::Builder.new(app) do
+ Discourse.authenticators.each { |authenticator| authenticator.register_middleware(self) }
end
- end
@omniauth.before_request_phase do |env|
request = ActionDispatch::Request.new(env)
@@ -28,7 +28,9 @@ class Middleware::OmniauthBypassMiddleware
CSRFTokenVerifier.new.call(env) if request.request_method.downcase.to_sym != :get
# Check whether the authenticator is enabled
- if !Discourse.enabled_authenticators.any? { |a| a.name.to_sym == env['omniauth.strategy'].name.to_sym }
+ if !Discourse.enabled_authenticators.any? { |a|
+ a.name.to_sym == env["omniauth.strategy"].name.to_sym
+ }
raise AuthenticatorDisabled
end
@@ -44,8 +46,9 @@ class Middleware::OmniauthBypassMiddleware
if env["PATH_INFO"].start_with?("/auth")
begin
# When only one provider is enabled, assume it can be completely trusted, and allow GET requests
- only_one_provider = !SiteSetting.enable_local_logins && Discourse.enabled_authenticators.length == 1
- OmniAuth.config.allowed_request_methods = only_one_provider ? [:get, :post] : [:post]
+ only_one_provider =
+ !SiteSetting.enable_local_logins && Discourse.enabled_authenticators.length == 1
+ OmniAuth.config.allowed_request_methods = only_one_provider ? %i[get post] : [:post]
@omniauth.call(env)
rescue AuthenticatorDisabled => e
@@ -71,5 +74,4 @@ class Middleware::OmniauthBypassMiddleware
@app.call(env)
end
end
-
end
diff --git a/lib/middleware/request_tracker.rb b/lib/middleware/request_tracker.rb
index 4decb0983c8..23acf64d127 100644
--- a/lib/middleware/request_tracker.rb
+++ b/lib/middleware/request_tracker.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'method_profiler'
-require 'middleware/anonymous_cache'
+require "method_profiler"
+require "middleware/anonymous_cache"
class Middleware::RequestTracker
@@detailed_request_loggers = nil
@@ -15,7 +15,8 @@ class Middleware::RequestTracker
# 14.15.16.32/27
# 216.148.1.2
#
- STATIC_IP_SKIPPER = ENV['DISCOURSE_MAX_REQS_PER_IP_EXCEPTIONS']&.split&.map { |ip| IPAddr.new(ip) }
+ STATIC_IP_SKIPPER =
+ ENV["DISCOURSE_MAX_REQS_PER_IP_EXCEPTIONS"]&.split&.map { |ip| IPAddr.new(ip) }
# register callbacks for detailed request loggers called on every request
# example:
@@ -30,9 +31,7 @@ class Middleware::RequestTracker
def self.unregister_detailed_request_logger(callback)
@@detailed_request_loggers.delete(callback)
- if @@detailed_request_loggers.length == 0
- @detailed_request_loggers = nil
- end
+ @detailed_request_loggers = nil if @@detailed_request_loggers.length == 0
end
# used for testing
@@ -107,7 +106,8 @@ class Middleware::RequestTracker
env_track_view = env["HTTP_DISCOURSE_TRACK_VIEW"]
track_view = status == 200
track_view &&= env_track_view != "0" && env_track_view != "false"
- track_view &&= env_track_view || (request.get? && !request.xhr? && headers["Content-Type"] =~ /text\/html/)
+ track_view &&=
+ env_track_view || (request.get? && !request.xhr? && headers["Content-Type"] =~ %r{text/html})
track_view = !!track_view
has_auth_cookie = Auth::DefaultCurrentUserProvider.find_v0_auth_cookie(request).present?
has_auth_cookie ||= Auth::DefaultCurrentUserProvider.find_v1_auth_cookie(env).present?
@@ -128,7 +128,7 @@ class Middleware::RequestTracker
is_mobile: helper.is_mobile?,
track_view: track_view,
timing: timing,
- queue_seconds: env['REQUEST_QUEUE_SECONDS']
+ queue_seconds: env["REQUEST_QUEUE_SECONDS"],
}
if h[:is_background]
@@ -146,7 +146,7 @@ class Middleware::RequestTracker
end
if h[:is_crawler]
- user_agent = env['HTTP_USER_AGENT']
+ user_agent = env["HTTP_USER_AGENT"]
if user_agent && (user_agent.encoding != Encoding::UTF_8)
user_agent = user_agent.encode("utf-8")
user_agent.scrub!
@@ -163,7 +163,12 @@ class Middleware::RequestTracker
def log_request_info(env, result, info, request = nil)
# we got to skip this on error ... its just logging
- data = self.class.get_data(env, result, info, request) rescue nil
+ data =
+ begin
+ self.class.get_data(env, result, info, request)
+ rescue StandardError
+ nil
+ end
if data
if result && (headers = result[1])
@@ -179,15 +184,16 @@ class Middleware::RequestTracker
end
def self.populate_request_queue_seconds!(env)
- if !env['REQUEST_QUEUE_SECONDS']
- if queue_start = env['HTTP_X_REQUEST_START']
- queue_start = if queue_start.start_with?("t=")
- queue_start.split("t=")[1].to_f
- else
- queue_start.to_f / 1000.0
- end
+ if !env["REQUEST_QUEUE_SECONDS"]
+ if queue_start = env["HTTP_X_REQUEST_START"]
+ queue_start =
+ if queue_start.start_with?("t=")
+ queue_start.split("t=")[1].to_f
+ else
+ queue_start.to_f / 1000.0
+ end
queue_time = (Time.now.to_f - queue_start)
- env['REQUEST_QUEUE_SECONDS'] = queue_time
+ env["REQUEST_QUEUE_SECONDS"] = queue_time
end
end
end
@@ -212,9 +218,9 @@ class Middleware::RequestTracker
TEXT
headers = {
"Retry-After" => available_in.to_s,
- "Discourse-Rate-Limit-Error-Code" => error_code
+ "Discourse-Rate-Limit-Error-Code" => error_code,
}
- return [429, headers, [message]]
+ return 429, headers, [message]
end
env["discourse.request_tracker"] = self
@@ -235,21 +241,21 @@ class Middleware::RequestTracker
headers["X-Sql-Calls"] = sql[:calls].to_s
headers["X-Sql-Time"] = "%0.6f" % sql[:duration]
end
- if queue = env['REQUEST_QUEUE_SECONDS']
+ if queue = env["REQUEST_QUEUE_SECONDS"]
headers["X-Queue-Time"] = "%0.6f" % queue
end
end
end
if env[Auth::DefaultCurrentUserProvider::BAD_TOKEN] && (headers = result[1])
- headers['Discourse-Logged-Out'] = '1'
+ headers["Discourse-Logged-Out"] = "1"
end
result
ensure
- if (limiters = env['DISCOURSE_RATE_LIMITERS']) && env['DISCOURSE_IS_ASSET_PATH']
+ if (limiters = env["DISCOURSE_RATE_LIMITERS"]) && env["DISCOURSE_IS_ASSET_PATH"]
limiters.each(&:rollback!)
- env['DISCOURSE_ASSET_RATE_LIMITERS'].each do |limiter|
+ env["DISCOURSE_ASSET_RATE_LIMITERS"].each do |limiter|
begin
limiter.performed!
rescue RateLimiter::LimitExceeded
@@ -257,25 +263,19 @@ class Middleware::RequestTracker
end
end
end
- if !env["discourse.request_tracker.skip"]
- log_request_info(env, result, info, request)
- end
+ log_request_info(env, result, info, request) if !env["discourse.request_tracker.skip"]
end
def log_later(data)
Scheduler::Defer.later("Track view") do
- unless Discourse.pg_readonly_mode?
- self.class.log_request(data)
- end
+ self.class.log_request(data) unless Discourse.pg_readonly_mode?
end
end
def find_auth_cookie(env)
min_allowed_timestamp = Time.now.to_i - (UserAuthToken::ROTATE_TIME_MINS + 1) * 60
cookie = Auth::DefaultCurrentUserProvider.find_v1_auth_cookie(env)
- if cookie && cookie[:issued_at] >= min_allowed_timestamp
- cookie
- end
+ cookie if cookie && cookie[:issued_at] >= min_allowed_timestamp
end
def is_private_ip?(ip)
@@ -286,10 +286,12 @@ class Middleware::RequestTracker
end
def rate_limit(request, cookie)
- warn = GlobalSetting.max_reqs_per_ip_mode == "warn" ||
- GlobalSetting.max_reqs_per_ip_mode == "warn+block"
- block = GlobalSetting.max_reqs_per_ip_mode == "block" ||
- GlobalSetting.max_reqs_per_ip_mode == "warn+block"
+ warn =
+ GlobalSetting.max_reqs_per_ip_mode == "warn" ||
+ GlobalSetting.max_reqs_per_ip_mode == "warn+block"
+ block =
+ GlobalSetting.max_reqs_per_ip_mode == "block" ||
+ GlobalSetting.max_reqs_per_ip_mode == "warn+block"
return if !block && !warn
@@ -304,54 +306,56 @@ class Middleware::RequestTracker
ip_or_id = ip
limit_on_id = false
- if cookie && cookie[:user_id] && cookie[:trust_level] && cookie[:trust_level] >= GlobalSetting.skip_per_ip_rate_limit_trust_level
+ if cookie && cookie[:user_id] && cookie[:trust_level] &&
+ cookie[:trust_level] >= GlobalSetting.skip_per_ip_rate_limit_trust_level
ip_or_id = cookie[:user_id]
limit_on_id = true
end
- limiter10 = RateLimiter.new(
- nil,
- "global_ip_limit_10_#{ip_or_id}",
- GlobalSetting.max_reqs_per_ip_per_10_seconds,
- 10,
- global: !limit_on_id,
- aggressive: true,
- error_code: limit_on_id ? "id_10_secs_limit" : "ip_10_secs_limit"
- )
-
- limiter60 = RateLimiter.new(
- nil,
- "global_ip_limit_60_#{ip_or_id}",
- GlobalSetting.max_reqs_per_ip_per_minute,
- 60,
- global: !limit_on_id,
- error_code: limit_on_id ? "id_60_secs_limit" : "ip_60_secs_limit",
- aggressive: true
- )
-
- limiter_assets10 = RateLimiter.new(
- nil,
- "global_ip_limit_10_assets_#{ip_or_id}",
- GlobalSetting.max_asset_reqs_per_ip_per_10_seconds,
- 10,
- error_code: limit_on_id ? "id_assets_10_secs_limit" : "ip_assets_10_secs_limit",
- global: !limit_on_id
- )
-
- request.env['DISCOURSE_RATE_LIMITERS'] = [limiter10, limiter60]
- request.env['DISCOURSE_ASSET_RATE_LIMITERS'] = [limiter_assets10]
+ limiter10 =
+ RateLimiter.new(
+ nil,
+ "global_ip_limit_10_#{ip_or_id}",
+ GlobalSetting.max_reqs_per_ip_per_10_seconds,
+ 10,
+ global: !limit_on_id,
+ aggressive: true,
+ error_code: limit_on_id ? "id_10_secs_limit" : "ip_10_secs_limit",
+ )
+
+ limiter60 =
+ RateLimiter.new(
+ nil,
+ "global_ip_limit_60_#{ip_or_id}",
+ GlobalSetting.max_reqs_per_ip_per_minute,
+ 60,
+ global: !limit_on_id,
+ error_code: limit_on_id ? "id_60_secs_limit" : "ip_60_secs_limit",
+ aggressive: true,
+ )
+
+ limiter_assets10 =
+ RateLimiter.new(
+ nil,
+ "global_ip_limit_10_assets_#{ip_or_id}",
+ GlobalSetting.max_asset_reqs_per_ip_per_10_seconds,
+ 10,
+ error_code: limit_on_id ? "id_assets_10_secs_limit" : "ip_assets_10_secs_limit",
+ global: !limit_on_id,
+ )
+
+ request.env["DISCOURSE_RATE_LIMITERS"] = [limiter10, limiter60]
+ request.env["DISCOURSE_ASSET_RATE_LIMITERS"] = [limiter_assets10]
if !limiter_assets10.can_perform?
if warn
- Discourse.warn("Global asset IP rate limit exceeded for #{ip}: 10 second rate limit", uri: request.env["REQUEST_URI"])
+ Discourse.warn(
+ "Global asset IP rate limit exceeded for #{ip}: 10 second rate limit",
+ uri: request.env["REQUEST_URI"],
+ )
end
- if block
- return [
- limiter_assets10.seconds_to_wait(Time.now.to_i),
- limiter_assets10.error_code
- ]
- end
+ return limiter_assets10.seconds_to_wait(Time.now.to_i), limiter_assets10.error_code if block
end
begin
@@ -364,7 +368,10 @@ class Middleware::RequestTracker
nil
rescue RateLimiter::LimitExceeded => e
if warn
- Discourse.warn("Global IP rate limit exceeded for #{ip}: #{type} second rate limit", uri: request.env["REQUEST_URI"])
+ Discourse.warn(
+ "Global IP rate limit exceeded for #{ip}: #{type} second rate limit",
+ uri: request.env["REQUEST_URI"],
+ )
end
if block
[e.available_in, e.error_code]
diff --git a/lib/middleware/turbo_dev.rb b/lib/middleware/turbo_dev.rb
index 53e81cb50df..8754508caf6 100644
--- a/lib/middleware/turbo_dev.rb
+++ b/lib/middleware/turbo_dev.rb
@@ -1,6 +1,5 @@
# frozen_string_literal: true
module Middleware
-
# Cheat and bypass Rails in development mode if the client attempts to download a static asset
# that's already been downloaded.
#
@@ -19,22 +18,19 @@ module Middleware
def call(env)
root = "#{GlobalSetting.relative_url_root}/assets/"
- is_asset = env['REQUEST_PATH'] && env['REQUEST_PATH'].starts_with?(root)
+ is_asset = env["REQUEST_PATH"] && env["REQUEST_PATH"].starts_with?(root)
# hack to bypass all middleware if serving assets, a lot faster 4.5 seconds -> 1.5 seconds
- if (etag = env['HTTP_IF_NONE_MATCH']) && is_asset
- name = env['REQUEST_PATH'][(root.length)..-1]
+ if (etag = env["HTTP_IF_NONE_MATCH"]) && is_asset
+ name = env["REQUEST_PATH"][(root.length)..-1]
etag = etag.gsub "\"", ""
asset = Rails.application.assets.find_asset(name)
- if asset && asset.digest == etag
- return [304, {}, []]
- end
+ return 304, {}, [] if asset && asset.digest == etag
end
status, headers, response = @app.call(env)
- headers['Cache-Control'] = 'no-cache' if is_asset
+ headers["Cache-Control"] = "no-cache" if is_asset
[status, headers, response]
end
end
-
end
diff --git a/lib/migration/base_dropper.rb b/lib/migration/base_dropper.rb
index 9aaf77e138a..abf7a39a734 100644
--- a/lib/migration/base_dropper.rb
+++ b/lib/migration/base_dropper.rb
@@ -9,9 +9,14 @@ module Migration
CREATE SCHEMA IF NOT EXISTS #{FUNCTION_SCHEMA_NAME};
SQL
- message = column_name ?
- "Discourse: #{column_name} in #{table_name} is readonly" :
- "Discourse: #{table_name} is read only"
+ message =
+ (
+ if column_name
+ "Discourse: #{column_name} in #{table_name} is readonly"
+ else
+ "Discourse: #{table_name} is read only"
+ end
+ )
DB.exec <<~SQL
CREATE OR REPLACE FUNCTION #{readonly_function_name(table_name, column_name)} RETURNS trigger AS $rcr$
@@ -27,12 +32,7 @@ module Migration
end
def self.readonly_function_name(table_name, column_name = nil, with_schema: true)
- function_name = [
- "raise",
- table_name,
- column_name,
- "readonly()"
- ].compact.join("_")
+ function_name = ["raise", table_name, column_name, "readonly()"].compact.join("_")
if with_schema && function_schema_exists?
"#{FUNCTION_SCHEMA_NAME}.#{function_name}"
@@ -42,9 +42,7 @@ module Migration
end
def self.old_readonly_function_name(table_name, column_name = nil)
- readonly_function_name(table_name, column_name).sub(
- "#{FUNCTION_SCHEMA_NAME}.", ''
- )
+ readonly_function_name(table_name, column_name).sub("#{FUNCTION_SCHEMA_NAME}.", "")
end
def self.readonly_trigger_name(table_name, column_name = nil)
@@ -52,7 +50,7 @@ module Migration
end
def self.function_schema_exists?
- DB.exec(<<~SQL).to_s == '1'
+ DB.exec(<<~SQL).to_s == "1"
SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = '#{FUNCTION_SCHEMA_NAME}'
diff --git a/lib/migration/column_dropper.rb b/lib/migration/column_dropper.rb
index 71e472baa49..83d2feec640 100644
--- a/lib/migration/column_dropper.rb
+++ b/lib/migration/column_dropper.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'migration/base_dropper'
+require "migration/base_dropper"
module Migration
class ColumnDropper
@@ -32,7 +32,9 @@ module Migration
BaseDropper.drop_readonly_function(table_name, column_name)
# Backward compatibility for old functions created in the public schema
- DB.exec("DROP FUNCTION IF EXISTS #{BaseDropper.old_readonly_function_name(table_name, column_name)} CASCADE")
+ DB.exec(
+ "DROP FUNCTION IF EXISTS #{BaseDropper.old_readonly_function_name(table_name, column_name)} CASCADE",
+ )
end
end
end
diff --git a/lib/migration/safe_migrate.rb b/lib/migration/safe_migrate.rb
index 0c8105e5593..ce3013300e0 100644
--- a/lib/migration/safe_migrate.rb
+++ b/lib/migration/safe_migrate.rb
@@ -1,8 +1,10 @@
# frozen_string_literal: true
-module Migration; end
+module Migration
+end
-class Discourse::InvalidMigration < StandardError; end
+class Discourse::InvalidMigration < StandardError
+end
class Migration::SafeMigrate
module SafeMigration
@@ -17,11 +19,9 @@ class Migration::SafeMigrate
end
def migrate(direction)
- if direction == :up &&
- version && version > Migration::SafeMigrate.earliest_post_deploy_version &&
- @@enable_safe != false &&
- !is_post_deploy_migration?
-
+ if direction == :up && version &&
+ version > Migration::SafeMigrate.earliest_post_deploy_version &&
+ @@enable_safe != false && !is_post_deploy_migration?
Migration::SafeMigrate.enable!
end
@@ -44,9 +44,7 @@ class Migration::SafeMigrate
return false if !method
- self.method(method).source_location.first.include?(
- Discourse::DB_POST_MIGRATE_PATH
- )
+ self.method(method).source_location.first.include?(Discourse::DB_POST_MIGRATE_PATH)
end
end
@@ -76,7 +74,7 @@ class Migration::SafeMigrate
def self.enable!
return if PG::Connection.method_defined?(:exec_migrator_unpatched)
- return if ENV['RAILS_ENV'] == "production"
+ return if ENV["RAILS_ENV"] == "production"
PG::Connection.class_eval do
alias_method :exec_migrator_unpatched, :exec
@@ -96,7 +94,7 @@ class Migration::SafeMigrate
def self.disable!
return if !PG::Connection.method_defined?(:exec_migrator_unpatched)
- return if ENV['RAILS_ENV'] == "production"
+ return if ENV["RAILS_ENV"] == "production"
PG::Connection.class_eval do
alias_method :exec, :exec_migrator_unpatched
@@ -108,11 +106,9 @@ class Migration::SafeMigrate
end
def self.patch_active_record!
- return if ENV['RAILS_ENV'] == "production"
+ return if ENV["RAILS_ENV"] == "production"
- ActiveSupport.on_load(:active_record) do
- ActiveRecord::Migration.prepend(SafeMigration)
- end
+ ActiveSupport.on_load(:active_record) { ActiveRecord::Migration.prepend(SafeMigration) }
if defined?(ActiveRecord::Tasks::DatabaseTasks)
ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(NiceErrors)
@@ -154,10 +150,11 @@ class Migration::SafeMigrate
end
def self.earliest_post_deploy_version
- @@earliest_post_deploy_version ||= begin
- first_file = Dir.glob("#{Discourse::DB_POST_MIGRATE_PATH}/*.rb").sort.first
- file_name = File.basename(first_file, ".rb")
- file_name.first(14).to_i
- end
+ @@earliest_post_deploy_version ||=
+ begin
+ first_file = Dir.glob("#{Discourse::DB_POST_MIGRATE_PATH}/*.rb").sort.first
+ file_name = File.basename(first_file, ".rb")
+ file_name.first(14).to_i
+ end
end
end
diff --git a/lib/migration/table_dropper.rb b/lib/migration/table_dropper.rb
index bbd27f02e5b..f2f9849cb9b 100644
--- a/lib/migration/table_dropper.rb
+++ b/lib/migration/table_dropper.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'migration/base_dropper'
+require "migration/base_dropper"
module Migration
class Migration::TableDropper
diff --git a/lib/mini_sql_multisite_connection.rb b/lib/mini_sql_multisite_connection.rb
index 26ad1d50263..2b8ef82066a 100644
--- a/lib/mini_sql_multisite_connection.rb
+++ b/lib/mini_sql_multisite_connection.rb
@@ -1,16 +1,17 @@
# frozen_string_literal: true
class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
-
class CustomBuilder < MiniSql::Builder
-
def initialize(connection, sql)
super
end
- def secure_category(secure_category_ids, category_alias = 'c')
+ def secure_category(secure_category_ids, category_alias = "c")
if secure_category_ids.present?
- where("NOT COALESCE(#{category_alias}.read_restricted, false) OR #{category_alias}.id in (:secure_category_ids)", secure_category_ids: secure_category_ids)
+ where(
+ "NOT COALESCE(#{category_alias}.read_restricted, false) OR #{category_alias}.id in (:secure_category_ids)",
+ secure_category_ids: secure_category_ids,
+ )
else
where("NOT COALESCE(#{category_alias}.read_restricted, false)")
end
@@ -40,8 +41,10 @@ class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
end
end
- def before_committed!(*); end
- def rolledback!(*); end
+ def before_committed!(*)
+ end
+ def rolledback!(*)
+ end
def trigger_transactional_callbacks?
true
end
@@ -67,9 +70,7 @@ class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
def after_commit(&blk)
return blk.call if !transaction_open?
- ActiveRecord::Base.connection.add_transaction_record(
- AfterCommitWrapper.new(&blk)
- )
+ ActiveRecord::Base.connection.add_transaction_record(AfterCommitWrapper.new(&blk))
end
def self.instance
@@ -107,5 +108,4 @@ class MiniSqlMultisiteConnection < MiniSql::ActiveRecordPostgres::Connection
query
end
end
-
end
diff --git a/lib/mobile_detection.rb b/lib/mobile_detection.rb
index 0fb621dd377..1ff3361a15d 100644
--- a/lib/mobile_detection.rb
+++ b/lib/mobile_detection.rb
@@ -10,10 +10,11 @@ module MobileDetection
return false unless SiteSetting.enable_mobile_theme
session[:mobile_view] = params[:mobile_view] if params && params.has_key?(:mobile_view)
- session[:mobile_view] = nil if params && params.has_key?(:mobile_view) && params[:mobile_view] == 'auto'
+ session[:mobile_view] = nil if params && params.has_key?(:mobile_view) &&
+ params[:mobile_view] == "auto"
if session && session[:mobile_view]
- session[:mobile_view] == '1'
+ session[:mobile_view] == "1"
else
mobile_device?(user_agent)
end
@@ -23,7 +24,8 @@ module MobileDetection
user_agent =~ /iPad|iPhone|iPod/
end
- MODERN_MOBILE_REGEX = %r{
+ MODERN_MOBILE_REGEX =
+ %r{
\(.*iPhone\ OS\ 1[3-9].*\)|
\(.*iPad.*OS\ 1[3-9].*\)|
Chrome\/8[89]|
@@ -37,5 +39,4 @@ module MobileDetection
def self.modern_mobile_device?(user_agent)
user_agent.match?(MODERN_MOBILE_REGEX)
end
-
end
diff --git a/lib/new_post_manager.rb b/lib/new_post_manager.rb
index 777d93bdb0d..3903c5dd53d 100644
--- a/lib/new_post_manager.rb
+++ b/lib/new_post_manager.rb
@@ -6,7 +6,6 @@
# with `NewPostManager.add_handler` to take other approaches depending
# on the user or input.
class NewPostManager
-
attr_reader :user, :args
def self.sorted_handlers
@@ -38,24 +37,21 @@ class NewPostManager
user = manager.user
args = manager.args
- !!(
- args[:first_post_checks] &&
- user.post_count == 0 &&
- user.topic_count == 0
- )
+ !!(args[:first_post_checks] && user.post_count == 0 && user.topic_count == 0)
end
def self.is_fast_typer?(manager)
args = manager.args
is_first_post?(manager) &&
- args[:typing_duration_msecs].to_i < SiteSetting.min_first_post_typing_time &&
- SiteSetting.auto_silence_fast_typers_on_first_post &&
- manager.user.trust_level <= SiteSetting.auto_silence_fast_typers_max_trust_level
+ args[:typing_duration_msecs].to_i < SiteSetting.min_first_post_typing_time &&
+ SiteSetting.auto_silence_fast_typers_on_first_post &&
+ manager.user.trust_level <= SiteSetting.auto_silence_fast_typers_max_trust_level
end
def self.auto_silence?(manager)
- is_first_post?(manager) && WordWatcher.new("#{manager.args[:title]} #{manager.args[:raw]}").should_silence?
+ is_first_post?(manager) &&
+ WordWatcher.new("#{manager.args[:title]} #{manager.args[:raw]}").should_silence?
end
def self.matches_auto_silence_regex?(manager)
@@ -74,7 +70,6 @@ class NewPostManager
end
"#{args[:title]} #{args[:raw]}" =~ regex
-
end
def self.exempt_user?(user)
@@ -90,19 +85,25 @@ class NewPostManager
return :email_spam if manager.args[:email_spam]
- return :post_count if (
- user.trust_level <= TrustLevel.levels[:basic] &&
- (user.post_count + user.topic_count) < SiteSetting.approve_post_count
- )
+ if (
+ user.trust_level <= TrustLevel.levels[:basic] &&
+ (user.post_count + user.topic_count) < SiteSetting.approve_post_count
+ )
+ return :post_count
+ end
return :trust_level if user.trust_level < SiteSetting.approve_unless_trust_level.to_i
- return :new_topics_unless_trust_level if (
- manager.args[:title].present? &&
- user.trust_level < SiteSetting.approve_new_topics_unless_trust_level.to_i
- )
+ if (
+ manager.args[:title].present? &&
+ user.trust_level < SiteSetting.approve_new_topics_unless_trust_level.to_i
+ )
+ return :new_topics_unless_trust_level
+ end
- return :watched_word if WordWatcher.new("#{manager.args[:title]} #{manager.args[:raw]}").requires_approval?
+ if WordWatcher.new("#{manager.args[:title]} #{manager.args[:raw]}").requires_approval?
+ return :watched_word
+ end
return :fast_typer if is_fast_typer?(manager)
@@ -112,10 +113,12 @@ class NewPostManager
return :category if post_needs_approval_in_its_category?(manager)
- return :contains_media if (
- manager.args[:image_sizes].present? &&
- user.trust_level < SiteSetting.review_media_unless_trust_level.to_i
- )
+ if (
+ manager.args[:image_sizes].present? &&
+ user.trust_level < SiteSetting.review_media_unless_trust_level.to_i
+ )
+ return :contains_media
+ end
:skip
end
@@ -136,7 +139,6 @@ class NewPostManager
end
def self.default_handler(manager)
-
reason = post_needs_approval?(manager)
return if reason == :skip
@@ -171,11 +173,26 @@ class NewPostManager
I18n.with_locale(SiteSetting.default_locale) do
if is_fast_typer?(manager)
- UserSilencer.silence(manager.user, Discourse.system_user, keep_posts: true, reason: I18n.t("user.new_user_typed_too_fast"))
+ UserSilencer.silence(
+ manager.user,
+ Discourse.system_user,
+ keep_posts: true,
+ reason: I18n.t("user.new_user_typed_too_fast"),
+ )
elsif auto_silence?(manager) || matches_auto_silence_regex?(manager)
- UserSilencer.silence(manager.user, Discourse.system_user, keep_posts: true, reason: I18n.t("user.content_matches_auto_silence_regex"))
+ UserSilencer.silence(
+ manager.user,
+ Discourse.system_user,
+ keep_posts: true,
+ reason: I18n.t("user.content_matches_auto_silence_regex"),
+ )
elsif reason == :email_spam && is_first_post?(manager)
- UserSilencer.silence(manager.user, Discourse.system_user, keep_posts: true, reason: I18n.t("user.email_in_spam_header"))
+ UserSilencer.silence(
+ manager.user,
+ Discourse.system_user,
+ keep_posts: true,
+ reason: I18n.t("user.email_in_spam_header"),
+ )
end
end
@@ -183,12 +200,10 @@ class NewPostManager
end
def self.queue_enabled?
- SiteSetting.approve_post_count > 0 ||
- SiteSetting.approve_unless_trust_level.to_i > 0 ||
- SiteSetting.approve_new_topics_unless_trust_level.to_i > 0 ||
- SiteSetting.approve_unless_staged ||
- WordWatcher.words_for_action_exists?(:require_approval) ||
- handlers.size > 1
+ SiteSetting.approve_post_count > 0 || SiteSetting.approve_unless_trust_level.to_i > 0 ||
+ SiteSetting.approve_new_topics_unless_trust_level.to_i > 0 ||
+ SiteSetting.approve_unless_staged ||
+ WordWatcher.words_for_action_exists?(:require_approval) || handlers.size > 1
end
def initialize(user, args)
@@ -197,14 +212,15 @@ class NewPostManager
end
def perform
- if !self.class.exempt_user?(@user) && matches = WordWatcher.new("#{@args[:title]} #{@args[:raw]}").should_block?.presence
+ if !self.class.exempt_user?(@user) &&
+ matches = WordWatcher.new("#{@args[:title]} #{@args[:raw]}").should_block?.presence
result = NewPostResult.new(:created_post, false)
if matches.size == 1
- key = 'contains_blocked_word'
+ key = "contains_blocked_word"
translation_args = { word: CGI.escapeHTML(matches[0]) }
else
- key = 'contains_blocked_words'
- translation_args = { words: CGI.escapeHTML(matches.join(', ')) }
+ key = "contains_blocked_words"
+ translation_args = { words: CGI.escapeHTML(matches.join(", ")) }
end
result.errors.add(:base, I18n.t(key, translation_args))
return result
@@ -217,8 +233,13 @@ class NewPostManager
end
# We never queue private messages
- return perform_create_post if @args[:archetype] == Archetype.private_message ||
- (args[:topic_id] && Topic.where(id: args[:topic_id], archetype: Archetype.private_message).exists?)
+ if @args[:archetype] == Archetype.private_message ||
+ (
+ args[:topic_id] &&
+ Topic.where(id: args[:topic_id], archetype: Archetype.private_message).exists?
+ )
+ return perform_create_post
+ end
NewPostManager.default_handler(self) || perform_create_post
end
@@ -226,11 +247,8 @@ class NewPostManager
# Enqueue this post
def enqueue(reason = nil)
result = NewPostResult.new(:enqueued)
- payload = {
- raw: @args[:raw],
- tags: @args[:tags]
- }
- %w(typing_duration_msecs composer_open_duration_msecs reply_to_post_number).each do |a|
+ payload = { raw: @args[:raw], tags: @args[:tags] }
+ %w[typing_duration_msecs composer_open_duration_msecs reply_to_post_number].each do |a|
payload[a] = @args[a].to_i if @args[a]
end
@@ -239,21 +257,27 @@ class NewPostManager
payload[:via_email] = true if !!@args[:via_email]
payload[:raw_email] = @args[:raw_email] if @args[:raw_email].present?
- reviewable = ReviewableQueuedPost.new(
- created_by: @user,
- payload: payload,
- topic_id: @args[:topic_id],
- reviewable_by_moderator: true
- )
- reviewable.payload['title'] = @args[:title] if @args[:title].present?
+ reviewable =
+ ReviewableQueuedPost.new(
+ created_by: @user,
+ payload: payload,
+ topic_id: @args[:topic_id],
+ reviewable_by_moderator: true,
+ )
+ reviewable.payload["title"] = @args[:title] if @args[:title].present?
reviewable.category_id = args[:category] if args[:category].present?
reviewable.created_new!
create_options = reviewable.create_options
- creator = @args[:topic_id] ?
- PostCreator.new(@user, create_options) :
- TopicCreator.new(@user, Guardian.new(@user), create_options)
+ creator =
+ (
+ if @args[:topic_id]
+ PostCreator.new(@user, create_options)
+ else
+ TopicCreator.new(@user, Guardian.new(@user), create_options)
+ end
+ )
errors = Set.new
creator.valid?
@@ -265,7 +289,7 @@ class NewPostManager
Discourse.system_user,
ReviewableScore.types[:needs_approval],
reason: reason,
- force_review: true
+ force_review: true,
)
else
reviewable.errors.full_messages.each { |msg| errors << msg }
@@ -293,5 +317,4 @@ class NewPostManager
result
end
-
end
diff --git a/lib/new_post_result.rb b/lib/new_post_result.rb
index 4fa50b24863..861fcc5ff94 100644
--- a/lib/new_post_result.rb
+++ b/lib/new_post_result.rb
@@ -37,7 +37,7 @@ class NewPostResult
Discourse.deprecate(
"NewPostManager#queued_post is deprecated. Please use #reviewable instead.",
output_in_test: true,
- drop_from: '2.9.0',
+ drop_from: "2.9.0",
)
reviewable
@@ -50,5 +50,4 @@ class NewPostResult
def failed?
!@success
end
-
end
diff --git a/lib/notification_levels.rb b/lib/notification_levels.rb
index a9499506640..9b43e6be706 100644
--- a/lib/notification_levels.rb
+++ b/lib/notification_levels.rb
@@ -2,19 +2,25 @@
module NotificationLevels
def self.all
- @all_levels ||= Enum.new(muted: 0,
- regular: 1,
- normal: 1, # alias for regular
- tracking: 2,
- watching: 3,
- watching_first_post: 4)
+ @all_levels ||=
+ Enum.new(
+ muted: 0,
+ regular: 1,
+ normal: 1, # alias for regular
+ tracking: 2,
+ watching: 3,
+ watching_first_post: 4,
+ )
end
def self.topic_levels
- @topic_levels ||= Enum.new(muted: 0,
- regular: 1,
- normal: 1, # alias for regular
- tracking: 2,
- watching: 3)
+ @topic_levels ||=
+ Enum.new(
+ muted: 0,
+ regular: 1,
+ normal: 1, # alias for regular
+ tracking: 2,
+ watching: 3,
+ )
end
end
diff --git a/lib/onebox.rb b/lib/onebox.rb
index e6e0eed187a..feee7c8e6da 100644
--- a/lib/onebox.rb
+++ b/lib/onebox.rb
@@ -19,9 +19,9 @@ module Onebox
max_download_kb: (10 * 1024), # 10MB
load_paths: [File.join(Rails.root, "lib/onebox/templates")],
allowed_ports: [80, 443],
- allowed_schemes: ["http", "https"],
+ allowed_schemes: %w[http https],
sanitize_config: SanitizeConfig::ONEBOX,
- redirect_limit: 5
+ redirect_limit: 5,
}
@@options = DEFAULTS
diff --git a/lib/onebox/domain_checker.rb b/lib/onebox/domain_checker.rb
index 1dd810491e2..6e6c99c3e39 100644
--- a/lib/onebox/domain_checker.rb
+++ b/lib/onebox/domain_checker.rb
@@ -3,9 +3,10 @@
module Onebox
class DomainChecker
def self.is_blocked?(hostname)
- SiteSetting.blocked_onebox_domains&.split('|').any? do |blocked|
- hostname == blocked || hostname.end_with?(".#{blocked}")
- end
+ SiteSetting
+ .blocked_onebox_domains
+ &.split("|")
+ .any? { |blocked| hostname == blocked || hostname.end_with?(".#{blocked}") }
end
end
end
diff --git a/lib/onebox/engine.rb b/lib/onebox/engine.rb
index e28807c9889..838986e685b 100644
--- a/lib/onebox/engine.rb
+++ b/lib/onebox/engine.rb
@@ -7,9 +7,7 @@ module Onebox
end
def self.engines
- constants.select do |constant|
- constant.to_s =~ /Onebox$/
- end.sort.map(&method(:const_get))
+ constants.select { |constant| constant.to_s =~ /Onebox$/ }.sort.map(&method(:const_get))
end
def self.all_iframe_origins
@@ -25,7 +23,7 @@ module Onebox
escaped_origin = escaped_origin.sub("\\*", '\S*')
end
- Regexp.new("\\A#{escaped_origin}", 'i')
+ Regexp.new("\\A#{escaped_origin}", "i")
end
end
@@ -50,7 +48,7 @@ module Onebox
@url = url
@uri = URI(url)
if always_https?
- @uri.scheme = 'https'
+ @uri.scheme = "https"
@url = @uri.to_s
end
@timeout = timeout || Onebox.options.timeout
diff --git a/lib/onebox/engine/allowlisted_generic_onebox.rb b/lib/onebox/engine/allowlisted_generic_onebox.rb
index aa25dd54a6a..3c8a2359eba 100644
--- a/lib/onebox/engine/allowlisted_generic_onebox.rb
+++ b/lib/onebox/engine/allowlisted_generic_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'htmlentities'
+require "htmlentities"
require "ipaddr"
module Onebox
@@ -18,7 +18,7 @@ module Onebox
# include the entire page HTML. However for some providers like Flickr it allows us
# to return gifv and galleries.
def self.default_html_providers
- ['Flickr', 'Meetup']
+ %w[Flickr Meetup]
end
def self.html_providers
@@ -39,23 +39,33 @@ module Onebox
end
def self.https_hosts
- %w(slideshare.net dailymotion.com livestream.com imgur.com flickr.com)
+ %w[slideshare.net dailymotion.com livestream.com imgur.com flickr.com]
end
def self.article_html_hosts
- %w(imdb.com)
+ %w[imdb.com]
end
def self.host_matches(uri, list)
- !!list.find { |h| %r((^|\.)#{Regexp.escape(h)}$).match(uri.host) }
+ !!list.find { |h| /(^|\.)#{Regexp.escape(h)}$/.match(uri.host) }
end
def self.allowed_twitter_labels
- ['brand', 'price', 'usd', 'cad', 'reading time', 'likes']
+ ["brand", "price", "usd", "cad", "reading time", "likes"]
end
def self.===(other)
- other.is_a?(URI) ? (IPAddr.new(other.hostname) rescue nil).nil? : true
+ if other.is_a?(URI)
+ (
+ begin
+ IPAddr.new(other.hostname)
+ rescue StandardError
+ nil
+ end
+ ).nil?
+ else
+ true
+ end
end
def to_html
@@ -65,8 +75,12 @@ module Onebox
def placeholder_html
return article_html if (is_article? || force_article_html?)
return image_html if is_image?
- return Onebox::Helpers.video_placeholder_html if !SiteSetting.enable_diffhtml_preview? && (is_video? || is_card?)
- return Onebox::Helpers.generic_placeholder_html if !SiteSetting.enable_diffhtml_preview? && is_embedded?
+ if !SiteSetting.enable_diffhtml_preview? && (is_video? || is_card?)
+ return Onebox::Helpers.video_placeholder_html
+ end
+ if !SiteSetting.enable_diffhtml_preview? && is_embedded?
+ return Onebox::Helpers.generic_placeholder_html
+ end
to_html
end
@@ -75,72 +89,90 @@ module Onebox
end
def data
- @data ||= begin
- html_entities = HTMLEntities.new
- d = { link: link }.merge(raw)
-
- if !Onebox::Helpers.blank?(d[:title])
- d[:title] = html_entities.decode(Onebox::Helpers.truncate(d[:title], 80))
- end
+ @data ||=
+ begin
+ html_entities = HTMLEntities.new
+ d = { link: link }.merge(raw)
- d[:description] ||= d[:summary]
- if !Onebox::Helpers.blank?(d[:description])
- d[:description] = html_entities.decode(Onebox::Helpers.truncate(d[:description], 250))
- end
-
- if !Onebox::Helpers.blank?(d[:site_name])
- d[:domain] = html_entities.decode(Onebox::Helpers.truncate(d[:site_name], 80))
- elsif !Onebox::Helpers.blank?(d[:domain])
- d[:domain] = "http://#{d[:domain]}" unless d[:domain] =~ /^https?:\/\//
- d[:domain] = URI(d[:domain]).host.to_s.sub(/^www\./, '') rescue nil
- end
+ if !Onebox::Helpers.blank?(d[:title])
+ d[:title] = html_entities.decode(Onebox::Helpers.truncate(d[:title], 80))
+ end
- # prefer secure URLs
- d[:image] = d[:image_secure_url] || d[:image_url] || d[:thumbnail_url] || d[:image]
- d[:image] = Onebox::Helpers::get_absolute_image_url(d[:image], @url)
- d[:image] = Onebox::Helpers::normalize_url_for_output(html_entities.decode(d[:image]))
- d[:image] = nil if Onebox::Helpers.blank?(d[:image])
+ d[:description] ||= d[:summary]
+ if !Onebox::Helpers.blank?(d[:description])
+ d[:description] = html_entities.decode(Onebox::Helpers.truncate(d[:description], 250))
+ end
- d[:video] = d[:video_secure_url] || d[:video_url] || d[:video]
- d[:video] = nil if Onebox::Helpers.blank?(d[:video])
+ if !Onebox::Helpers.blank?(d[:site_name])
+ d[:domain] = html_entities.decode(Onebox::Helpers.truncate(d[:site_name], 80))
+ elsif !Onebox::Helpers.blank?(d[:domain])
+ d[:domain] = "http://#{d[:domain]}" unless d[:domain] =~ %r{^https?://}
+ d[:domain] = begin
+ URI(d[:domain]).host.to_s.sub(/^www\./, "")
+ rescue StandardError
+ nil
+ end
+ end
- d[:published_time] = d[:article_published_time] unless Onebox::Helpers.blank?(d[:article_published_time])
- if !Onebox::Helpers.blank?(d[:published_time])
- d[:article_published_time] = Time.parse(d[:published_time]).strftime("%-d %b %y")
- d[:article_published_time_title] = Time.parse(d[:published_time]).strftime("%I:%M%p - %d %B %Y")
- end
+ # prefer secure URLs
+ d[:image] = d[:image_secure_url] || d[:image_url] || d[:thumbnail_url] || d[:image]
+ d[:image] = Onebox::Helpers.get_absolute_image_url(d[:image], @url)
+ d[:image] = Onebox::Helpers.normalize_url_for_output(html_entities.decode(d[:image]))
+ d[:image] = nil if Onebox::Helpers.blank?(d[:image])
+
+ d[:video] = d[:video_secure_url] || d[:video_url] || d[:video]
+ d[:video] = nil if Onebox::Helpers.blank?(d[:video])
+
+ d[:published_time] = d[:article_published_time] unless Onebox::Helpers.blank?(
+ d[:article_published_time],
+ )
+ if !Onebox::Helpers.blank?(d[:published_time])
+ d[:article_published_time] = Time.parse(d[:published_time]).strftime("%-d %b %y")
+ d[:article_published_time_title] = Time.parse(d[:published_time]).strftime(
+ "%I:%M%p - %d %B %Y",
+ )
+ end
- # Twitter labels
- if !Onebox::Helpers.blank?(d[:label1]) && !Onebox::Helpers.blank?(d[:data1]) && !!AllowlistedGenericOnebox.allowed_twitter_labels.find { |l| d[:label1] =~ /#{l}/i }
- d[:label_1] = Onebox::Helpers.truncate(d[:label1])
- d[:data_1] = Onebox::Helpers.truncate(d[:data1])
- end
- if !Onebox::Helpers.blank?(d[:label2]) && !Onebox::Helpers.blank?(d[:data2]) && !!AllowlistedGenericOnebox.allowed_twitter_labels.find { |l| d[:label2] =~ /#{l}/i }
- unless Onebox::Helpers.blank?(d[:label_1])
- d[:label_2] = Onebox::Helpers.truncate(d[:label2])
- d[:data_2] = Onebox::Helpers.truncate(d[:data2])
- else
- d[:label_1] = Onebox::Helpers.truncate(d[:label2])
- d[:data_1] = Onebox::Helpers.truncate(d[:data2])
+ # Twitter labels
+ if !Onebox::Helpers.blank?(d[:label1]) && !Onebox::Helpers.blank?(d[:data1]) &&
+ !!AllowlistedGenericOnebox.allowed_twitter_labels.find { |l|
+ d[:label1] =~ /#{l}/i
+ }
+ d[:label_1] = Onebox::Helpers.truncate(d[:label1])
+ d[:data_1] = Onebox::Helpers.truncate(d[:data1])
+ end
+ if !Onebox::Helpers.blank?(d[:label2]) && !Onebox::Helpers.blank?(d[:data2]) &&
+ !!AllowlistedGenericOnebox.allowed_twitter_labels.find { |l|
+ d[:label2] =~ /#{l}/i
+ }
+ unless Onebox::Helpers.blank?(d[:label_1])
+ d[:label_2] = Onebox::Helpers.truncate(d[:label2])
+ d[:data_2] = Onebox::Helpers.truncate(d[:data2])
+ else
+ d[:label_1] = Onebox::Helpers.truncate(d[:label2])
+ d[:data_1] = Onebox::Helpers.truncate(d[:data2])
+ end
end
- end
- if Onebox::Helpers.blank?(d[:label_1]) && !Onebox::Helpers.blank?(d[:price_amount]) && !Onebox::Helpers.blank?(d[:price_currency])
- d[:label_1] = "Price"
- d[:data_1] = Onebox::Helpers.truncate("#{d[:price_currency].strip} #{d[:price_amount].strip}")
- end
+ if Onebox::Helpers.blank?(d[:label_1]) && !Onebox::Helpers.blank?(d[:price_amount]) &&
+ !Onebox::Helpers.blank?(d[:price_currency])
+ d[:label_1] = "Price"
+ d[:data_1] = Onebox::Helpers.truncate(
+ "#{d[:price_currency].strip} #{d[:price_amount].strip}",
+ )
+ end
- skip_missing_tags = [:video]
- d.each do |k, v|
- next if skip_missing_tags.include?(k)
- if v == nil || v == ''
- errors[k] ||= []
- errors[k] << 'is blank'
+ skip_missing_tags = [:video]
+ d.each do |k, v|
+ next if skip_missing_tags.include?(k)
+ if v == nil || v == ""
+ errors[k] ||= []
+ errors[k] << "is blank"
+ end
end
- end
- d
- end
+ d
+ end
end
private
@@ -154,23 +186,21 @@ module Onebox
end
def generic_html
- return article_html if (is_article? || force_article_html?)
- return video_html if is_video?
- return image_html if is_image?
+ return article_html if (is_article? || force_article_html?)
+ return video_html if is_video?
+ return image_html if is_image?
return embedded_html if is_embedded?
- return card_html if is_card?
- return article_html if (has_text? || is_image_article?)
+ return card_html if is_card?
+ return article_html if (has_text? || is_image_article?)
end
def is_card?
- data[:card] == 'player' &&
- data[:player] =~ URI::regexp &&
+ data[:card] == "player" && data[:player] =~ URI.regexp &&
options[:allowed_iframe_regexes]&.any? { |r| data[:player] =~ r }
end
def is_article?
- (data[:type] =~ /article/ || data[:asset_type] =~ /article/) &&
- has_text?
+ (data[:type] =~ /article/ || data[:asset_type] =~ /article/) && has_text?
end
def has_text?
@@ -186,9 +216,7 @@ module Onebox
end
def is_image?
- data[:type] =~ /photo|image/ &&
- data[:type] !~ /photostream/ &&
- has_image?
+ data[:type] =~ /photo|image/ && data[:type] !~ /photostream/ && has_image?
end
def has_image?
@@ -196,8 +224,7 @@ module Onebox
end
def is_video?
- data[:type] =~ /^video[\/\.]/ &&
- data[:video_type] == "video/mp4" && # Many sites include 'videos' with text/html types (i.e. iframes)
+ data[:type] =~ %r{^video[/\.]} && data[:video_type] == "video/mp4" && # Many sites include 'videos' with text/html types (i.e. iframes)
!Onebox::Helpers.blank?(data[:video])
end
@@ -206,13 +233,14 @@ module Onebox
return true if AllowlistedGenericOnebox.html_providers.include?(data[:provider_name])
return false unless data[:html]["iframe"]
- fragment = Nokogiri::HTML5::fragment(data[:html])
- src = fragment.at_css('iframe')&.[]("src")
+ fragment = Nokogiri::HTML5.fragment(data[:html])
+ src = fragment.at_css("iframe")&.[]("src")
options[:allowed_iframe_regexes]&.any? { |r| src =~ r }
end
def force_article_html?
- AllowlistedGenericOnebox.host_matches(uri, AllowlistedGenericOnebox.article_html_hosts) && (has_text? || is_image_article?)
+ AllowlistedGenericOnebox.host_matches(uri, AllowlistedGenericOnebox.article_html_hosts) &&
+ (has_text? || is_image_article?)
end
def card_html
@@ -237,8 +265,8 @@ module Onebox
escaped_src = ::Onebox::Helpers.normalize_url_for_output(data[:image])
- alt = data[:description] || data[:title]
- width = data[:image_width] || data[:thumbnail_width] || data[:width]
+ alt = data[:description] || data[:title]
+ width = data[:image_width] || data[:thumbnail_width] || data[:width]
height = data[:image_height] || data[:thumbnail_height] || data[:height]
"<img src='#{escaped_src}' alt='#{alt}' width='#{width}' height='#{height}' class='onebox'>"
@@ -263,7 +291,7 @@ module Onebox
end
def embedded_html
- fragment = Nokogiri::HTML5::fragment(data[:html])
+ fragment = Nokogiri::HTML5.fragment(data[:html])
fragment.css("img").each { |img| img["class"] = "thumbnail" }
if iframe = fragment.at_css("iframe")
iframe.remove_attribute("style")
diff --git a/lib/onebox/engine/amazon_onebox.rb b/lib/onebox/engine/amazon_onebox.rb
index 9f1aca9f833..ae3ae9e36f5 100644
--- a/lib/onebox/engine/amazon_onebox.rb
+++ b/lib/onebox/engine/amazon_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'json'
+require "json"
require "onebox/open_graph"
module Onebox
@@ -11,7 +11,9 @@ module Onebox
include HTML
always_https
- matches_regexp(/^https?:\/\/(?:www\.)?(?:smile\.)?(amazon|amzn)\.(?<tld>com|ca|de|it|es|fr|co\.jp|co\.uk|cn|in|com\.br|com\.mx|nl|pl|sa|sg|se|com\.tr|ae)\//)
+ matches_regexp(
+ %r{^https?://(?:www\.)?(?:smile\.)?(amazon|amzn)\.(?<tld>com|ca|de|it|es|fr|co\.jp|co\.uk|cn|in|com\.br|com\.mx|nl|pl|sa|sg|se|com\.tr|ae)/},
+ )
def url
@raw ||= nil
@@ -29,7 +31,8 @@ module Onebox
end
if match && match[:id]
- id = Addressable::URI.encode_component(match[:id], Addressable::URI::CharacterClasses::PATH)
+ id =
+ Addressable::URI.encode_component(match[:id], Addressable::URI::CharacterClasses::PATH)
return "https://www.amazon.#{tld}/dp/#{id}"
end
@@ -41,15 +44,13 @@ module Onebox
end
def http_params
- if @options && @options[:user_agent]
- { 'User-Agent' => @options[:user_agent] }
- end
+ { "User-Agent" => @options[:user_agent] } if @options && @options[:user_agent]
end
def to_html(ignore_errors = false)
unless ignore_errors
verified_data # forces a check for missing fields
- return '' unless errors.empty?
+ return "" unless errors.empty?
end
super()
@@ -60,19 +61,20 @@ module Onebox
end
def verified_data
- @verified_data ||= begin
- result = data
-
- required_tags = [:title, :description]
- required_tags.each do |tag|
- if result[tag].blank?
- errors[tag] ||= []
- errors[tag] << 'is blank'
+ @verified_data ||=
+ begin
+ result = data
+
+ required_tags = %i[title description]
+ required_tags.each do |tag|
+ if result[tag].blank?
+ errors[tag] ||= []
+ errors[tag] << "is blank"
+ end
end
- end
- result
- end
+ result
+ end
@verified_data
end
@@ -80,13 +82,13 @@ module Onebox
private
def has_cached_body
- body_cacher&.respond_to?('cache_response_body?') &&
+ body_cacher&.respond_to?("cache_response_body?") &&
body_cacher.cache_response_body?(uri.to_s) &&
body_cacher.cached_response_body_exists?(uri.to_s)
end
def match
- @match ||= @url.match(/(?:d|g)p\/(?:product\/|video\/detail\/)?(?<id>[A-Z0-9]+)(?:\/|\?|$)/mi)
+ @match ||= @url.match(%r{(?:d|g)p/(?:product/|video/detail/)?(?<id>[A-Z0-9]+)(?:/|\?|$)}mi)
end
def image
@@ -117,14 +119,16 @@ module Onebox
def price
# get item price (Amazon markup is inconsistent, deal with it)
- if raw.css("#priceblock_ourprice .restOfPrice")[0] && raw.css("#priceblock_ourprice .restOfPrice")[0].inner_text
+ if raw.css("#priceblock_ourprice .restOfPrice")[0] &&
+ raw.css("#priceblock_ourprice .restOfPrice")[0].inner_text
"#{raw.css("#priceblock_ourprice .restOfPrice")[0].inner_text}#{raw.css("#priceblock_ourprice .buyingPrice")[0].inner_text}.#{raw.css("#priceblock_ourprice .restOfPrice")[1].inner_text}"
- elsif raw.css("#priceblock_dealprice") && (dealprice = raw.css("#priceblock_dealprice span")[0])
+ elsif raw.css("#priceblock_dealprice") &&
+ (dealprice = raw.css("#priceblock_dealprice span")[0])
dealprice.inner_text
elsif !raw.css("#priceblock_ourprice").inner_text.empty?
raw.css("#priceblock_ourprice").inner_text
else
- result = raw.css('#corePrice_feature_div .a-price .a-offscreen').first&.inner_text
+ result = raw.css("#corePrice_feature_div .a-price .a-offscreen").first&.inner_text
if result.blank?
result = raw.css(".mediaMatrixListItem.a-active .a-color-price").inner_text
end
@@ -134,21 +138,30 @@ module Onebox
end
def multiple_authors(authors_xpath)
- raw
- .xpath(authors_xpath)
- .map { |a| a.inner_text.strip }
- .join(", ")
+ raw.xpath(authors_xpath).map { |a| a.inner_text.strip }.join(", ")
end
def data
og = ::Onebox::OpenGraph.new(raw)
- if raw.at_css('#dp.book_mobile') # printed books
+ if raw.at_css("#dp.book_mobile") # printed books
title = raw.at("h1#title")&.inner_text
- authors = raw.at_css('#byline_secondary_view_div') ? multiple_authors("//div[@id='byline_secondary_view_div']//span[@class='a-text-bold']") : raw.at("#byline")&.inner_text
- rating = raw.at("#averageCustomerReviews_feature_div .a-icon")&.inner_text || raw.at("#cmrsArcLink .a-icon")&.inner_text
-
- table_xpath = "//div[@id='productDetails_secondary_view_div']//table[@id='productDetails_techSpec_section_1']"
+ authors =
+ (
+ if raw.at_css("#byline_secondary_view_div")
+ multiple_authors(
+ "//div[@id='byline_secondary_view_div']//span[@class='a-text-bold']",
+ )
+ else
+ raw.at("#byline")&.inner_text
+ end
+ )
+ rating =
+ raw.at("#averageCustomerReviews_feature_div .a-icon")&.inner_text ||
+ raw.at("#cmrsArcLink .a-icon")&.inner_text
+
+ table_xpath =
+ "//div[@id='productDetails_secondary_view_div']//table[@id='productDetails_techSpec_section_1']"
isbn = raw.xpath("#{table_xpath}//tr[8]//td").inner_text.strip
# if ISBN is misplaced or absent it's hard to find out which data is
@@ -167,18 +180,29 @@ module Onebox
by_info: authors,
image: og.image || image,
description: raw.at("#productDescription")&.inner_text,
- rating: "#{rating}#{', ' if rating && (!isbn&.empty? || !price&.empty?)}",
+ rating: "#{rating}#{", " if rating && (!isbn&.empty? || !price&.empty?)}",
price: price,
isbn_asin_text: "ISBN",
isbn_asin: isbn,
publisher: publisher,
- published: "#{published}#{', ' if published && !price&.empty?}"
+ published: "#{published}#{", " if published && !price&.empty?}",
}
-
- elsif raw.at_css('#dp.ebooks_mobile') # ebooks
+ elsif raw.at_css("#dp.ebooks_mobile") # ebooks
title = raw.at("#ebooksTitle")&.inner_text
- authors = raw.at_css('#a-popover-mobile-udp-contributor-popover-id') ? multiple_authors("//div[@id='a-popover-mobile-udp-contributor-popover-id']//span[contains(@class,'a-text-bold')]") : (raw.at("#byline")&.inner_text&.strip || raw.at("#bylineInfo")&.inner_text&.strip)
- rating = raw.at("#averageCustomerReviews_feature_div .a-icon")&.inner_text || raw.at("#cmrsArcLink .a-icon")&.inner_text || raw.at("#acrCustomerReviewLink .a-icon")&.inner_text
+ authors =
+ (
+ if raw.at_css("#a-popover-mobile-udp-contributor-popover-id")
+ multiple_authors(
+ "//div[@id='a-popover-mobile-udp-contributor-popover-id']//span[contains(@class,'a-text-bold')]",
+ )
+ else
+ (raw.at("#byline")&.inner_text&.strip || raw.at("#bylineInfo")&.inner_text&.strip)
+ end
+ )
+ rating =
+ raw.at("#averageCustomerReviews_feature_div .a-icon")&.inner_text ||
+ raw.at("#cmrsArcLink .a-icon")&.inner_text ||
+ raw.at("#acrCustomerReviewLink .a-icon")&.inner_text
table_xpath = "//div[@id='detailBullets_secondary_view_div']//ul"
asin = raw.xpath("#{table_xpath}//li[4]/span/span[2]").inner_text
@@ -198,22 +222,16 @@ module Onebox
by_info: authors,
image: og.image || image,
description: raw.at("#productDescription")&.inner_text,
- rating: "#{rating}#{', ' if rating && (!asin&.empty? || !price&.empty?)}",
+ rating: "#{rating}#{", " if rating && (!asin&.empty? || !price&.empty?)}",
price: price,
isbn_asin_text: "ASIN",
isbn_asin: asin,
publisher: publisher,
- published: "#{published}#{', ' if published && !price&.empty?}"
+ published: "#{published}#{", " if published && !price&.empty?}",
}
-
else
title = og.title || CGI.unescapeHTML(raw.css("title").inner_text)
- result = {
- link: url,
- title: title,
- image: og.image || image,
- price: price
- }
+ result = { link: url, title: title, image: og.image || image, price: price }
result[:by_info] = raw.at("#by-line")
result[:by_info] = Onebox::Helpers.clean(result[:by_info].inner_html) if result[:by_info]
@@ -221,10 +239,10 @@ module Onebox
summary = raw.at("#productDescription")
description = og.description || summary&.inner_text&.strip
- if description.blank?
- description = raw.css("meta[name=description]").first&.[]("content")
- end
- result[:description] = CGI.unescapeHTML(Onebox::Helpers.truncate(description, 250)) if description
+ description = raw.css("meta[name=description]").first&.[]("content") if description.blank?
+ result[:description] = CGI.unescapeHTML(
+ Onebox::Helpers.truncate(description, 250),
+ ) if description
end
result[:price] = nil if result[:price].start_with?("$0") || result[:price] == 0
diff --git a/lib/onebox/engine/animated_image_onebox.rb b/lib/onebox/engine/animated_image_onebox.rb
index 9dc8a5f4846..a960ac5e619 100644
--- a/lib/onebox/engine/animated_image_onebox.rb
+++ b/lib/onebox/engine/animated_image_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/.*(giphy\.com|gph\.is|tenor\.com)\//)
+ matches_regexp(%r{^https?://.*(giphy\.com|gph\.is|tenor\.com)/})
always_https
def to_html
diff --git a/lib/onebox/engine/audio_onebox.rb b/lib/onebox/engine/audio_onebox.rb
index 8a5f52c4b08..8a41b100dd7 100644
--- a/lib/onebox/engine/audio_onebox.rb
+++ b/lib/onebox/engine/audio_onebox.rb
@@ -5,7 +5,7 @@ module Onebox
class AudioOnebox
include Engine
- matches_regexp(/^(https?:)?\/\/.*\.(mp3|ogg|opus|wav|m4a)(\?.*)?$/i)
+ matches_regexp(%r{^(https?:)?//.*\.(mp3|ogg|opus|wav|m4a)(\?.*)?$}i)
def always_https?
AllowlistedGenericOnebox.host_matches(uri, AllowlistedGenericOnebox.https_hosts)
diff --git a/lib/onebox/engine/audioboom_onebox.rb b/lib/onebox/engine/audioboom_onebox.rb
index 89986f46857..daf26f6a831 100644
--- a/lib/onebox/engine/audioboom_onebox.rb
+++ b/lib/onebox/engine/audioboom_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/audioboom\.com\/posts\/\d+/)
+ matches_regexp(%r{^https?://audioboom\.com/posts/\d+})
always_https
def placeholder_html
diff --git a/lib/onebox/engine/band_camp_onebox.rb b/lib/onebox/engine/band_camp_onebox.rb
index a31e5890322..937826ce9ea 100644
--- a/lib/onebox/engine/band_camp_onebox.rb
+++ b/lib/onebox/engine/band_camp_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/.*\.bandcamp\.com\/(album|track)\//)
+ matches_regexp(%r{^https?://.*\.bandcamp\.com/(album|track)/})
always_https
requires_iframe_origins "https://bandcamp.com"
diff --git a/lib/onebox/engine/cloud_app_onebox.rb b/lib/onebox/engine/cloud_app_onebox.rb
index f1b985edf7c..2c076381411 100644
--- a/lib/onebox/engine/cloud_app_onebox.rb
+++ b/lib/onebox/engine/cloud_app_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/cl\.ly/)
+ matches_regexp(%r{^https?://cl\.ly})
always_https
def to_html
diff --git a/lib/onebox/engine/coub_onebox.rb b/lib/onebox/engine/coub_onebox.rb
index 7e57e454296..5cac6c5dbac 100644
--- a/lib/onebox/engine/coub_onebox.rb
+++ b/lib/onebox/engine/coub_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/coub\.com\/view\//)
+ matches_regexp(%r{^https?://coub\.com/view/})
always_https
def placeholder_html
diff --git a/lib/onebox/engine/facebook_media_onebox.rb b/lib/onebox/engine/facebook_media_onebox.rb
index 903eccb131a..cdf4d699ff3 100644
--- a/lib/onebox/engine/facebook_media_onebox.rb
+++ b/lib/onebox/engine/facebook_media_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/.*\.facebook\.com\/(\w+)\/(videos|\?).*/)
+ matches_regexp(%r{^https?://.*\.facebook\.com/(\w+)/(videos|\?).*})
always_https
requires_iframe_origins "https://www.facebook.com"
diff --git a/lib/onebox/engine/five_hundred_px_onebox.rb b/lib/onebox/engine/five_hundred_px_onebox.rb
index 806b5f9e6af..d2aab48eaf9 100644
--- a/lib/onebox/engine/five_hundred_px_onebox.rb
+++ b/lib/onebox/engine/five_hundred_px_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/500px\.com\/photo\/\d+\//)
+ matches_regexp(%r{^https?://500px\.com/photo/\d+/})
always_https
def to_html
diff --git a/lib/onebox/engine/flickr_onebox.rb b/lib/onebox/engine/flickr_onebox.rb
index 3ed26684a76..435a53e027f 100644
--- a/lib/onebox/engine/flickr_onebox.rb
+++ b/lib/onebox/engine/flickr_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative './opengraph_image'
+require_relative "./opengraph_image"
module Onebox
module Engine
@@ -8,12 +8,12 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/www\.flickr\.com\/photos\//)
+ matches_regexp(%r{^https?://www\.flickr\.com/photos/})
always_https
def to_html
og = get_opengraph
- return album_html(og) if og.url =~ /\/sets\//
+ return album_html(og) if og.url =~ %r{/sets/}
return image_html(og) if !og.image.nil?
nil
end
diff --git a/lib/onebox/engine/flickr_shortened_onebox.rb b/lib/onebox/engine/flickr_shortened_onebox.rb
index 1c1243050bc..0a6baf1360c 100644
--- a/lib/onebox/engine/flickr_shortened_onebox.rb
+++ b/lib/onebox/engine/flickr_shortened_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative './opengraph_image'
+require_relative "./opengraph_image"
module Onebox
module Engine
@@ -9,7 +9,7 @@ module Onebox
include StandardEmbed
include OpengraphImage
- matches_regexp(/^https?:\/\/flic\.kr\/p\//)
+ matches_regexp(%r{^https?://flic\.kr/p/})
always_https
end
end
diff --git a/lib/onebox/engine/gfycat_onebox.rb b/lib/onebox/engine/gfycat_onebox.rb
index 27fd4bf79e0..44ca947f66f 100644
--- a/lib/onebox/engine/gfycat_onebox.rb
+++ b/lib/onebox/engine/gfycat_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include JSON
- matches_regexp(/^https?:\/\/gfycat\.com\//)
+ matches_regexp(%r{^https?://gfycat\.com/})
always_https
# This engine should have priority over AllowlistedGenericOnebox.
@@ -60,14 +60,19 @@ module Onebox
private
def match
- @match ||= @url.match(/^https?:\/\/gfycat\.com\/(gifs\/detail\/)?(?<name>.+)/)
+ @match ||= @url.match(%r{^https?://gfycat\.com/(gifs/detail/)?(?<name>.+)})
end
def og_data
return @og_data if defined?(@og_data)
- response = Onebox::Helpers.fetch_response(url, redirect_limit: 10) rescue nil
- page = Nokogiri::HTML(response)
+ response =
+ begin
+ Onebox::Helpers.fetch_response(url, redirect_limit: 10)
+ rescue StandardError
+ nil
+ end
+ page = Nokogiri.HTML(response)
script = page.at_css('script[type="application/ld+json"]')
if json_string = script&.text
@@ -82,15 +87,15 @@ module Onebox
@data = {
name: match[:name],
- title: og_data[:headline] || 'No Title',
+ title: og_data[:headline] || "No Title",
author: og_data[:author],
url: @url,
}
- if keywords = og_data[:keywords]&.split(',')
+ if keywords = og_data[:keywords]&.split(",")
@data[:keywords] = keywords
.map { |keyword| "<a href='https://gfycat.com/gifs/search/#{keyword}'>##{keyword}</a>" }
- .join(' ')
+ .join(" ")
end
if og_data[:video]
diff --git a/lib/onebox/engine/github_actions_onebox.rb b/lib/onebox/engine/github_actions_onebox.rb
index 182fff49d58..6630fefa4df 100644
--- a/lib/onebox/engine/github_actions_onebox.rb
+++ b/lib/onebox/engine/github_actions_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative '../mixins/github_body'
+require_relative "../mixins/github_body"
module Onebox
module Engine
@@ -9,7 +9,9 @@ module Onebox
include LayoutSupport
include JSON
- matches_regexp(/^https?:\/\/(?:www\.)?(?:(?:\w)+\.)?github\.com\/(?<org>.+)\/(?<repo>.+)\/(actions\/runs\/[[:digit:]]+|pull\/[[:digit:]]*\/checks\?check_run_id=[[:digit:]]+)/)
+ matches_regexp(
+ %r{^https?://(?:www\.)?(?:(?:\w)+\.)?github\.com/(?<org>.+)/(?<repo>.+)/(actions/runs/[[:digit:]]+|pull/[[:digit:]]*/checks\?check_run_id=[[:digit:]]+)},
+ )
always_https
def url
@@ -29,12 +31,18 @@ module Onebox
def match_url
return if defined?(@match) && defined?(@type)
- if match = @url.match(/^https?:\/\/(?:www\.)?(?:(?:\w)+\.)?github\.com\/(?<org>.+)\/(?<repo>.+)\/actions\/runs\/(?<run_id>[[:digit:]]+)/)
+ if match =
+ @url.match(
+ %r{^https?://(?:www\.)?(?:(?:\w)+\.)?github\.com/(?<org>.+)/(?<repo>.+)/actions/runs/(?<run_id>[[:digit:]]+)},
+ )
@match = match
@type = :actions_run
end
- if match = @url.match(/^https?:\/\/(?:www\.)?(?:(?:\w)+\.)?github\.com\/(?<org>.+)\/(?<repo>.+)\/pull\/(?<pr_id>[[:digit:]]*)\/checks\?check_run_id=(?<check_run_id>[[:digit:]]+)/)
+ if match =
+ @url.match(
+ %r{^https?://(?:www\.)?(?:(?:\w)+\.)?github\.com/(?<org>.+)/(?<repo>.+)/pull/(?<pr_id>[[:digit:]]*)/checks\?check_run_id=(?<check_run_id>[[:digit:]]+)},
+ )
@match = match
@type = :pr_run
end
@@ -67,18 +75,20 @@ module Onebox
status = "pending"
end
- title = if type == :actions_run
- raw["head_commit"]["message"].lines.first
- elsif type == :pr_run
- pr_url = "https://api.github.com/repos/#{match[:org]}/#{match[:repo]}/pulls/#{match[:pr_id]}"
- ::MultiJson.load(URI.parse(pr_url).open(read_timeout: timeout))["title"]
- end
+ title =
+ if type == :actions_run
+ raw["head_commit"]["message"].lines.first
+ elsif type == :pr_run
+ pr_url =
+ "https://api.github.com/repos/#{match[:org]}/#{match[:repo]}/pulls/#{match[:pr_id]}"
+ ::MultiJson.load(URI.parse(pr_url).open(read_timeout: timeout))["title"]
+ end
{
- link: @url,
- title: title,
- name: raw["name"],
- run_number: raw["run_number"],
+ :link => @url,
+ :title => title,
+ :name => raw["name"],
+ :run_number => raw["run_number"],
status => true,
}
end
diff --git a/lib/onebox/engine/github_blob_onebox.rb b/lib/onebox/engine/github_blob_onebox.rb
index fd70a4b2af1..48a7e6dec05 100644
--- a/lib/onebox/engine/github_blob_onebox.rb
+++ b/lib/onebox/engine/github_blob_onebox.rb
@@ -1,12 +1,12 @@
# frozen_string_literal: true
-require_relative '../mixins/git_blob_onebox'
+require_relative "../mixins/git_blob_onebox"
module Onebox
module Engine
class GithubBlobOnebox
def self.git_regexp
- /^https?:\/\/(www\.)?github\.com.*\/blob\//
+ %r{^https?://(www\.)?github\.com.*/blob/}
end
def self.onebox_name
@@ -16,7 +16,7 @@ module Onebox
include Onebox::Mixins::GitBlobOnebox
def raw_regexp
- /github\.com\/(?<user>[^\/]+)\/(?<repo>[^\/]+)\/blob\/(?<sha1>[^\/]+)\/(?<file>[^#]+)(#(L(?<from>[^-]*)(-L(?<to>.*))?))?/mi
+ %r{github\.com/(?<user>[^/]+)/(?<repo>[^/]+)/blob/(?<sha1>[^/]+)/(?<file>[^#]+)(#(L(?<from>[^-]*)(-L(?<to>.*))?))?}mi
end
def raw_template(m)
@@ -24,7 +24,7 @@ module Onebox
end
def title
- Sanitize.fragment(Onebox::Helpers.uri_unencode(link).sub(/^https?\:\/\/github\.com\//, ''))
+ Sanitize.fragment(Onebox::Helpers.uri_unencode(link).sub(%r{^https?\://github\.com/}, ""))
end
end
end
diff --git a/lib/onebox/engine/github_commit_onebox.rb b/lib/onebox/engine/github_commit_onebox.rb
index d1820faa4bb..e1fa68547ed 100644
--- a/lib/onebox/engine/github_commit_onebox.rb
+++ b/lib/onebox/engine/github_commit_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative '../mixins/github_body'
+require_relative "../mixins/github_body"
module Onebox
module Engine
@@ -10,7 +10,7 @@ module Onebox
include JSON
include Onebox::Mixins::GithubBody
- matches_regexp(/^https?:\/\/(?:www\.)?(?:(?:\w)+\.)?(github)\.com(?:\/)?(?:.)*\/commit\//)
+ matches_regexp(%r{^https?://(?:www\.)?(?:(?:\w)+\.)?(github)\.com(?:/)?(?:.)*/commit/})
always_https
def url
@@ -22,8 +22,12 @@ module Onebox
def match
return @match if defined?(@match)
- @match = @url.match(%{github\.com/(?<owner>[^/]+)/(?<repository>[^/]+)/commit/(?<sha>[^/]+)})
- @match ||= @url.match(%{github\.com/(?<owner>[^/]+)/(?<repository>[^/]+)/pull/(?<pr>[^/]+)/commit/(?<sha>[^/]+)})
+ @match =
+ @url.match(%{github\.com/(?<owner>[^/]+)/(?<repository>[^/]+)/commit/(?<sha>[^/]+)})
+ @match ||=
+ @url.match(
+ %{github\.com/(?<owner>[^/]+)/(?<repository>[^/]+)/pull/(?<pr>[^/]+)/commit/(?<sha>[^/]+)},
+ )
@match
end
@@ -31,18 +35,18 @@ module Onebox
def data
result = raw.clone
- lines = result['commit']['message'].split("\n")
- result['title'] = lines.first
- result['body'], result['excerpt'] = compute_body(lines[1..lines.length].join("\n"))
+ lines = result["commit"]["message"].split("\n")
+ result["title"] = lines.first
+ result["body"], result["excerpt"] = compute_body(lines[1..lines.length].join("\n"))
- committed_at = Time.parse(result['commit']['committer']['date'])
- result['committed_at'] = committed_at.strftime("%I:%M%p - %d %b %y %Z")
- result['committed_at_date'] = committed_at.strftime("%F")
- result['committed_at_time'] = committed_at.strftime("%T")
+ committed_at = Time.parse(result["commit"]["committer"]["date"])
+ result["committed_at"] = committed_at.strftime("%I:%M%p - %d %b %y %Z")
+ result["committed_at_date"] = committed_at.strftime("%F")
+ result["committed_at_time"] = committed_at.strftime("%T")
- result['link'] = link
+ result["link"] = link
ulink = URI(link)
- result['domain'] = "#{ulink.host}/#{ulink.path.split('/')[1]}/#{ulink.path.split('/')[2]}"
+ result["domain"] = "#{ulink.host}/#{ulink.path.split("/")[1]}/#{ulink.path.split("/")[2]}"
result
end
diff --git a/lib/onebox/engine/github_folder_onebox.rb b/lib/onebox/engine/github_folder_onebox.rb
index aae75888be0..d77a27ca749 100644
--- a/lib/onebox/engine/github_folder_onebox.rb
+++ b/lib/onebox/engine/github_folder_onebox.rb
@@ -28,7 +28,7 @@ module Onebox
# For links to markdown and rdoc
if html_doc.css(".Box.md, .Box.rdoc").present?
- node = html_doc.css('a.anchor').find { |n| n['href'] == "##{fragment}" }
+ node = html_doc.css("a.anchor").find { |n| n["href"] == "##{fragment}" }
subtitle = node&.parent&.text
end
@@ -40,12 +40,12 @@ module Onebox
title: Onebox::Helpers.truncate(title, 250),
path: display_path,
description: display_description,
- favicon: get_favicon
+ favicon: get_favicon,
}
end
def extract_path(root, max_length)
- path = url.split('#')[0].split('?')[0]
+ path = url.split("#")[0].split("?")[0]
path = path["#{root}/tree/".length..-1]
return unless path
diff --git a/lib/onebox/engine/github_gist_onebox.rb b/lib/onebox/engine/github_gist_onebox.rb
index 21561d85ffb..ad579428d25 100644
--- a/lib/onebox/engine/github_gist_onebox.rb
+++ b/lib/onebox/engine/github_gist_onebox.rb
@@ -9,7 +9,7 @@ module Onebox
MAX_FILES = 3
- matches_regexp(/^http(?:s)?:\/\/gist\.(?:(?:\w)+\.)?(github)\.com(?:\/)?/)
+ matches_regexp(%r{^http(?:s)?://gist\.(?:(?:\w)+\.)?(github)\.com(?:/)?})
always_https
def url
@@ -20,10 +20,10 @@ module Onebox
def data
@data ||= {
- title: 'gist.github.com',
+ title: "gist.github.com",
link: link,
gist_files: gist_files.take(MAX_FILES),
- truncated_files?: truncated_files?
+ truncated_files?: truncated_files?,
}
end
@@ -34,9 +34,7 @@ module Onebox
def gist_files
return [] unless gist_api
- @gist_files ||= gist_api["files"].values.map do |file_json|
- GistFile.new(file_json)
- end
+ @gist_files ||= gist_api["files"].values.map { |file_json| GistFile.new(file_json) }
end
def gist_api
diff --git a/lib/onebox/engine/github_issue_onebox.rb b/lib/onebox/engine/github_issue_onebox.rb
index 4d387f47995..510fc0ca3e2 100644
--- a/lib/onebox/engine/github_issue_onebox.rb
+++ b/lib/onebox/engine/github_issue_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative '../mixins/github_body'
+require_relative "../mixins/github_body"
module Onebox
module Engine
@@ -11,7 +11,9 @@ module Onebox
include JSON
include Onebox::Mixins::GithubBody
- matches_regexp(/^https?:\/\/(?:www\.)?(?:(?:\w)+\.)?github\.com\/(?<org>.+)\/(?<repo>.+)\/issues\/([[:digit:]]+)/)
+ matches_regexp(
+ %r{^https?://(?:www\.)?(?:(?:\w)+\.)?github\.com/(?<org>.+)/(?<repo>.+)/issues/([[:digit:]]+)},
+ )
always_https
def url
@@ -22,35 +24,36 @@ module Onebox
private
def match
- @match ||= @url.match(/^http(?:s)?:\/\/(?:www\.)?(?:(?:\w)+\.)?github\.com\/(?<org>.+)\/(?<repo>.+)\/(?<type>issues)\/(?<item_id>[\d]+)/)
+ @match ||=
+ @url.match(
+ %r{^http(?:s)?://(?:www\.)?(?:(?:\w)+\.)?github\.com/(?<org>.+)/(?<repo>.+)/(?<type>issues)/(?<item_id>[\d]+)},
+ )
end
def data
- created_at = Time.parse(raw['created_at'])
- closed_at = Time.parse(raw['closed_at']) if raw['closed_at']
- body, excerpt = compute_body(raw['body'])
+ created_at = Time.parse(raw["created_at"])
+ closed_at = Time.parse(raw["closed_at"]) if raw["closed_at"]
+ body, excerpt = compute_body(raw["body"])
ulink = URI(link)
- labels = raw['labels'].map do |l|
- { name: Emoji.codes_to_img(l['name']) }
- end
+ labels = raw["labels"].map { |l| { name: Emoji.codes_to_img(l["name"]) } }
{
link: @url,
- title: raw['title'],
+ title: raw["title"],
body: body,
excerpt: excerpt,
labels: labels,
- user: raw['user'],
- created_at: created_at.strftime('%I:%M%p - %d %b %y %Z'),
- created_at_date: created_at.strftime('%F'),
- created_at_time: created_at.strftime('%T'),
- closed_at: closed_at&.strftime('%I:%M%p - %d %b %y %Z'),
- closed_at_date: closed_at&.strftime('%F'),
- closed_at_time: closed_at&.strftime('%T'),
- closed_by: raw['closed_by'],
- avatar: "https://avatars1.githubusercontent.com/u/#{raw['user']['id']}?v=2&s=96",
- domain: "#{ulink.host}/#{ulink.path.split('/')[1]}/#{ulink.path.split('/')[2]}",
+ user: raw["user"],
+ created_at: created_at.strftime("%I:%M%p - %d %b %y %Z"),
+ created_at_date: created_at.strftime("%F"),
+ created_at_time: created_at.strftime("%T"),
+ closed_at: closed_at&.strftime("%I:%M%p - %d %b %y %Z"),
+ closed_at_date: closed_at&.strftime("%F"),
+ closed_at_time: closed_at&.strftime("%T"),
+ closed_by: raw["closed_by"],
+ avatar: "https://avatars1.githubusercontent.com/u/#{raw["user"]["id"]}?v=2&s=96",
+ domain: "#{ulink.host}/#{ulink.path.split("/")[1]}/#{ulink.path.split("/")[2]}",
}
end
end
diff --git a/lib/onebox/engine/github_pull_request_onebox.rb b/lib/onebox/engine/github_pull_request_onebox.rb
index 1ef23815cc9..77310cc46f9 100644
--- a/lib/onebox/engine/github_pull_request_onebox.rb
+++ b/lib/onebox/engine/github_pull_request_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative '../mixins/github_body'
+require_relative "../mixins/github_body"
module Onebox
module Engine
@@ -12,7 +12,7 @@ module Onebox
GITHUB_COMMENT_REGEX = /(<!--.*?-->\r\n)/
- matches_regexp(/^https?:\/\/(?:www\.)?(?:(?:\w)+\.)?(github)\.com(?:\/)?(?:.)*\/pull/)
+ matches_regexp(%r{^https?://(?:www\.)?(?:(?:\w)+\.)?(github)\.com(?:/)?(?:.)*/pull})
always_https
def url
@@ -22,51 +22,59 @@ module Onebox
private
def match
- @match ||= @url.match(%r{github\.com/(?<owner>[^/]+)/(?<repository>[^/]+)/pull/(?<number>[^/]+)})
+ @match ||=
+ @url.match(%r{github\.com/(?<owner>[^/]+)/(?<repository>[^/]+)/pull/(?<number>[^/]+)})
end
def data
result = raw.clone
- result['link'] = link
+ result["link"] = link
- created_at = Time.parse(result['created_at'])
- result['created_at'] = created_at.strftime("%I:%M%p - %d %b %y %Z")
- result['created_at_date'] = created_at.strftime("%F")
- result['created_at_time'] = created_at.strftime("%T")
+ created_at = Time.parse(result["created_at"])
+ result["created_at"] = created_at.strftime("%I:%M%p - %d %b %y %Z")
+ result["created_at_date"] = created_at.strftime("%F")
+ result["created_at_time"] = created_at.strftime("%T")
ulink = URI(link)
- result['domain'] = "#{ulink.host}/#{ulink.path.split('/')[1]}/#{ulink.path.split('/')[2]}"
+ result["domain"] = "#{ulink.host}/#{ulink.path.split("/")[1]}/#{ulink.path.split("/")[2]}"
- result['body'], result['excerpt'] = compute_body(result['body'])
+ result["body"], result["excerpt"] = compute_body(result["body"])
- if result['commit'] = load_commit(link)
- result['body'], result['excerpt'] = compute_body(result['commit']['commit']['message'].lines[1..].join)
- elsif result['comment'] = load_comment(link)
- result['body'], result['excerpt'] = compute_body(result['comment']['body'])
- elsif result['discussion'] = load_review(link)
- result['body'], result['excerpt'] = compute_body(result['discussion']['body'])
+ if result["commit"] = load_commit(link)
+ result["body"], result["excerpt"] =
+ compute_body(result["commit"]["commit"]["message"].lines[1..].join)
+ elsif result["comment"] = load_comment(link)
+ result["body"], result["excerpt"] = compute_body(result["comment"]["body"])
+ elsif result["discussion"] = load_review(link)
+ result["body"], result["excerpt"] = compute_body(result["discussion"]["body"])
else
- result['pr'] = true
+ result["pr"] = true
end
result
end
def load_commit(link)
- if commit_match = link.match(/commits\/(\h+)/)
- load_json("https://api.github.com/repos/#{match[:owner]}/#{match[:repository]}/commits/#{commit_match[1]}")
+ if commit_match = link.match(%r{commits/(\h+)})
+ load_json(
+ "https://api.github.com/repos/#{match[:owner]}/#{match[:repository]}/commits/#{commit_match[1]}",
+ )
end
end
def load_comment(link)
if comment_match = link.match(/#issuecomment-(\d+)/)
- load_json("https://api.github.com/repos/#{match[:owner]}/#{match[:repository]}/issues/comments/#{comment_match[1]}")
+ load_json(
+ "https://api.github.com/repos/#{match[:owner]}/#{match[:repository]}/issues/comments/#{comment_match[1]}",
+ )
end
end
def load_review(link)
if review_match = link.match(/#discussion_r(\d+)/)
- load_json("https://api.github.com/repos/#{match[:owner]}/#{match[:repository]}/pulls/comments/#{review_match[1]}")
+ load_json(
+ "https://api.github.com/repos/#{match[:owner]}/#{match[:repository]}/pulls/comments/#{review_match[1]}",
+ )
end
end
diff --git a/lib/onebox/engine/gitlab_blob_onebox.rb b/lib/onebox/engine/gitlab_blob_onebox.rb
index d8ba1973381..c948e5bf6df 100644
--- a/lib/onebox/engine/gitlab_blob_onebox.rb
+++ b/lib/onebox/engine/gitlab_blob_onebox.rb
@@ -1,12 +1,12 @@
# frozen_string_literal: true
-require_relative '../mixins/git_blob_onebox'
+require_relative "../mixins/git_blob_onebox"
module Onebox
module Engine
class GitlabBlobOnebox
def self.git_regexp
- /^https?:\/\/(www\.)?gitlab\.com.*\/blob\//
+ %r{^https?://(www\.)?gitlab\.com.*/blob/}
end
def self.onebox_name
@@ -16,7 +16,7 @@ module Onebox
include Onebox::Mixins::GitBlobOnebox
def raw_regexp
- /gitlab\.com\/(?<user>[^\/]+)\/(?<repo>[^\/]+)\/blob\/(?<sha1>[^\/]+)\/(?<file>[^#]+)(#(L(?<from>[^-]*)(-L(?<to>.*))?))?/mi
+ %r{gitlab\.com/(?<user>[^/]+)/(?<repo>[^/]+)/blob/(?<sha1>[^/]+)/(?<file>[^#]+)(#(L(?<from>[^-]*)(-L(?<to>.*))?))?}mi
end
def raw_template(m)
@@ -24,7 +24,7 @@ module Onebox
end
def title
- Sanitize.fragment(Onebox::Helpers.uri_unencode(link).sub(/^https?\:\/\/gitlab\.com\//, ''))
+ Sanitize.fragment(Onebox::Helpers.uri_unencode(link).sub(%r{^https?\://gitlab\.com/}, ""))
end
end
end
diff --git a/lib/onebox/engine/google_calendar_onebox.rb b/lib/onebox/engine/google_calendar_onebox.rb
index b666df4d080..a7b57b220b6 100644
--- a/lib/onebox/engine/google_calendar_onebox.rb
+++ b/lib/onebox/engine/google_calendar_onebox.rb
@@ -10,7 +10,7 @@ module Onebox
requires_iframe_origins "https://calendar.google.com"
def to_html
- url = @url.split('&').first
+ url = @url.split("&").first
src = ::Onebox::Helpers.normalize_url_for_output(url)
"<iframe src='#{src}&rm=minimal' style='border: 0' width='800' height='600' frameborder='0' scrolling='no'>#{placeholder_html}</iframe>"
end
diff --git a/lib/onebox/engine/google_docs_onebox.rb b/lib/onebox/engine/google_docs_onebox.rb
index cc7872aebe4..ebb29a43bb5 100644
--- a/lib/onebox/engine/google_docs_onebox.rb
+++ b/lib/onebox/engine/google_docs_onebox.rb
@@ -7,15 +7,12 @@ module Onebox
include StandardEmbed
include LayoutSupport
- SUPPORTED_ENDPOINTS = %w(spreadsheets document forms presentation)
- SHORT_TYPES = {
- spreadsheets: :sheets,
- document: :docs,
- presentation: :slides,
- forms: :forms,
- }
-
- matches_regexp(/^(https?:)?\/\/(docs\.google\.com)\/(?<endpoint>(#{SUPPORTED_ENDPOINTS.join('|')}))\/d\/((?<key>[\w-]*)).+$/)
+ SUPPORTED_ENDPOINTS = %w[spreadsheets document forms presentation]
+ SHORT_TYPES = { spreadsheets: :sheets, document: :docs, presentation: :slides, forms: :forms }
+
+ matches_regexp(
+ %r{^(https?:)?//(docs\.google\.com)/(?<endpoint>(#{SUPPORTED_ENDPOINTS.join("|")}))/d/((?<key>[\w-]*)).+$},
+ )
always_https
private
@@ -24,17 +21,18 @@ module Onebox
og_data = get_opengraph
short_type = SHORT_TYPES[match[:endpoint].to_sym]
- description = if Onebox::Helpers.blank?(og_data.description)
- "This #{short_type.to_s.chop.capitalize} is private"
- else
- Onebox::Helpers.truncate(og_data.description, 250)
- end
+ description =
+ if Onebox::Helpers.blank?(og_data.description)
+ "This #{short_type.to_s.chop.capitalize} is private"
+ else
+ Onebox::Helpers.truncate(og_data.description, 250)
+ end
{
link: link,
title: og_data.title || "Google #{short_type.to_s.capitalize}",
description: description,
- type: short_type
+ type: short_type,
}
end
diff --git a/lib/onebox/engine/google_drive_onebox.rb b/lib/onebox/engine/google_drive_onebox.rb
index 82628228ea9..cb8bbf797e1 100644
--- a/lib/onebox/engine/google_drive_onebox.rb
+++ b/lib/onebox/engine/google_drive_onebox.rb
@@ -7,7 +7,7 @@ module Onebox
include StandardEmbed
include LayoutSupport
- matches_regexp(/^(https?:)?\/\/(drive\.google\.com)\/file\/d\/(?<key>[\w-]*)\/.+$/)
+ matches_regexp(%r{^(https?:)?//(drive\.google\.com)/file/d/(?<key>[\w-]*)/.+$})
always_https
protected
@@ -15,14 +15,14 @@ module Onebox
def data
og_data = get_opengraph
title = og_data.title || "Google Drive"
- title = "#{og_data.title} (video)" if og_data.type =~ /^video[\/\.]/
+ title = "#{og_data.title} (video)" if og_data.type =~ %r{^video[/\.]}
description = og_data.description || "Google Drive file."
{
link: link,
title: title,
description: Onebox::Helpers.truncate(description, 250),
- image: og_data.image
+ image: og_data.image,
}
end
end
diff --git a/lib/onebox/engine/google_maps_onebox.rb b/lib/onebox/engine/google_maps_onebox.rb
index 0c4fbcf16d9..828c7fd5dcb 100644
--- a/lib/onebox/engine/google_maps_onebox.rb
+++ b/lib/onebox/engine/google_maps_onebox.rb
@@ -25,24 +25,30 @@ module Onebox
requires_iframe_origins("https://maps.google.com", "https://google.com")
# Matches shortened Google Maps URLs
- matches_regexp :short, %r"^(https?:)?//goo\.gl/maps/"
+ matches_regexp :short, %r{^(https?:)?//goo\.gl/maps/}
# Matches URLs for custom-created maps
- matches_regexp :custom, %r"^(?:https?:)?//www\.google(?:\.(?:\w{2,}))+/maps/d/(?:edit|viewer|embed)\?mid=.+$"
+ matches_regexp :custom,
+ %r"^(?:https?:)?//www\.google(?:\.(?:\w{2,}))+/maps/d/(?:edit|viewer|embed)\?mid=.+$"
# Matches URLs with streetview data
- matches_regexp :streetview, %r"^(?:https?:)?//www\.google(?:\.(?:\w{2,}))+/maps[^@]+@(?<lon>-?[\d.]+),(?<lat>-?[\d.]+),(?:\d+)a,(?<zoom>[\d.]+)y,(?<heading>[\d.]+)h,(?<pitch>[\d.]+)t.+?data=.*?!1s(?<pano>[^!]{22})"
+ matches_regexp :streetview,
+ %r"^(?:https?:)?//www\.google(?:\.(?:\w{2,}))+/maps[^@]+@(?<lon>-?[\d.]+),(?<lat>-?[\d.]+),(?:\d+)a,(?<zoom>[\d.]+)y,(?<heading>[\d.]+)h,(?<pitch>[\d.]+)t.+?data=.*?!1s(?<pano>[^!]{22})"
# Matches "normal" Google Maps URLs with arbitrary data
- matches_regexp :standard, %r"^(?:https?:)?//www\.google(?:\.(?:\w{2,}))+/maps"
+ matches_regexp :standard, %r"^(?:https?:)?//www\.google(?:\.(?:\w{2,}))+/maps"
# Matches URLs for the old Google Maps domain which we occasionally get redirected to
- matches_regexp :canonical, %r"^(?:https?:)?//maps\.google(?:\.(?:\w{2,}))+/maps\?"
+ matches_regexp :canonical, %r"^(?:https?:)?//maps\.google(?:\.(?:\w{2,}))+/maps\?"
def initialize(url, timeout = nil)
super
resolve_url!
- rescue Net::HTTPServerException, Timeout::Error, Net::HTTPError, Errno::ECONNREFUSED, RuntimeError => err
+ rescue Net::HTTPServerException,
+ Timeout::Error,
+ Net::HTTPError,
+ Errno::ECONNREFUSED,
+ RuntimeError => err
raise ArgumentError, "malformed url or unresolveable: #{err.message}"
end
@@ -95,17 +101,16 @@ module Onebox
zoom = match[:mz] == "z" ? match[:zoom] : Math.log2(57280048.0 / match[:zoom].to_f).round
location = "#{match[:lon]},#{match[:lat]}"
url = "https://maps.google.com/maps?ll=#{location}&z=#{zoom}&output=embed&dg=ntvb"
- url += "&q=#{$1}" if match = @url.match(/\/place\/([^\/\?]+)/)
+ url += "&q=#{$1}" if match = @url.match(%r{/place/([^/\?]+)})
url += "&cid=#{($1 + $2).to_i(16)}" if @url.match(/!3m1!1s0x(\h{16}):0x(\h{16})/)
@url = url
- @placeholder = "https://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&center=#{location}&zoom=#{zoom}&size=690x400&sensor=false"
-
+ @placeholder =
+ "https://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&center=#{location}&zoom=#{zoom}&size=690x400&sensor=false"
when :custom
url = @url.dup
@url = rewrite_custom_url(url, "embed")
@placeholder = rewrite_custom_url(url, "thumbnail")
@placeholder_height = @placeholder_width = 120
-
when :streetview
@streetview = true
panoid = match[:pano]
@@ -115,19 +120,24 @@ module Onebox
pitch = (match[:pitch].to_f / 10.0).round(4).to_s
fov = (match[:zoom].to_f / 100.0).round(4).to_s
zoom = match[:zoom].to_f.round
- @url = "https://www.google.com/maps/embed?pb=!3m2!2sen!4v0!6m8!1m7!1s#{panoid}!2m2!1d#{lon}!2d#{lat}!3f#{heading}!4f#{pitch}!5f#{fov}"
- @placeholder = "https://maps.googleapis.com/maps/api/streetview?size=690x400&location=#{lon},#{lat}&pano=#{panoid}&fov=#{zoom}&heading=#{heading}&pitch=#{pitch}&sensor=false"
-
+ @url =
+ "https://www.google.com/maps/embed?pb=!3m2!2sen!4v0!6m8!1m7!1s#{panoid}!2m2!1d#{lon}!2d#{lat}!3f#{heading}!4f#{pitch}!5f#{fov}"
+ @placeholder =
+ "https://maps.googleapis.com/maps/api/streetview?size=690x400&location=#{lon},#{lat}&pano=#{panoid}&fov=#{zoom}&heading=#{heading}&pitch=#{pitch}&sensor=false"
when :canonical
- query = URI::decode_www_form(uri.query).to_h
+ query = URI.decode_www_form(uri.query).to_h
if !query.has_key?("ll")
- raise ArgumentError, "canonical url lacks location argument" unless query.has_key?("sll")
+ unless query.has_key?("sll")
+ raise ArgumentError, "canonical url lacks location argument"
+ end
query["ll"] = query["sll"]
@url += "&ll=#{query["sll"]}"
end
location = query["ll"]
if !query.has_key?("z")
- raise ArgumentError, "canonical url has incomplete query arguments" unless query.has_key?("spn") || query.has_key?("sspn")
+ unless query.has_key?("spn") || query.has_key?("sspn")
+ raise ArgumentError, "canonical url has incomplete query arguments"
+ end
if !query.has_key?("spn")
query["spn"] = query["sspn"]
@url += "&spn=#{query["sspn"]}"
@@ -137,9 +147,9 @@ module Onebox
else
zoom = query["z"]
end
- @url = @url.sub('output=classic', 'output=embed')
- @placeholder = "https://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=690x400&sensor=false&center=#{location}&zoom=#{zoom}"
-
+ @url = @url.sub("output=classic", "output=embed")
+ @placeholder =
+ "https://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=690x400&sensor=false&center=#{location}&zoom=#{zoom}"
else
raise "unexpected url type #{type.inspect}"
end
@@ -156,27 +166,34 @@ module Onebox
def rewrite_custom_url(url, target)
uri = URI(url)
- uri.path = uri.path.sub(/(?<=^\/maps\/d\/)\w+$/, target)
+ uri.path = uri.path.sub(%r{(?<=^/maps/d/)\w+$}, target)
uri.to_s
end
def follow_redirect!
begin
- http = FinalDestination::HTTP.start(
- uri.host,
- uri.port,
- use_ssl: uri.scheme == 'https',
- open_timeout: timeout,
- read_timeout: timeout
- )
+ http =
+ FinalDestination::HTTP.start(
+ uri.host,
+ uri.port,
+ use_ssl: uri.scheme == "https",
+ open_timeout: timeout,
+ read_timeout: timeout,
+ )
response = http.head(uri.path)
- raise "unexpected response code #{response.code}" unless %w(200 301 302).include?(response.code)
+ unless %w[200 301 302].include?(response.code)
+ raise "unexpected response code #{response.code}"
+ end
@url = response.code == "200" ? uri.to_s : response["Location"]
@uri = URI(@url)
ensure
- http.finish rescue nil
+ begin
+ http.finish
+ rescue StandardError
+ nil
+ end
end
end
end
diff --git a/lib/onebox/engine/google_photos_onebox.rb b/lib/onebox/engine/google_photos_onebox.rb
index 6c930ce59cc..afb8aade192 100644
--- a/lib/onebox/engine/google_photos_onebox.rb
+++ b/lib/onebox/engine/google_photos_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/(photos)\.(app\.goo\.gl|google\.com)/)
+ matches_regexp(%r{^https?://(photos)\.(app\.goo\.gl|google\.com)})
always_https
def to_html
diff --git a/lib/onebox/engine/google_play_app_onebox.rb b/lib/onebox/engine/google_play_app_onebox.rb
index 1e2557d4422..f03fceee505 100644
--- a/lib/onebox/engine/google_play_app_onebox.rb
+++ b/lib/onebox/engine/google_play_app_onebox.rb
@@ -7,23 +7,36 @@ module Onebox
include LayoutSupport
include HTML
- DEFAULTS = {
- MAX_DESCRIPTION_CHARS: 500
- }
+ DEFAULTS = { MAX_DESCRIPTION_CHARS: 500 }
- matches_regexp(/^https?:\/\/play\.(?:(?:\w)+\.)?(google)\.com(?:\/)?\/store\/apps\//)
+ matches_regexp(%r{^https?://play\.(?:(?:\w)+\.)?(google)\.com(?:/)?/store/apps/})
always_https
private
def data
- price = raw.css("meta[itemprop=price]").first["content"] rescue "Free"
+ price =
+ begin
+ raw.css("meta[itemprop=price]").first["content"]
+ rescue StandardError
+ "Free"
+ end
{
link: link,
- title: raw.css("meta[property='og:title']").first["content"].gsub(" - Apps on Google Play", ""),
- image: ::Onebox::Helpers.normalize_url_for_output(raw.css("meta[property='og:image']").first["content"]),
- description: raw.css("meta[name=description]").first["content"][0..DEFAULTS[:MAX_DESCRIPTION_CHARS]].chop + "...",
- price: price == "0" ? "Free" : price
+ title:
+ raw.css("meta[property='og:title']").first["content"].gsub(
+ " - Apps on Google Play",
+ "",
+ ),
+ image:
+ ::Onebox::Helpers.normalize_url_for_output(
+ raw.css("meta[property='og:image']").first["content"],
+ ),
+ description:
+ raw.css("meta[name=description]").first["content"][
+ 0..DEFAULTS[:MAX_DESCRIPTION_CHARS]
+ ].chop + "...",
+ price: price == "0" ? "Free" : price,
}
end
end
diff --git a/lib/onebox/engine/hackernews_onebox.rb b/lib/onebox/engine/hackernews_onebox.rb
index 79d8e037a58..b4507f26e0c 100644
--- a/lib/onebox/engine/hackernews_onebox.rb
+++ b/lib/onebox/engine/hackernews_onebox.rb
@@ -7,7 +7,7 @@ module Onebox
include LayoutSupport
include JSON
- REGEX = /^https?:\/\/news\.ycombinator\.com\/item\?id=(?<item_id>\d+)/
+ REGEX = %r{^https?://news\.ycombinator\.com/item\?id=(?<item_id>\d+)}
matches_regexp(REGEX)
@@ -23,22 +23,24 @@ module Onebox
end
def data
- return nil unless %w{story comment}.include?(raw['type'])
+ return nil unless %w[story comment].include?(raw["type"])
html_entities = HTMLEntities.new
data = {
link: @url,
- title: Onebox::Helpers.truncate(raw['title'], 80),
- favicon: 'https://news.ycombinator.com/y18.gif',
- timestamp: Time.at(raw['time']).strftime("%-l:%M %p - %-d %b %Y"),
- author: raw['by']
+ title: Onebox::Helpers.truncate(raw["title"], 80),
+ favicon: "https://news.ycombinator.com/y18.gif",
+ timestamp: Time.at(raw["time"]).strftime("%-l:%M %p - %-d %b %Y"),
+ author: raw["by"],
}
- data['description'] = html_entities.decode(Onebox::Helpers.truncate(raw['text'], 400)) if raw['text']
+ data["description"] = html_entities.decode(
+ Onebox::Helpers.truncate(raw["text"], 400),
+ ) if raw["text"]
- if raw['type'] == 'story'
- data['data_1'] = raw['score']
- data['data_2'] = raw['descendants']
+ if raw["type"] == "story"
+ data["data_1"] = raw["score"]
+ data["data_2"] = raw["descendants"]
end
data
diff --git a/lib/onebox/engine/image_onebox.rb b/lib/onebox/engine/image_onebox.rb
index d37faff841b..2b6e08ac923 100644
--- a/lib/onebox/engine/image_onebox.rb
+++ b/lib/onebox/engine/image_onebox.rb
@@ -5,8 +5,8 @@ module Onebox
class ImageOnebox
include Engine
- matches_content_type(/^image\/(png|jpg|jpeg|gif|bmp|tif|tiff)$/)
- matches_regexp(/^(https?:)?\/\/.+\.(png|jpg|jpeg|gif|bmp|tif|tiff)(\?.*)?$/i)
+ matches_content_type(%r{^image/(png|jpg|jpeg|gif|bmp|tif|tiff)$})
+ matches_regexp(%r{^(https?:)?//.+\.(png|jpg|jpeg|gif|bmp|tif|tiff)(\?.*)?$}i)
def always_https?
AllowlistedGenericOnebox.host_matches(uri, AllowlistedGenericOnebox.https_hosts)
@@ -14,7 +14,7 @@ module Onebox
def to_html
# Fix Dropbox image links
- if @url[/^https:\/\/www.dropbox.com\/s\//]
+ if @url[%r{^https://www.dropbox.com/s/}]
@url.sub!("https://www.dropbox.com", "https://dl.dropboxusercontent.com")
end
diff --git a/lib/onebox/engine/imgur_onebox.rb b/lib/onebox/engine/imgur_onebox.rb
index 26a90379dd1..127f73baee9 100644
--- a/lib/onebox/engine/imgur_onebox.rb
+++ b/lib/onebox/engine/imgur_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/(www\.)?imgur\.com/)
+ matches_regexp(%r{^https?://(www\.)?imgur\.com})
always_https
def to_html
@@ -23,7 +23,7 @@ module Onebox
<<-HTML
<video width='#{og.video_width}' height='#{og.video_height}' #{og.title_attr} controls loop>
<source src='#{og.video_secure_url}' type='video/mp4'>
- <source src='#{og.video_secure_url.gsub('mp4', 'webm')}' type='video/webm'>
+ <source src='#{og.video_secure_url.gsub("mp4", "webm")}' type='video/webm'>
</video>
HTML
end
@@ -47,10 +47,15 @@ module Onebox
end
def is_album?
- response = Onebox::Helpers.fetch_response("https://api.imgur.com/oembed.json?url=#{url}") rescue "{}"
+ response =
+ begin
+ Onebox::Helpers.fetch_response("https://api.imgur.com/oembed.json?url=#{url}")
+ rescue StandardError
+ "{}"
+ end
oembed_data = Onebox::Helpers.symbolize_keys(::MultiJson.load(response))
- imgur_data_id = Nokogiri::HTML(oembed_data[:html]).xpath("//blockquote").attr("data-id")
- imgur_data_id.to_s[/a\//]
+ imgur_data_id = Nokogiri.HTML(oembed_data[:html]).xpath("//blockquote").attr("data-id")
+ imgur_data_id.to_s[%r{a/}]
end
def image_html(og)
diff --git a/lib/onebox/engine/instagram_onebox.rb b/lib/onebox/engine/instagram_onebox.rb
index 7cc96ad3d61..86fd55947f2 100644
--- a/lib/onebox/engine/instagram_onebox.rb
+++ b/lib/onebox/engine/instagram_onebox.rb
@@ -7,28 +7,38 @@ module Onebox
include StandardEmbed
include LayoutSupport
- matches_regexp(/^https?:\/\/(?:www\.)?(?:instagram\.com|instagr\.am)\/?(?:.*)\/(?:p|tv)\/[a-zA-Z\d_-]+/)
+ matches_regexp(
+ %r{^https?://(?:www\.)?(?:instagram\.com|instagr\.am)/?(?:.*)/(?:p|tv)/[a-zA-Z\d_-]+},
+ )
always_https
requires_iframe_origins "https://www.instagram.com"
def clean_url
- url.scan(/^https?:\/\/(?:www\.)?(?:instagram\.com|instagr\.am)\/?(?:.*)\/(?:p|tv)\/[a-zA-Z\d_-]+/).flatten.first
+ url
+ .scan(
+ %r{^https?://(?:www\.)?(?:instagram\.com|instagr\.am)/?(?:.*)/(?:p|tv)/[a-zA-Z\d_-]+},
+ )
+ .flatten
+ .first
end
def data
- @data ||= begin
- oembed = get_oembed
- raise "No oEmbed data found. Ensure 'facebook_app_access_token' is valid" if oembed.data.empty?
+ @data ||=
+ begin
+ oembed = get_oembed
+ if oembed.data.empty?
+ raise "No oEmbed data found. Ensure 'facebook_app_access_token' is valid"
+ end
- {
- link: clean_url.gsub("/#{oembed.author_name}/", "/") + '/embed',
- title: "@#{oembed.author_name}",
- image: oembed.thumbnail_url,
- image_width: oembed.data[:thumbnail_width],
- image_height: oembed.data[:thumbnail_height],
- description: Onebox::Helpers.truncate(oembed.title, 250),
- }
- end
+ {
+ link: clean_url.gsub("/#{oembed.author_name}/", "/") + "/embed",
+ title: "@#{oembed.author_name}",
+ image: oembed.thumbnail_url,
+ image_width: oembed.data[:thumbnail_width],
+ image_height: oembed.data[:thumbnail_height],
+ description: Onebox::Helpers.truncate(oembed.title, 250),
+ }
+ end
end
def placeholder_html
@@ -53,7 +63,7 @@ module Onebox
end
def get_oembed_url
- if access_token != ''
+ if access_token != ""
"https://graph.facebook.com/v9.0/instagram_oembed?url=#{clean_url}&access_token=#{access_token}"
else
# The following is officially deprecated by Instagram, but works in some limited circumstances.
diff --git a/lib/onebox/engine/kaltura_onebox.rb b/lib/onebox/engine/kaltura_onebox.rb
index d94091a4f0a..f9ace113638 100644
--- a/lib/onebox/engine/kaltura_onebox.rb
+++ b/lib/onebox/engine/kaltura_onebox.rb
@@ -7,7 +7,7 @@ module Onebox
include StandardEmbed
always_https
- matches_regexp(/^https?:\/\/[a-z0-9]+\.kaltura\.com\/id\/[a-zA-Z0-9]+/)
+ matches_regexp(%r{^https?://[a-z0-9]+\.kaltura\.com/id/[a-zA-Z0-9]+})
requires_iframe_origins "https://*.kaltura.com"
def preview_html
diff --git a/lib/onebox/engine/mixcloud_onebox.rb b/lib/onebox/engine/mixcloud_onebox.rb
index 3d4e92295fa..1a681d5ec0f 100644
--- a/lib/onebox/engine/mixcloud_onebox.rb
+++ b/lib/onebox/engine/mixcloud_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/www\.mixcloud\.com\//)
+ matches_regexp(%r{^https?://www\.mixcloud\.com/})
always_https
requires_iframe_origins "https://www.mixcloud.com"
diff --git a/lib/onebox/engine/motoko_onebox.rb b/lib/onebox/engine/motoko_onebox.rb
index ec6433d2e47..1656150fbfd 100644
--- a/lib/onebox/engine/motoko_onebox.rb
+++ b/lib/onebox/engine/motoko_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/embed\.smartcontracts\.org\/?.*/)
+ matches_regexp(%r{^https?://embed\.smartcontracts\.org/?.*})
requires_iframe_origins "https://embed.smartcontracts.org"
always_https
diff --git a/lib/onebox/engine/opengraph_image.rb b/lib/onebox/engine/opengraph_image.rb
index a104db36ffb..77bf8ee2103 100644
--- a/lib/onebox/engine/opengraph_image.rb
+++ b/lib/onebox/engine/opengraph_image.rb
@@ -3,7 +3,6 @@
module Onebox
module Engine
module OpengraphImage
-
def to_html
og = get_opengraph
"<img src='#{og.image}' width='#{og.image_width}' height='#{og.image_height}' class='onebox' #{og.title_attr}>"
diff --git a/lib/onebox/engine/pastebin_onebox.rb b/lib/onebox/engine/pastebin_onebox.rb
index d9b26467f3c..c542457f8d2 100644
--- a/lib/onebox/engine/pastebin_onebox.rb
+++ b/lib/onebox/engine/pastebin_onebox.rb
@@ -8,17 +8,12 @@ module Onebox
MAX_LINES = 10
- matches_regexp(/^http?:\/\/pastebin\.com/)
+ matches_regexp(%r{^http?://pastebin\.com})
private
def data
- @data ||= {
- title: 'pastebin.com',
- link: link,
- content: content,
- truncated?: truncated?
- }
+ @data ||= { title: "pastebin.com", link: link, content: content, truncated?: truncated? }
end
def content
@@ -31,21 +26,30 @@ module Onebox
def lines
return @lines if defined?(@lines)
- response = Onebox::Helpers.fetch_response("http://pastebin.com/raw/#{paste_key}", redirect_limit: 1) rescue ""
+ response =
+ begin
+ Onebox::Helpers.fetch_response(
+ "http://pastebin.com/raw/#{paste_key}",
+ redirect_limit: 1,
+ )
+ rescue StandardError
+ ""
+ end
@lines = response.split("\n")
end
def paste_key
- regex = case uri
- when /\/raw\//
- /\/raw\/([^\/]+)/
- when /\/download\//
- /\/download\/([^\/]+)/
- when /\/embed\//
- /\/embed\/([^\/]+)/
- else
- /\/([^\/]+)/
- end
+ regex =
+ case uri
+ when %r{/raw/}
+ %r{/raw/([^/]+)}
+ when %r{/download/}
+ %r{/download/([^/]+)}
+ when %r{/embed/}
+ %r{/embed/([^/]+)}
+ else
+ %r{/([^/]+)}
+ end
match = uri.path.match(regex)
match[1] if match && match[1]
diff --git a/lib/onebox/engine/pdf_onebox.rb b/lib/onebox/engine/pdf_onebox.rb
index 2a8d46f0d4a..30af7975b03 100644
--- a/lib/onebox/engine/pdf_onebox.rb
+++ b/lib/onebox/engine/pdf_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include LayoutSupport
- matches_regexp(/^(https?:)?\/\/.*\.pdf(\?.*)?$/i)
+ matches_regexp(%r{^(https?:)?//.*\.pdf(\?.*)?$}i)
always_https
private
@@ -14,7 +14,7 @@ module Onebox
def data
begin
size = Onebox::Helpers.fetch_content_length(@url)
- rescue
+ rescue StandardError
raise "Unable to read pdf file: #{@url}"
end
diff --git a/lib/onebox/engine/pubmed_onebox.rb b/lib/onebox/engine/pubmed_onebox.rb
index 366d5d50299..fe3a39da27c 100644
--- a/lib/onebox/engine/pubmed_onebox.rb
+++ b/lib/onebox/engine/pubmed_onebox.rb
@@ -6,22 +6,22 @@ module Onebox
include Engine
include LayoutSupport
- matches_regexp(/^https?:\/\/(?:(?:\w)+\.)?(www.ncbi.nlm.nih)\.gov(?:\/)?\/pubmed\/\d+/)
+ matches_regexp(%r{^https?://(?:(?:\w)+\.)?(www.ncbi.nlm.nih)\.gov(?:/)?/pubmed/\d+})
private
def xml
return @xml if defined?(@xml)
- doc = Nokogiri::XML(URI.join(@url, "?report=xml&format=text").open)
+ doc = Nokogiri.XML(URI.join(@url, "?report=xml&format=text").open)
pre = doc.xpath("//pre")
- @xml = Nokogiri::XML("<root>" + pre.text + "</root>")
+ @xml = Nokogiri.XML("<root>" + pre.text + "</root>")
end
def authors
initials = xml.css("Initials").map { |x| x.content }
last_names = xml.css("LastName").map { |x| x.content }
author_list = (initials.zip(last_names)).map { |i, l| i + " " + l }
- if author_list.length > 1 then
+ if author_list.length > 1
author_list[-2] = author_list[-2] + " and " + author_list[-1]
author_list.pop
end
@@ -29,7 +29,8 @@ module Onebox
end
def date
- xml.css("PubDate")
+ xml
+ .css("PubDate")
.children
.map { |x| x.content }
.select { |s| !s.match(/^\s+$/) }
@@ -48,7 +49,7 @@ module Onebox
abstract: xml.css("AbstractText").text,
date: date,
link: @url,
- pmid: match[:pmid]
+ pmid: match[:pmid],
}
end
diff --git a/lib/onebox/engine/reddit_media_onebox.rb b/lib/onebox/engine/reddit_media_onebox.rb
index d479a6b6496..876ed41fd56 100644
--- a/lib/onebox/engine/reddit_media_onebox.rb
+++ b/lib/onebox/engine/reddit_media_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/(www\.)?reddit\.com/)
+ matches_regexp(%r{^https?://(www\.)?reddit\.com})
def to_html
if raw[:type] == "image"
@@ -25,7 +25,7 @@ module Onebox
</article>
</aside>
HTML
- elsif raw[:type] =~ /^video[\/\.]/
+ elsif raw[:type] =~ %r{^video[/\.]}
<<-HTML
<aside class="onebox reddit">
<header class="source">
diff --git a/lib/onebox/engine/replit_onebox.rb b/lib/onebox/engine/replit_onebox.rb
index 8aa6d7b2651..55c49fea9f0 100644
--- a/lib/onebox/engine/replit_onebox.rb
+++ b/lib/onebox/engine/replit_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/(replit\.com|repl\.it)\/.+/)
+ matches_regexp(%r{^https?://(replit\.com|repl\.it)/.+})
always_https
def placeholder_html
diff --git a/lib/onebox/engine/simplecast_onebox.rb b/lib/onebox/engine/simplecast_onebox.rb
index b4c8790cbb9..df474b3832e 100644
--- a/lib/onebox/engine/simplecast_onebox.rb
+++ b/lib/onebox/engine/simplecast_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/https?:\/\/(.+)?simplecast.com\/(episodes|s)\/.*/)
+ matches_regexp(%r{https?://(.+)?simplecast.com/(episodes|s)/.*})
always_https
requires_iframe_origins("https://player.simplecast.com")
diff --git a/lib/onebox/engine/sketch_fab_onebox.rb b/lib/onebox/engine/sketch_fab_onebox.rb
index e45f6f0cf34..b946f3270ef 100644
--- a/lib/onebox/engine/sketch_fab_onebox.rb
+++ b/lib/onebox/engine/sketch_fab_onebox.rb
@@ -6,7 +6,9 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/sketchfab\.com\/(?:models\/|3d-models\/(?:[^\/\s]+-)?)([a-z0-9]{32})/)
+ matches_regexp(
+ /^https?:\/\/sketchfab\.com\/(?:models\/|3d-models\/(?:[^\/\s]+-)?)([a-z0-9]{32})/,
+ )
always_https
requires_iframe_origins("https://sketchfab.com")
diff --git a/lib/onebox/engine/sound_cloud_onebox.rb b/lib/onebox/engine/sound_cloud_onebox.rb
index c257932c2cd..1571c1bd942 100644
--- a/lib/onebox/engine/sound_cloud_onebox.rb
+++ b/lib/onebox/engine/sound_cloud_onebox.rb
@@ -6,13 +6,13 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/soundcloud\.com/)
+ matches_regexp(%r{^https?://soundcloud\.com})
requires_iframe_origins "https://w.soundcloud.com"
always_https
def to_html
oembed = get_oembed
- oembed.html.gsub('visual=true', 'visual=false')
+ oembed.html.gsub("visual=true", "visual=false")
end
def placeholder_html
diff --git a/lib/onebox/engine/stack_exchange_onebox.rb b/lib/onebox/engine/stack_exchange_onebox.rb
index c918ed93aac..c64400d0d05 100644
--- a/lib/onebox/engine/stack_exchange_onebox.rb
+++ b/lib/onebox/engine/stack_exchange_onebox.rb
@@ -8,14 +8,23 @@ module Onebox
include JSON
def self.domains
- %w(stackexchange.com stackoverflow.com superuser.com serverfault.com askubuntu.com stackapps.com mathoverflow.net)
- .map { |domain| Regexp.escape(domain) }
+ %w[
+ stackexchange.com
+ stackoverflow.com
+ superuser.com
+ serverfault.com
+ askubuntu.com
+ stackapps.com
+ mathoverflow.net
+ ].map { |domain| Regexp.escape(domain) }
end
- matches_regexp(/^https?:\/\/(?:(?:(?<subsubdomain>\w*)\.)?(?<subdomain>\w*)\.)?(?<domain>#{domains.join('|')})\/((?:questions|q)\/(?<question_id>\d*)(\/.*\/(?<answer_id1>\d*))?|(a\/(?<answer_id2>\d*)))/)
+ matches_regexp(
+ %r{^https?://(?:(?:(?<subsubdomain>\w*)\.)?(?<subdomain>\w*)\.)?(?<domain>#{domains.join("|")})/((?:questions|q)/(?<question_id>\d*)(/.*/(?<answer_id1>\d*))?|(a/(?<answer_id2>\d*)))},
+ )
def always_https?
- uri.host.split('.').length <= 3
+ uri.host.split(".").length <= 3
end
private
@@ -39,14 +48,15 @@ module Onebox
def data
return @data if defined?(@data)
- result = raw['items'][0]
+ result = raw["items"][0]
if result
- result['creation_date'] =
- Time.at(result['creation_date'].to_i).strftime("%I:%M%p - %d %b %y %Z")
+ result["creation_date"] = Time.at(result["creation_date"].to_i).strftime(
+ "%I:%M%p - %d %b %y %Z",
+ )
- result['tags'] = result['tags'].take(4).join(', ')
- result['is_answer'] = result.key?('answer_id')
- result['is_question'] = result.key?('question_id')
+ result["tags"] = result["tags"].take(4).join(", ")
+ result["is_answer"] = result.key?("answer_id")
+ result["is_question"] = result.key?("question_id")
end
@data = result
diff --git a/lib/onebox/engine/standard_embed.rb b/lib/onebox/engine/standard_embed.rb
index 29e6caf48cd..df5aa9aa9fb 100644
--- a/lib/onebox/engine/standard_embed.rb
+++ b/lib/onebox/engine/standard_embed.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-require 'cgi'
-require 'onebox/normalizer'
-require 'onebox/open_graph'
-require 'onebox/oembed'
-require 'onebox/json_ld'
+require "cgi"
+require "onebox/normalizer"
+require "onebox/open_graph"
+require "onebox/oembed"
+require "onebox/json_ld"
module Onebox
module Engine
@@ -26,12 +26,12 @@ module Onebox
end
# Some oembed providers (like meetup.com) don't provide links to themselves
- add_oembed_provider(/www\.meetup\.com\//, 'http://api.meetup.com/oembed')
- add_oembed_provider(/www\.mixcloud\.com\//, 'https://www.mixcloud.com/oembed/')
+ add_oembed_provider(%r{www\.meetup\.com/}, "http://api.meetup.com/oembed")
+ add_oembed_provider(%r{www\.mixcloud\.com/}, "https://www.mixcloud.com/oembed/")
# In order to support Private Videos
- add_oembed_provider(/vimeo\.com\//, 'https://vimeo.com/api/oembed.json')
+ add_oembed_provider(%r{vimeo\.com/}, "https://vimeo.com/api/oembed.json")
# NYT requires login so use oembed only
- add_oembed_provider(/nytimes\.com\//, 'https://www.nytimes.com/svc/oembed/json/')
+ add_oembed_provider(%r{nytimes\.com/}, "https://www.nytimes.com/svc/oembed/json/")
def always_https?
AllowlistedGenericOnebox.host_matches(uri, AllowlistedGenericOnebox.https_hosts) || super
@@ -58,7 +58,7 @@ module Onebox
return @html_doc if defined?(@html_doc)
headers = nil
- headers = { 'Cookie' => options[:cookie] } if options[:cookie]
+ headers = { "Cookie" => options[:cookie] } if options[:cookie]
@html_doc = Onebox::Helpers.fetch_html_doc(url, headers)
end
@@ -76,12 +76,17 @@ module Onebox
twitter = {}
- html_doc.css('meta').each do |m|
- if (m["property"] && m["property"][/^twitter:(.+)$/i]) || (m["name"] && m["name"][/^twitter:(.+)$/i])
- value = (m["content"] || m["value"]).to_s
- twitter[$1.tr('-:' , '_').to_sym] ||= value unless (Onebox::Helpers::blank?(value) || value == "0 minutes")
+ html_doc
+ .css("meta")
+ .each do |m|
+ if (m["property"] && m["property"][/^twitter:(.+)$/i]) ||
+ (m["name"] && m["name"][/^twitter:(.+)$/i])
+ value = (m["content"] || m["value"]).to_s
+ twitter[$1.tr("-:", "_").to_sym] ||= value unless (
+ Onebox::Helpers.blank?(value) || value == "0 minutes"
+ )
+ end
end
- end
twitter
end
@@ -89,17 +94,20 @@ module Onebox
def get_favicon
return nil unless html_doc
- favicon = html_doc.css('link[rel="shortcut icon"], link[rel="icon shortcut"], link[rel="shortcut"], link[rel="icon"]').first
- favicon = favicon.nil? ? nil : (favicon['href'].nil? ? nil : favicon['href'].strip)
+ favicon =
+ html_doc.css(
+ 'link[rel="shortcut icon"], link[rel="icon shortcut"], link[rel="shortcut"], link[rel="icon"]',
+ ).first
+ favicon = favicon.nil? ? nil : (favicon["href"].nil? ? nil : favicon["href"].strip)
- Onebox::Helpers::get_absolute_image_url(favicon, url)
+ Onebox::Helpers.get_absolute_image_url(favicon, url)
end
def get_description
return nil unless html_doc
- description = html_doc.at("meta[name='description']").to_h['content']
- description ||= html_doc.at("meta[name='Description']").to_h['content']
+ description = html_doc.at("meta[name='description']").to_h["content"]
+ description ||= html_doc.at("meta[name='Description']").to_h["content"]
description
end
@@ -109,7 +117,11 @@ module Onebox
return "{}" if Onebox::Helpers.blank?(oembed_url)
- Onebox::Helpers.fetch_response(oembed_url) rescue "{}"
+ begin
+ Onebox::Helpers.fetch_response(oembed_url)
+ rescue StandardError
+ "{}"
+ end
rescue Errno::ECONNREFUSED, Net::HTTPError, Net::HTTPFatalError, MultiJson::LoadError
"{}"
end
@@ -158,7 +170,7 @@ module Onebox
def set_twitter_data_on_raw
twitter = get_twitter
- twitter.each { |k, v| @raw[k] ||= v unless Onebox::Helpers::blank?(v) }
+ twitter.each { |k, v| @raw[k] ||= v unless Onebox::Helpers.blank?(v) }
end
def set_oembed_data_on_raw
@@ -173,13 +185,13 @@ module Onebox
def set_favicon_data_on_raw
favicon = get_favicon
- @raw[:favicon] = favicon unless Onebox::Helpers::blank?(favicon)
+ @raw[:favicon] = favicon unless Onebox::Helpers.blank?(favicon)
end
def set_description_on_raw
unless @raw[:description]
description = get_description
- @raw[:description] = description unless Onebox::Helpers::blank?(description)
+ @raw[:description] = description unless Onebox::Helpers.blank?(description)
end
end
end
diff --git a/lib/onebox/engine/steam_store_onebox.rb b/lib/onebox/engine/steam_store_onebox.rb
index e39ab843424..2642bf0ef65 100644
--- a/lib/onebox/engine/steam_store_onebox.rb
+++ b/lib/onebox/engine/steam_store_onebox.rb
@@ -7,7 +7,7 @@ module Onebox
include StandardEmbed
always_https
- matches_regexp(/^https?:\/\/store\.steampowered\.com\/app\/\d+/)
+ matches_regexp(%r{^https?://store\.steampowered\.com/app/\d+})
requires_iframe_origins "https://store.steampowered.com"
def placeholder_html
@@ -24,7 +24,7 @@ module Onebox
end
def to_html
- iframe_url = @url[/https?:\/\/store\.steampowered\.com\/app\/\d+/].gsub("/app/", "/widget/")
+ iframe_url = @url[%r{https?://store\.steampowered\.com/app/\d+}].gsub("/app/", "/widget/")
escaped_src = ::Onebox::Helpers.normalize_url_for_output(iframe_url)
<<-HTML
diff --git a/lib/onebox/engine/trello_onebox.rb b/lib/onebox/engine/trello_onebox.rb
index c74b39f01ac..810ff5888b6 100644
--- a/lib/onebox/engine/trello_onebox.rb
+++ b/lib/onebox/engine/trello_onebox.rb
@@ -6,13 +6,13 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https:\/\/trello\.com\/[bc]\/\W*/)
+ matches_regexp(%r{^https://trello\.com/[bc]/\W*})
requires_iframe_origins "https://trello.com"
always_https
def to_html
src = "https://trello.com/#{match[:type]}/#{match[:key]}.html"
- height = match[:type] == 'b' ? 400 : 200
+ height = match[:type] == "b" ? 400 : 200
<<-HTML
<iframe src="#{src}" width="100%" height="#{height}" frameborder="0" style="border:0"></iframe>
diff --git a/lib/onebox/engine/twitch_clips_onebox.rb b/lib/onebox/engine/twitch_clips_onebox.rb
index 8c4fb525b63..022a4e50b2e 100644
--- a/lib/onebox/engine/twitch_clips_onebox.rb
+++ b/lib/onebox/engine/twitch_clips_onebox.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-require_relative '../mixins/twitch_onebox'
+require_relative "../mixins/twitch_onebox"
class Onebox::Engine::TwitchClipsOnebox
def self.twitch_regexp
- /^https?:\/\/clips\.twitch\.tv\/([a-zA-Z0-9_]+\/?[^#\?\/]+)/
+ %r{^https?://clips\.twitch\.tv/([a-zA-Z0-9_]+/?[^#\?/]+)}
end
include Onebox::Mixins::TwitchOnebox
diff --git a/lib/onebox/engine/twitch_stream_onebox.rb b/lib/onebox/engine/twitch_stream_onebox.rb
index f0e1d5d346c..ca339aea1f0 100644
--- a/lib/onebox/engine/twitch_stream_onebox.rb
+++ b/lib/onebox/engine/twitch_stream_onebox.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative '../mixins/twitch_onebox'
+require_relative "../mixins/twitch_onebox"
class Onebox::Engine::TwitchStreamOnebox
def self.twitch_regexp
diff --git a/lib/onebox/engine/twitch_video_onebox.rb b/lib/onebox/engine/twitch_video_onebox.rb
index 47fd2eefeb4..9312c6bd332 100644
--- a/lib/onebox/engine/twitch_video_onebox.rb
+++ b/lib/onebox/engine/twitch_video_onebox.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-require_relative '../mixins/twitch_onebox'
+require_relative "../mixins/twitch_onebox"
class Onebox::Engine::TwitchVideoOnebox
def self.twitch_regexp
- /^https?:\/\/(?:www\.)?twitch\.tv\/videos\/([0-9]+)/
+ %r{^https?://(?:www\.)?twitch\.tv/videos/([0-9]+)}
end
include Onebox::Mixins::TwitchOnebox
diff --git a/lib/onebox/engine/twitter_status_onebox.rb b/lib/onebox/engine/twitter_status_onebox.rb
index bdb94b5ebb1..c409e20071e 100644
--- a/lib/onebox/engine/twitter_status_onebox.rb
+++ b/lib/onebox/engine/twitter_status_onebox.rb
@@ -7,7 +7,9 @@ module Onebox
include LayoutSupport
include HTML
- matches_regexp(/^https?:\/\/(mobile\.|www\.)?twitter\.com\/.+?\/status(es)?\/\d+(\/(video|photo)\/\d?+)?+(\/?\?.*)?\/?$/)
+ matches_regexp(
+ %r{^https?://(mobile\.|www\.)?twitter\.com/.+?/status(es)?/\d+(/(video|photo)/\d?+)?+(/?\?.*)?/?$},
+ )
always_https
def self.===(other)
@@ -16,11 +18,11 @@ module Onebox
end
def http_params
- { 'User-Agent' => 'DiscourseBot/1.0' }
+ { "User-Agent" => "DiscourseBot/1.0" }
end
def to_html
- raw.present? ? super : ''
+ raw.present? ? super : ""
end
private
@@ -38,9 +40,7 @@ module Onebox
end
def raw
- if twitter_api_credentials_present?
- @raw ||= client.status(match[:id]).to_hash
- end
+ @raw ||= client.status(match[:id]).to_hash if twitter_api_credentials_present?
end
def access(*keys)
@@ -70,7 +70,7 @@ module Onebox
end
def avatar
- access(:user, :profile_image_url_https).sub('normal', '400x400')
+ access(:user, :profile_image_url_https).sub("normal", "400x400")
end
def likes
@@ -114,7 +114,7 @@ module Onebox
quoted_tweet: quoted_tweet,
quoted_full_name: quoted_full_name,
quoted_screen_name: quoted_screen_name,
- quoted_link: quoted_link
+ quoted_link: quoted_link,
}
end
end
diff --git a/lib/onebox/engine/typeform_onebox.rb b/lib/onebox/engine/typeform_onebox.rb
index 184aff5e02e..e94a8c07c1d 100644
--- a/lib/onebox/engine/typeform_onebox.rb
+++ b/lib/onebox/engine/typeform_onebox.rb
@@ -5,7 +5,7 @@ module Onebox
class TypeformOnebox
include Engine
- matches_regexp(/^https?:\/\/[a-z0-9\-_]+\.typeform\.com\/to\/[a-zA-Z0-9]+/)
+ matches_regexp(%r{^https?://[a-z0-9\-_]+\.typeform\.com/to/[a-zA-Z0-9]+})
requires_iframe_origins "https://*.typeform.com"
always_https
@@ -31,17 +31,17 @@ module Onebox
def build_typeform_src
escaped_src = ::Onebox::Helpers.normalize_url_for_output(@url)
- query_params = CGI::parse(URI::parse(escaped_src).query || '')
+ query_params = CGI.parse(URI.parse(escaped_src).query || "")
- return escaped_src if query_params.has_key?('typeform-embed')
+ return escaped_src if query_params.has_key?("typeform-embed")
if query_params.empty?
- escaped_src += '?' unless escaped_src.end_with?('?')
+ escaped_src += "?" unless escaped_src.end_with?("?")
else
- escaped_src += '&'
+ escaped_src += "&"
end
- escaped_src += 'typeform-embed=embed-widget'
+ escaped_src += "typeform-embed=embed-widget"
end
end
end
diff --git a/lib/onebox/engine/video_onebox.rb b/lib/onebox/engine/video_onebox.rb
index 7d6c282027c..b0483bfbd40 100644
--- a/lib/onebox/engine/video_onebox.rb
+++ b/lib/onebox/engine/video_onebox.rb
@@ -5,7 +5,7 @@ module Onebox
class VideoOnebox
include Engine
- matches_regexp(/^(https?:)?\/\/.*\.(mov|mp4|webm|ogv)(\?.*)?$/i)
+ matches_regexp(%r{^(https?:)?//.*\.(mov|mp4|webm|ogv)(\?.*)?$}i)
def always_https?
AllowlistedGenericOnebox.host_matches(uri, AllowlistedGenericOnebox.https_hosts)
@@ -13,7 +13,7 @@ module Onebox
def to_html
# Fix Dropbox image links
- if @url[/^https:\/\/www.dropbox.com\/s\//]
+ if @url[%r{^https://www.dropbox.com/s/}]
@url.sub!("https://www.dropbox.com", "https://dl.dropboxusercontent.com")
end
diff --git a/lib/onebox/engine/vimeo_onebox.rb b/lib/onebox/engine/vimeo_onebox.rb
index b9b689c90c3..4a684641e46 100644
--- a/lib/onebox/engine/vimeo_onebox.rb
+++ b/lib/onebox/engine/vimeo_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/(www\.)?vimeo\.com\/\d+(\/\w+)?\/?/)
+ matches_regexp(%r{^https?://(www\.)?vimeo\.com/\d+(/\w+)?/?})
requires_iframe_origins "https://player.vimeo.com"
always_https
@@ -15,9 +15,9 @@ module Onebox
end
def to_html
- video_src = Nokogiri::HTML5::fragment(oembed_data[:html]).at_css('iframe')&.[]("src")
+ video_src = Nokogiri::HTML5.fragment(oembed_data[:html]).at_css("iframe")&.[]("src")
video_src = "https://player.vimeo.com/video/#{oembed_data[:video_id]}" if video_src.blank?
- video_src = video_src.gsub('autoplay=1', '').chomp("?")
+ video_src = video_src.gsub("autoplay=1", "").chomp("?")
<<-HTML
<iframe
@@ -35,7 +35,7 @@ module Onebox
def oembed_data
response = Onebox::Helpers.fetch_response("https://vimeo.com/api/oembed.json?url=#{url}")
@oembed_data = Onebox::Helpers.symbolize_keys(::MultiJson.load(response))
- rescue
+ rescue StandardError
"{}"
end
diff --git a/lib/onebox/engine/wikimedia_onebox.rb b/lib/onebox/engine/wikimedia_onebox.rb
index c222f58bf91..5fc16d7ecbf 100644
--- a/lib/onebox/engine/wikimedia_onebox.rb
+++ b/lib/onebox/engine/wikimedia_onebox.rb
@@ -7,7 +7,7 @@ module Onebox
include LayoutSupport
include JSON
- matches_regexp(/^https?:\/\/commons\.wikimedia\.org\/wiki\/(File:.+)/)
+ matches_regexp(%r{^https?://commons\.wikimedia\.org/wiki/(File:.+)})
always_https
def self.priority
@@ -25,17 +25,17 @@ module Onebox
private
def match
- @match ||= @url.match(/^https?:\/\/commons\.wikimedia\.org\/wiki\/(?<name>File:.+)/)
+ @match ||= @url.match(%r{^https?://commons\.wikimedia\.org/wiki/(?<name>File:.+)})
end
def data
- first_page = raw['query']['pages'].first[1]
+ first_page = raw["query"]["pages"].first[1]
{
- link: first_page['imageinfo'].first['descriptionurl'],
- title: first_page['title'],
- image: first_page['imageinfo'].first['url'],
- thumbnail: first_page['imageinfo'].first['thumburl']
+ link: first_page["imageinfo"].first["descriptionurl"],
+ title: first_page["title"],
+ image: first_page["imageinfo"].first["url"],
+ thumbnail: first_page["imageinfo"].first["thumburl"],
}
end
end
diff --git a/lib/onebox/engine/wikipedia_onebox.rb b/lib/onebox/engine/wikipedia_onebox.rb
index 6d7d40424a0..725436f3bbe 100644
--- a/lib/onebox/engine/wikipedia_onebox.rb
+++ b/lib/onebox/engine/wikipedia_onebox.rb
@@ -7,7 +7,7 @@ module Onebox
include LayoutSupport
include HTML
- matches_regexp(/^https?:\/\/.*\.wikipedia\.(com|org)/)
+ matches_regexp(%r{^https?://.*\.wikipedia\.(com|org)})
always_https
private
@@ -19,7 +19,7 @@ module Onebox
# Detect section Hash in the url and retrive the related paragraphs. if no hash provided the first few paragraphs will be used
# Author Lidlanca
# Date 9/8/2014
- if (m_url_hash = @url.match(/#([^\/?]+)/)) # extract url hash
+ if (m_url_hash = @url.match(%r{#([^/?]+)})) # extract url hash
m_url_hash_name = m_url_hash[1]
end
@@ -37,7 +37,11 @@ module Onebox
# div tag is commonly used as an assets wraper in an article section. often as the first element holding an image.
# ul support will imporve the output generated for a section with a list as the main content (for example: an Author Bibliography, A musician Discography, etc)
first_p_found = nil
- while (((next_sibling = cur_element.next_sibling).name =~ /p|text|div|ul/) || first_p_found.nil?) do # from section header get the next sibling until it is a breaker tag
+ while (
+ ((next_sibling = cur_element.next_sibling).name =~ /p|text|div|ul/) ||
+ first_p_found.nil?
+ )
+ # from section header get the next sibling until it is a breaker tag
cur_element = next_sibling
if (cur_element.name == "p" || cur_element.name == "ul") #we treat a list as we detect a p to avoid showing
first_p_found = true
@@ -58,7 +62,13 @@ module Onebox
if paras[cnt].name == "ul" # Handle UL tag. Generate a textual ordered list (1.item | 2.item | 3.item). Unfortunately no newline allowed in output
li_index = 1
list_items = []
- paras[cnt].children.css("li").each { |li| list_items.push "#{li_index}." + li.inner_text ; li_index += 1 }
+ paras[cnt]
+ .children
+ .css("li")
+ .each do |li|
+ list_items.push "#{li_index}." + li.inner_text
+ li_index += 1
+ end
paragraph = (list_items.join " |\n ")[0..Onebox::LayoutSupport.max_text]
else
paragraph = paras[cnt].inner_text[0..Onebox::LayoutSupport.max_text]
@@ -70,12 +80,15 @@ module Onebox
end
end
- text = "#{text[0..Onebox::LayoutSupport.max_text]}..." if text.length > Onebox::LayoutSupport.max_text
+ text = "#{text[0..Onebox::LayoutSupport.max_text]}..." if text.length >
+ Onebox::LayoutSupport.max_text
result = {
link: link,
- title: raw.css("html body h1").inner_text + (section_title_text ? " | " + section_title_text : ""), #if a section sub title exists add it to the main article title
- description: text
+ title:
+ raw.css("html body h1").inner_text +
+ (section_title_text ? " | " + section_title_text : ""), #if a section sub title exists add it to the main article title
+ description: text,
}
img = raw.css(".image img")
diff --git a/lib/onebox/engine/wistia_onebox.rb b/lib/onebox/engine/wistia_onebox.rb
index c8fe3a2ae30..ad85d0731dc 100644
--- a/lib/onebox/engine/wistia_onebox.rb
+++ b/lib/onebox/engine/wistia_onebox.rb
@@ -6,7 +6,7 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/https?:\/\/(.+)?(wistia.com|wi.st)\/(medias|embed)\/.*/)
+ matches_regexp(%r{https?://(.+)?(wistia.com|wi.st)/(medias|embed)/.*})
requires_iframe_origins("https://fast.wistia.com", "https://fast.wistia.net")
always_https
diff --git a/lib/onebox/engine/xkcd_onebox.rb b/lib/onebox/engine/xkcd_onebox.rb
index b16c25b098a..171e7e5d620 100644
--- a/lib/onebox/engine/xkcd_onebox.rb
+++ b/lib/onebox/engine/xkcd_onebox.rb
@@ -7,7 +7,7 @@ module Onebox
include LayoutSupport
include JSON
- matches_regexp(/^https?:\/\/(www\.)?(m\.)?xkcd\.com\/\d+/)
+ matches_regexp(%r{^https?://(www\.)?(m\.)?xkcd\.com/\d+})
def url
"https://xkcd.com/#{match[:comic_id]}/info.0.json"
@@ -20,12 +20,7 @@ module Onebox
end
def data
- {
- link: @url,
- title: raw['safe_title'],
- image: raw['img'],
- description: raw['alt']
- }
+ { link: @url, title: raw["safe_title"], image: raw["img"], description: raw["alt"] }
end
end
end
diff --git a/lib/onebox/engine/youku_onebox.rb b/lib/onebox/engine/youku_onebox.rb
index 2b9234fd931..7b59fac693b 100644
--- a/lib/onebox/engine/youku_onebox.rb
+++ b/lib/onebox/engine/youku_onebox.rb
@@ -6,16 +6,16 @@ module Onebox
include Engine
include HTML
- matches_regexp(/^(https?:\/\/)?([\da-z\.-]+)(youku.com\/)(.)+\/?$/)
+ matches_regexp(%r{^(https?://)?([\da-z\.-]+)(youku.com/)(.)+/?$})
requires_iframe_origins "https://player.youku.com"
# Try to get the video ID. Works for URLs of the form:
# * http://v.youku.com/v_show/id_XNjM3MzAxNzc2.html
# * http://v.youku.com/v_show/id_XMTQ5MjgyMjMyOA==.html?from=y1.3-tech-index3-232-10183.89969-89963.3-1
def video_id
- match = uri.path.match(/\/v_show\/id_([a-zA-Z0-9_=\-]+)(\.html)?.*/)
+ match = uri.path.match(%r{/v_show/id_([a-zA-Z0-9_=\-]+)(\.html)?.*})
match && match[1]
- rescue
+ rescue StandardError
nil
end
diff --git a/lib/onebox/engine/youtube_onebox.rb b/lib/onebox/engine/youtube_onebox.rb
index 128df9b1656..b316746ee0a 100644
--- a/lib/onebox/engine/youtube_onebox.rb
+++ b/lib/onebox/engine/youtube_onebox.rb
@@ -6,11 +6,11 @@ module Onebox
include Engine
include StandardEmbed
- matches_regexp(/^https?:\/\/(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/.+$/)
+ matches_regexp(%r{^https?://(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)/.+$})
requires_iframe_origins "https://www.youtube.com"
always_https
- WIDTH ||= 480
+ WIDTH ||= 480
HEIGHT ||= 360
def parse_embed_response
@@ -21,16 +21,20 @@ module Onebox
@embed_doc ||= Onebox::Helpers.fetch_html_doc(embed_url)
begin
- script_tag = @embed_doc.xpath('//script').find { |tag| tag.to_s.include?('ytcfg.set') }.to_s
+ script_tag =
+ @embed_doc.xpath("//script").find { |tag| tag.to_s.include?("ytcfg.set") }.to_s
match = script_tag.to_s.match(/ytcfg\.set\((?<json>.*)\)/)
yt_json = ::JSON.parse(match[:json])
- renderer = ::JSON.parse(yt_json['PLAYER_VARS']['embedded_player_response'])['embedPreview']['thumbnailPreviewRenderer']
+ renderer =
+ ::JSON.parse(yt_json["PLAYER_VARS"]["embedded_player_response"])["embedPreview"][
+ "thumbnailPreviewRenderer"
+ ]
- title = renderer['title']['runs'].first['text']
+ title = renderer["title"]["runs"].first["text"]
image = "https://img.youtube.com/vi/#{video_id}/hqdefault.jpg"
- rescue
+ rescue StandardError
return
end
@@ -42,7 +46,7 @@ module Onebox
result = parse_embed_response
result ||= get_opengraph.data
- "<img src='#{result[:image]}' width='#{WIDTH}' height='#{HEIGHT}' title='#{CGI::escapeHTML(result[:title])}'>"
+ "<img src='#{result[:image]}' width='#{WIDTH}' height='#{HEIGHT}' title='#{CGI.escapeHTML(result[:title])}'>"
else
to_html
end
@@ -75,48 +79,44 @@ module Onebox
# for channel pages
html = Onebox::Engine::AllowlistedGenericOnebox.new(@url, @timeout).to_html
return if Onebox::Helpers.blank?(html)
- html.gsub!(/['"]\/\//, "https://")
+ html.gsub!(%r{['"]//}, "https://")
html
end
end
def video_title
- @video_title ||= begin
- result = parse_embed_response || get_opengraph.data
- result[:title]
- end
+ @video_title ||=
+ begin
+ result = parse_embed_response || get_opengraph.data
+ result[:title]
+ end
end
private
def video_id
- @video_id ||= begin
- id = nil
+ @video_id ||=
+ begin
+ id = nil
- # http://youtu.be/afyK1HSFfgw
- if uri.host["youtu.be"]
- id = uri.path[/\/([\w\-]+)/, 1]
- end
+ # http://youtu.be/afyK1HSFfgw
+ id = uri.path[%r{/([\w\-]+)}, 1] if uri.host["youtu.be"]
- # https://www.youtube.com/embed/vsF0K3Ou1v0
- if uri.path["/embed/"]
- id ||= uri.path[/\/embed\/([\w\-]+)/, 1]
- end
+ # https://www.youtube.com/embed/vsF0K3Ou1v0
+ id ||= uri.path[%r{/embed/([\w\-]+)}, 1] if uri.path["/embed/"]
- # https://www.youtube.com/shorts/wi2jAtpBl0Y
- if uri.path["/shorts/"]
- id ||= uri.path[/\/shorts\/([\w\-]+)/, 1]
- end
+ # https://www.youtube.com/shorts/wi2jAtpBl0Y
+ id ||= uri.path[%r{/shorts/([\w\-]+)}, 1] if uri.path["/shorts/"]
- # https://www.youtube.com/watch?v=Z0UISCEe52Y
- id ||= params['v']
+ # https://www.youtube.com/watch?v=Z0UISCEe52Y
+ id ||= params["v"]
- sanitize_yt_id(id)
- end
+ sanitize_yt_id(id)
+ end
end
def list_id
- @list_id ||= sanitize_yt_id(params['list'])
+ @list_id ||= sanitize_yt_id(params["list"])
end
def sanitize_yt_id(raw)
@@ -124,45 +124,44 @@ module Onebox
end
def embed_params
- p = { 'feature' => 'oembed', 'wmode' => 'opaque' }
+ p = { "feature" => "oembed", "wmode" => "opaque" }
- p['list'] = list_id if list_id
+ p["list"] = list_id if list_id
# Parse timestrings, and assign the result as a start= parameter
- start = if params['start']
- params['start']
- elsif params['t']
- params['t']
- elsif uri.fragment && uri.fragment.start_with?('t=')
- # referencing uri is safe here because any throws were already caught by video_id returning nil
- # remove the t= from the start
- uri.fragment[2..-1]
- end
+ start =
+ if params["start"]
+ params["start"]
+ elsif params["t"]
+ params["t"]
+ elsif uri.fragment && uri.fragment.start_with?("t=")
+ # referencing uri is safe here because any throws were already caught by video_id returning nil
+ # remove the t= from the start
+ uri.fragment[2..-1]
+ end
- p['start'] = parse_timestring(start) if start
- p['end'] = parse_timestring params['end'] if params['end']
+ p["start"] = parse_timestring(start) if start
+ p["end"] = parse_timestring params["end"] if params["end"]
# Official workaround for looping videos
# https://developers.google.com/youtube/player_parameters#loop
# use params.include? so that you can just add "&loop"
- if params.include?('loop')
- p['loop'] = 1
- p['playlist'] = video_id
+ if params.include?("loop")
+ p["loop"] = 1
+ p["playlist"] = video_id
end
# https://developers.google.com/youtube/player_parameters#rel
- p['rel'] = 0 if params.include?('rel')
+ p["rel"] = 0 if params.include?("rel")
# https://developers.google.com/youtube/player_parameters#enablejsapi
- p['enablejsapi'] = params['enablejsapi'] if params.include?('enablejsapi')
+ p["enablejsapi"] = params["enablejsapi"] if params.include?("enablejsapi")
URI.encode_www_form(p)
end
def parse_timestring(string)
- if string =~ /(\d+h)?(\d+m)?(\d+s?)?/
- ($1.to_i * 3600) + ($2.to_i * 60) + $3.to_i
- end
+ ($1.to_i * 3600) + ($2.to_i * 60) + $3.to_i if string =~ /(\d+h)?(\d+m)?(\d+s?)?/
end
def params
@@ -173,12 +172,13 @@ module Onebox
# if one day it suddenly gave you an array.
#
# However, we aren't interested. Just take the first one.
- @params ||= begin
- p = {}
- CGI.parse(uri.query).each { |k, v| p[k] = v.first }
- p
- end
- rescue
+ @params ||=
+ begin
+ p = {}
+ CGI.parse(uri.query).each { |k, v| p[k] = v.first }
+ p
+ end
+ rescue StandardError
{}
end
end
diff --git a/lib/onebox/file_type_finder.rb b/lib/onebox/file_type_finder.rb
index 8ba4dc8c3f4..5d1ad772e45 100644
--- a/lib/onebox/file_type_finder.rb
+++ b/lib/onebox/file_type_finder.rb
@@ -18,7 +18,7 @@ module Onebox
".latex" => "tex",
".ru" => "rb",
".simplecov" => "rb", # Not official, but seems commonly found
- ".sty" => "tex"
+ ".sty" => "tex",
}
# Some extensionless files for which we know the type
@@ -29,12 +29,9 @@ module Onebox
# FIRST by their types and THEN by their names.
@extensionless_files = {
"cmake.in" => "cmake",
-
"gruntfile" => "js",
"gulpfile" => "js",
-
"artisan" => "php",
-
"berksfile" => "rb",
"capfile" => "rb",
"cheffile" => "rb",
@@ -44,8 +41,7 @@ module Onebox
"rakefile" => "rb",
"thorfile" => "rb",
"vagrantfile" => "rb",
-
- "boxfile" => "yaml" # Not currently (2014-11) in Highlight.js
+ "boxfile" => "yaml", # Not currently (2014-11) in Highlight.js
}
def self.from_file_name(file_name)
@@ -53,9 +49,7 @@ module Onebox
# First check against the known lists of "special" files and extensions.
return @extensionless_files[lower_name] if @extensionless_files.has_key?(lower_name)
- @long_file_types.each { |extension, type|
- return type if lower_name.end_with?(extension)
- }
+ @long_file_types.each { |extension, type| return type if lower_name.end_with?(extension) }
# Otherwise, just split on the last ".",
# but add one so we don't return the "." itself.
diff --git a/lib/onebox/helpers.rb b/lib/onebox/helpers.rb
index 9067f7b263e..57ea939680a 100644
--- a/lib/onebox/helpers.rb
+++ b/lib/onebox/helpers.rb
@@ -4,10 +4,10 @@ require "addressable"
module Onebox
module Helpers
+ class DownloadTooLarge < StandardError
+ end
- class DownloadTooLarge < StandardError; end
-
- IGNORE_CANONICAL_DOMAINS ||= ['www.instagram.com', 'medium.com', 'youtube.com']
+ IGNORE_CANONICAL_DOMAINS ||= %w[www.instagram.com medium.com youtube.com]
def self.symbolize_keys(hash)
return {} if hash.nil?
@@ -21,26 +21,47 @@ module Onebox
end
def self.clean(html)
- html.gsub(/<[^>]+>/, ' ').gsub(/\n/, '')
+ html.gsub(/<[^>]+>/, " ").gsub(/\n/, "")
end
def self.fetch_html_doc(url, headers = nil, body_cacher = nil)
- response = (fetch_response(url, headers: headers, body_cacher: body_cacher) rescue nil)
- doc = Nokogiri::HTML(response)
+ response =
+ (
+ begin
+ fetch_response(url, headers: headers, body_cacher: body_cacher)
+ rescue StandardError
+ nil
+ end
+ )
+ doc = Nokogiri.HTML(response)
uri = Addressable::URI.parse(url)
ignore_canonical_tag = doc.at('meta[property="og:ignore_canonical"]')
- should_ignore_canonical = IGNORE_CANONICAL_DOMAINS.map { |hostname| uri.hostname.match?(hostname) }.any?
+ should_ignore_canonical =
+ IGNORE_CANONICAL_DOMAINS.map { |hostname| uri.hostname.match?(hostname) }.any?
- unless (ignore_canonical_tag && ignore_canonical_tag['content'].to_s == 'true') || should_ignore_canonical
+ unless (ignore_canonical_tag && ignore_canonical_tag["content"].to_s == "true") ||
+ should_ignore_canonical
# prefer canonical link
canonical_link = doc.at('//link[@rel="canonical"]/@href')
canonical_uri = Addressable::URI.parse(canonical_link)
- if canonical_link && canonical_uri && "#{canonical_uri.host}#{canonical_uri.path}" != "#{uri.host}#{uri.path}"
- uri = FinalDestination.new(canonical_link, Oneboxer.get_final_destination_options(canonical_link)).resolve
+ if canonical_link && canonical_uri &&
+ "#{canonical_uri.host}#{canonical_uri.path}" != "#{uri.host}#{uri.path}"
+ uri =
+ FinalDestination.new(
+ canonical_link,
+ Oneboxer.get_final_destination_options(canonical_link),
+ ).resolve
if uri.present?
- response = (fetch_response(uri.to_s, headers: headers, body_cacher: body_cacher) rescue nil)
- doc = Nokogiri::HTML(response) if response
+ response =
+ (
+ begin
+ fetch_response(uri.to_s, headers: headers, body_cacher: body_cacher)
+ rescue StandardError
+ nil
+ end
+ )
+ doc = Nokogiri.HTML(response) if response
end
end
end
@@ -48,32 +69,42 @@ module Onebox
doc
end
- def self.fetch_response(location, redirect_limit: 5, domain: nil, headers: nil, body_cacher: nil)
- redirect_limit = Onebox.options.redirect_limit if redirect_limit > Onebox.options.redirect_limit
+ def self.fetch_response(
+ location,
+ redirect_limit: 5,
+ domain: nil,
+ headers: nil,
+ body_cacher: nil
+ )
+ redirect_limit = Onebox.options.redirect_limit if redirect_limit >
+ Onebox.options.redirect_limit
- raise Net::HTTPError.new('HTTP redirect too deep', location) if redirect_limit == 0
+ raise Net::HTTPError.new("HTTP redirect too deep", location) if redirect_limit == 0
uri = Addressable::URI.parse(location)
uri = Addressable::URI.join(domain, uri) if !uri.host
- use_body_cacher = body_cacher && body_cacher.respond_to?('fetch_cached_response_body')
+ use_body_cacher = body_cacher && body_cacher.respond_to?("fetch_cached_response_body")
if use_body_cacher
response_body = body_cacher.fetch_cached_response_body(uri.to_s)
- if response_body.present?
- return response_body
- end
+ return response_body if response_body.present?
end
result = StringIO.new
- FinalDestination::HTTP.start(uri.host, uri.port, open_timeout: Onebox.options.connect_timeout, use_ssl: uri.normalized_scheme == 'https') do |http|
+ FinalDestination::HTTP.start(
+ uri.host,
+ uri.port,
+ open_timeout: Onebox.options.connect_timeout,
+ use_ssl: uri.normalized_scheme == "https",
+ ) do |http|
http.read_timeout = Onebox.options.timeout
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Work around path building bugs
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Work around path building bugs
headers ||= {}
- if Onebox.options.user_agent && !headers['User-Agent']
- headers['User-Agent'] = Onebox.options.user_agent
+ if Onebox.options.user_agent && !headers["User-Agent"]
+ headers["User-Agent"] = Onebox.options.user_agent
end
request = Net::HTTP::Get.new(uri.request_uri, headers)
@@ -81,11 +112,10 @@ module Onebox
size_bytes = Onebox.options.max_download_kb * 1024
http.request(request) do |response|
-
- if cookie = response.get_fields('set-cookie')
+ if cookie = response.get_fields("set-cookie")
# HACK: If this breaks again in the future, use HTTP::CookieJar from gem 'http-cookie'
# See test: it "does not send cookies to the wrong domain"
- redir_header = { 'Cookie' => cookie.join('; ') }
+ redir_header = { "Cookie" => cookie.join("; ") }
end
redir_header = nil unless redir_header.is_a? Hash
@@ -94,11 +124,13 @@ module Onebox
unless code === 200
response.error! unless [301, 302, 303, 307, 308].include?(code)
- return fetch_response(
- response['location'],
- redirect_limit: redirect_limit - 1,
- domain: "#{uri.scheme}://#{uri.host}",
- headers: redir_header
+ return(
+ fetch_response(
+ response["location"],
+ redirect_limit: redirect_limit - 1,
+ domain: "#{uri.scheme}://#{uri.host}",
+ headers: redir_header,
+ )
)
end
@@ -120,7 +152,12 @@ module Onebox
def self.fetch_content_length(location)
uri = URI(location)
- FinalDestination::HTTP.start(uri.host, uri.port, open_timeout: Onebox.options.connect_timeout, use_ssl: uri.is_a?(URI::HTTPS)) do |http|
+ FinalDestination::HTTP.start(
+ uri.host,
+ uri.port,
+ open_timeout: Onebox.options.connect_timeout,
+ use_ssl: uri.is_a?(URI::HTTPS),
+ ) do |http|
http.read_timeout = Onebox.options.timeout
if uri.is_a?(URI::HTTPS)
http.use_ssl = true
@@ -129,30 +166,24 @@ module Onebox
http.request_head([uri.path, uri.query].join("?")) do |response|
code = response.code.to_i
- unless code === 200 || Onebox::Helpers.blank?(response.content_length)
- return nil
- end
+ return nil unless code === 200 || Onebox::Helpers.blank?(response.content_length)
return response.content_length
end
end
end
def self.pretty_filesize(size)
- conv = [ 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB' ]
+ conv = %w[B KB MB GB TB PB EB]
scale = 1024
ndx = 1
- if (size < 2 * (scale**ndx)) then
- return "#{(size)} #{conv[ndx - 1]}"
- end
+ return "#{(size)} #{conv[ndx - 1]}" if (size < 2 * (scale**ndx))
size = size.to_f
[2, 3, 4, 5, 6, 7].each do |i|
- if (size < 2 * (scale**i)) then
- return "#{'%.2f' % (size / (scale**(i - 1)))} #{conv[i - 1]}"
- end
+ return "#{"%.2f" % (size / (scale**(i - 1)))} #{conv[i - 1]}" if (size < 2 * (scale**i))
end
ndx = 7
- "#{'%.2f' % (size / (scale**(ndx - 1)))} #{conv[ndx - 1]}"
+ "#{"%.2f" % (size / (scale**(ndx - 1)))} #{conv[ndx - 1]}"
end
def self.click_to_scroll_div(width = 690, height = 400)
@@ -187,7 +218,7 @@ module Onebox
return "" unless url
url = url.dup
# expect properly encoded url, remove any unsafe chars
- url.gsub!(' ', '%20')
+ url.gsub!(" ", "%20")
url.gsub!("'", "&apos;")
url.gsub!('"', "&quot;")
url.gsub!(/[^\w\-`.~:\/?#\[\]@!$&'\(\)*+,;=%\p{M}’]/, "")
@@ -212,13 +243,34 @@ module Onebox
uri = Addressable::URI.parse(url)
- encoded_uri = Addressable::URI.new(
- scheme: Addressable::URI.encode_component(uri.scheme, Addressable::URI::CharacterClasses::SCHEME),
- authority: Addressable::URI.encode_component(uri.authority, Addressable::URI::CharacterClasses::AUTHORITY),
- path: Addressable::URI.encode_component(uri.path, Addressable::URI::CharacterClasses::PATH + "\\%"),
- query: Addressable::URI.encode_component(uri.query, "a-zA-Z0-9\\-\\.\\_\\~\\$\\&\\*\\,\\=\\:\\@\\?\\%"),
- fragment: Addressable::URI.encode_component(uri.fragment, "a-zA-Z0-9\\-\\.\\_\\~\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=\\:\\/\\?\\%")
- )
+ encoded_uri =
+ Addressable::URI.new(
+ scheme:
+ Addressable::URI.encode_component(
+ uri.scheme,
+ Addressable::URI::CharacterClasses::SCHEME,
+ ),
+ authority:
+ Addressable::URI.encode_component(
+ uri.authority,
+ Addressable::URI::CharacterClasses::AUTHORITY,
+ ),
+ path:
+ Addressable::URI.encode_component(
+ uri.path,
+ Addressable::URI::CharacterClasses::PATH + "\\%",
+ ),
+ query:
+ Addressable::URI.encode_component(
+ uri.query,
+ "a-zA-Z0-9\\-\\.\\_\\~\\$\\&\\*\\,\\=\\:\\@\\?\\%",
+ ),
+ fragment:
+ Addressable::URI.encode_component(
+ uri.fragment,
+ "a-zA-Z0-9\\-\\.\\_\\~\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=\\:\\/\\?\\%",
+ ),
+ )
encoded_uri.to_s
end
diff --git a/lib/onebox/json_ld.rb b/lib/onebox/json_ld.rb
index 9a70401daea..b9137b96bdd 100644
--- a/lib/onebox/json_ld.rb
+++ b/lib/onebox/json_ld.rb
@@ -13,22 +13,24 @@ module Onebox
private
def extract(doc)
- return {} if Onebox::Helpers::blank?(doc)
-
- doc.css('script[type="application/ld+json"]').each do |element|
- parsed_json = parse_json(element.text)
-
- if parsed_json.kind_of?(Array)
- parsed_json = parsed_json.detect { |x| SUPPORTED_TYPES.include?(x["@type"]) }
- return {} if !parsed_json
+ return {} if Onebox::Helpers.blank?(doc)
+
+ doc
+ .css('script[type="application/ld+json"]')
+ .each do |element|
+ parsed_json = parse_json(element.text)
+
+ if parsed_json.kind_of?(Array)
+ parsed_json = parsed_json.detect { |x| SUPPORTED_TYPES.include?(x["@type"]) }
+ return {} if !parsed_json
+ end
+
+ case parsed_json["@type"]
+ when MOVIE_JSON_LD_TYPE
+ return Onebox::Movie.new(parsed_json).to_h
+ end
end
- case parsed_json["@type"]
- when MOVIE_JSON_LD_TYPE
- return Onebox::Movie.new(parsed_json).to_h
- end
- end
-
{}
end
diff --git a/lib/onebox/layout.rb b/lib/onebox/layout.rb
index a697ba24f07..e6e31daa6f9 100644
--- a/lib/onebox/layout.rb
+++ b/lib/onebox/layout.rb
@@ -15,7 +15,7 @@ module Onebox
@record = Onebox::Helpers.symbolize_keys(record)
# Fix any relative paths
- if @record[:image] && @record[:image] =~ /^\/[^\/]/
+ if @record[:image] && @record[:image] =~ %r{^/[^/]}
@record[:image] = "#{uri.scheme}://#{uri.host}/#{@record[:image]}"
end
@@ -40,7 +40,7 @@ module Onebox
link: record[:link],
title: record[:title],
favicon: record[:favicon],
- domain: record[:domain] || uri.host.to_s.sub(/^www\./, ''),
+ domain: record[:domain] || uri.host.to_s.sub(/^www\./, ""),
article_published_time: record[:article_published_time],
article_published_time_title: record[:article_published_time_title],
metadata_1_label: record[:metadata_1_label],
@@ -48,7 +48,7 @@ module Onebox
metadata_2_label: record[:metadata_2_label],
metadata_2_value: record[:metadata_2_value],
subname: view.template_name,
- view: view.to_html
+ view: view.to_html,
}
end
end
diff --git a/lib/onebox/layout_support.rb b/lib/onebox/layout_support.rb
index dcec7cf287c..aa8f6c9bac2 100644
--- a/lib/onebox/layout_support.rb
+++ b/lib/onebox/layout_support.rb
@@ -2,7 +2,6 @@
module Onebox
module LayoutSupport
-
def self.max_text
500
end
diff --git a/lib/onebox/matcher.rb b/lib/onebox/matcher.rb
index 1bfbc7a06e1..2f4b7fc3ffa 100644
--- a/lib/onebox/matcher.rb
+++ b/lib/onebox/matcher.rb
@@ -12,9 +12,8 @@ module Onebox
end
def ordered_engines
- @ordered_engines ||= Engine.engines.sort_by do |e|
- e.respond_to?(:priority) ? e.priority : 100
- end
+ @ordered_engines ||=
+ Engine.engines.sort_by { |e| e.respond_to?(:priority) ? e.priority : 100 }
end
def oneboxed
@@ -24,8 +23,8 @@ module Onebox
ordered_engines.find do |engine|
(
- engine.respond_to?(:handles_content_type?) && engine.handles_content_type?(@options[:content_type]) ||
- engine === @uri
+ engine.respond_to?(:handles_content_type?) &&
+ engine.handles_content_type?(@options[:content_type]) || engine === @uri
) && has_allowed_iframe_origins?(engine)
end
end
diff --git a/lib/onebox/mixins/git_blob_onebox.rb b/lib/onebox/mixins/git_blob_onebox.rb
index 073f0fd27c0..511a6b60849 100644
--- a/lib/onebox/mixins/git_blob_onebox.rb
+++ b/lib/onebox/mixins/git_blob_onebox.rb
@@ -21,7 +21,7 @@ module Onebox
LINES_AFTER: 10,
SHOW_LINE_NUMBER: true,
MAX_LINES: 20,
- MAX_CHARS: 5000
+ MAX_CHARS: 5000,
}
module InstanceMethods
@@ -44,7 +44,8 @@ module Onebox
if constant_name_u == constant_name.to_s
#define a constant if not already defined
unless self.class.const_defined? constant_name_u.to_sym
- Onebox::Mixins::GitBlobOnebox.const_set constant_name_u.to_sym , options[constant_name_u.to_sym]
+ Onebox::Mixins::GitBlobOnebox.const_set constant_name_u.to_sym,
+ options[constant_name_u.to_sym]
end
end
end
@@ -54,61 +55,61 @@ module Onebox
def calc_range(m, contents_lines_size)
truncated = false
- from = /\d+/.match(m[:from]) #get numeric should only match a positive interger
- to = /\d+/.match(m[:to]) #get numeric should only match a positive interger
+ from = /\d+/.match(m[:from]) #get numeric should only match a positive interger
+ to = /\d+/.match(m[:to]) #get numeric should only match a positive interger
range_provided = !(from.nil? && to.nil?) #true if "from" or "to" provided in URL
- from = from.nil? ? 1 : from[0].to_i #if from not provided default to 1st line
- to = to.nil? ? -1 : to[0].to_i #if to not provided default to undefiend to be handled later in the logic
+ from = from.nil? ? 1 : from[0].to_i #if from not provided default to 1st line
+ to = to.nil? ? -1 : to[0].to_i #if to not provided default to undefiend to be handled later in the logic
- if to === -1 && range_provided #case "from" exists but no valid "to". aka ONE_LINER
+ if to === -1 && range_provided #case "from" exists but no valid "to". aka ONE_LINER
one_liner = true
to = from
else
one_liner = false
end
- unless range_provided #case no range provided default to 1..MAX_LINES
+ unless range_provided #case no range provided default to 1..MAX_LINES
from = 1
- to = MAX_LINES
+ to = MAX_LINES
truncated = true if contents_lines_size > MAX_LINES
#we can technically return here
end
- from, to = [from, to].sort #enforce valid range. [from < to]
- from = 1 if from > contents_lines_size #if "from" out of TOP bound set to 1st line
- to = contents_lines_size if to > contents_lines_size #if "to" is out of TOP bound set to last line.
+ from, to = [from, to].sort #enforce valid range. [from < to]
+ from = 1 if from > contents_lines_size #if "from" out of TOP bound set to 1st line
+ to = contents_lines_size if to > contents_lines_size #if "to" is out of TOP bound set to last line.
if one_liner
@selected_one_liner = from
if EXPAND_ONE_LINER != EXPAND_NONE
if (EXPAND_ONE_LINER & EXPAND_BEFORE != 0) # check if EXPAND_BEFORE flag is on
- from = [1, from - LINES_BEFORE].max # make sure expand before does not go out of bound
+ from = [1, from - LINES_BEFORE].max # make sure expand before does not go out of bound
end
- if (EXPAND_ONE_LINER & EXPAND_AFTER != 0) # check if EXPAND_FLAG flag is on
+ if (EXPAND_ONE_LINER & EXPAND_AFTER != 0) # check if EXPAND_FLAG flag is on
to = [to + LINES_AFTER, contents_lines_size].min # make sure expand after does not go out of bound
end
- from = contents_lines_size if from > contents_lines_size #if "from" is out of the content top bound
+ from = contents_lines_size if from > contents_lines_size #if "from" is out of the content top bound
# to = contents_lines_size if to > contents_lines_size #if "to" is out of the content top bound
else
#no expand show the one liner solely
end
end
- if to - from > MAX_LINES && !one_liner #if exceed the MAX_LINES limit correct unless range was produced by one_liner which it expand setting will allow exceeding the line limit
+ if to - from > MAX_LINES && !one_liner #if exceed the MAX_LINES limit correct unless range was produced by one_liner which it expand setting will allow exceeding the line limit
truncated = true
- to = from + MAX_LINES - 1
+ to = from + MAX_LINES - 1
end
{
- from: from, #calculated from
- from_minus_one: from - 1, #used for getting currect ol>li numbering with css used in template
- to: to, #calculated to
- one_liner: one_liner, #boolean if a one-liner
- selected_one_liner: @selected_one_liner, #if a one liner is provided we create a reference for it.
- range_provided: range_provided, #boolean if range provided
- truncated: truncated
+ from: from, #calculated from
+ from_minus_one: from - 1, #used for getting currect ol>li numbering with css used in template
+ to: to, #calculated to
+ one_liner: one_liner, #boolean if a one-liner
+ selected_one_liner: @selected_one_liner, #if a one liner is provided we create a reference for it.
+ range_provided: range_provided, #boolean if range provided
+ truncated: truncated,
}
end
@@ -117,23 +118,21 @@ module Onebox
min_space = 100
a_lines = str.lines
a_lines.each do |l|
- l = l.chomp("\n") # remove new line
+ l = l.chomp("\n") # remove new line
m = l.match(/^[ ]*/) # find leading spaces 0 or more
unless m.nil? || l.size == m[0].size || l.size == 0 # no match | only spaces in line | empty line
m_str_length = m[0].size
- if m_str_length <= 1 # minimum space is 1 or nothing we can break we found our minimum
+ if m_str_length <= 1 # minimum space is 1 or nothing we can break we found our minimum
min_space = m_str_length
break #stop iteration
end
- if m_str_length < min_space
- min_space = m_str_length
- end
+ min_space = m_str_length if m_str_length < min_space
else
next # SKIP no match or line is only spaces
end
end
a_lines.each do |l|
- re = Regexp.new "^[ ]{#{min_space}}" #match the minimum spaces of the line
+ re = Regexp.new "^[ ]{#{min_space}}" #match the minimum spaces of the line
l.gsub!(re, "")
end
a_lines.join
@@ -143,11 +142,15 @@ module Onebox
lines = removeLeadingIndentation(lines.join).lines # A little ineffeicent we could modify removeLeadingIndentation to accept array and return array, but for now it is only working with a string
hash_builder = []
output_builder = []
- lines.map.with_index { |line, i|
+ lines.map.with_index do |line, i|
lnum = (i.to_i + start)
- hash_builder.push(line_number: lnum, data: line.gsub("\n", ""), selected: (selected == lnum) ? true : false)
+ hash_builder.push(
+ line_number: lnum,
+ data: line.gsub("\n", ""),
+ selected: (selected == lnum) ? true : false,
+ )
output_builder.push "#{lnum}: #{line}"
- }
+ end
{ output: output_builder.join(), array: hash_builder }
end
@@ -157,13 +160,13 @@ module Onebox
m = @url.match(self.raw_regexp)
if m
- from = /\d+/.match(m[:from]) #get numeric should only match a positive interger
- to = /\d+/.match(m[:to]) #get numeric should only match a positive interger
+ from = /\d+/.match(m[:from]) #get numeric should only match a positive interger
+ to = /\d+/.match(m[:to]) #get numeric should only match a positive interger
@file = m[:file]
@lang = Onebox::FileTypeFinder.from_file_name(m[:file])
- if @lang == "stl" && link.match?(/^https?:\/\/(www\.)?github\.com.*\/blob\//)
+ if @lang == "stl" && link.match?(%r{^https?://(www\.)?github\.com.*/blob/})
@model_file = @lang.dup
@raw = "https://render.githubusercontent.com/view/solid?url=" + self.raw_template(m)
else
@@ -175,10 +178,10 @@ module Onebox
return
end
- contents_lines = contents.lines #get contents lines
+ contents_lines = contents.lines #get contents lines
contents_lines_size = contents_lines.size #get number of lines
- cr = calc_range(m, contents_lines_size) #calculate the range of lines for output
+ cr = calc_range(m, contents_lines_size) #calculate the range of lines for output
selected_one_liner = cr[:selected_one_liner] #if url is a one-liner calc_range will return it
from = cr[:from]
to = cr[:to]
@@ -186,20 +189,24 @@ module Onebox
range_provided = cr[:range_provided]
@cr_results = cr
- if range_provided #if a range provided (single line or more)
+ if range_provided #if a range provided (single line or more)
if SHOW_LINE_NUMBER
- lines_result = line_number_helper(contents_lines[(from - 1)..(to - 1)], from, selected_one_liner) #print code with prefix line numbers in case range provided
+ lines_result =
+ line_number_helper(
+ contents_lines[(from - 1)..(to - 1)],
+ from,
+ selected_one_liner,
+ ) #print code with prefix line numbers in case range provided
contents = lines_result[:output]
@selected_lines_array = lines_result[:array]
else
contents = contents_lines[(from - 1)..(to - 1)].join()
end
-
else
contents = contents_lines[(from - 1)..(to - 1)].join()
end
- if contents.length > MAX_CHARS #truncate content chars to limits
+ if contents.length > MAX_CHARS #truncate content chars to limits
contents = contents[0..MAX_CHARS]
@truncated = true
end
@@ -219,14 +226,14 @@ module Onebox
content: raw,
binary: @binary,
lang: "lang-#{@lang}",
- lines: @selected_lines_array ,
+ lines: @selected_lines_array,
has_lines: !@selected_lines_array.nil?,
selected_one_liner: @selected_one_liner,
cr_results: @cr_results,
truncated: @truncated,
model_file: @model_file,
width: 480,
- height: 360
+ height: 360,
}
end
end
diff --git a/lib/onebox/mixins/github_body.rb b/lib/onebox/mixins/github_body.rb
index f6c1e843561..b14de31a6be 100644
--- a/lib/onebox/mixins/github_body.rb
+++ b/lib/onebox/mixins/github_body.rb
@@ -14,7 +14,7 @@ module Onebox
def compute_body(body)
if body
- body = body.gsub(GITHUB_COMMENT_REGEX, '').strip
+ body = body.gsub(GITHUB_COMMENT_REGEX, "").strip
if body.length == 0
body = nil
elsif body.length > MAX_BODY_LENGTH
diff --git a/lib/onebox/movie.rb b/lib/onebox/movie.rb
index 645005615bd..702e3c0537f 100644
--- a/lib/onebox/movie.rb
+++ b/lib/onebox/movie.rb
@@ -7,29 +7,29 @@ module Onebox
end
def name
- @json_ld_data['name']
+ @json_ld_data["name"]
end
def image
- @json_ld_data['image']
+ @json_ld_data["image"]
end
def description
- @json_ld_data['description']
+ @json_ld_data["description"]
end
def rating
- @json_ld_data.dig('aggregateRating', 'ratingValue')
+ @json_ld_data.dig("aggregateRating", "ratingValue")
end
def genres
- @json_ld_data['genre']
+ @json_ld_data["genre"]
end
def duration
- return nil unless @json_ld_data['duration']
+ return nil unless @json_ld_data["duration"]
- Time.parse(@json_ld_data['duration']).strftime '%H:%M'
+ Time.parse(@json_ld_data["duration"]).strftime "%H:%M"
end
def to_h
@@ -39,7 +39,7 @@ module Onebox
description: description,
rating: rating,
genres: genres,
- duration: duration
+ duration: duration,
}
end
end
diff --git a/lib/onebox/normalizer.rb b/lib/onebox/normalizer.rb
index 3eafb635c0b..ac4c26b541a 100644
--- a/lib/onebox/normalizer.rb
+++ b/lib/onebox/normalizer.rb
@@ -5,11 +5,11 @@ module Onebox
attr_reader :data
def get(attr, length = nil, sanitize = true)
- return nil if Onebox::Helpers::blank?(data)
+ return nil if Onebox::Helpers.blank?(data)
value = data[attr]
- return nil if Onebox::Helpers::blank?(value)
+ return nil if Onebox::Helpers.blank?(value)
value = html_entities.decode(value)
value = Sanitize.fragment(value) if sanitize
@@ -22,14 +22,14 @@ module Onebox
def method_missing(attr, *args, &block)
value = get(attr, *args)
- return nil if Onebox::Helpers::blank?(value)
+ return nil if Onebox::Helpers.blank?(value)
method_name = attr.to_s
if method_name.end_with?(*integer_suffixes)
value.to_i
elsif method_name.end_with?(*url_suffixes)
result = Onebox::Helpers.normalize_url_for_output(value)
- result unless Onebox::Helpers::blank?(result)
+ result unless Onebox::Helpers.blank?(result)
else
value
end
@@ -38,11 +38,11 @@ module Onebox
private
def integer_suffixes
- ['width', 'height']
+ %w[width height]
end
def url_suffixes
- ['url', 'image', 'video']
+ %w[url image video]
end
def html_entities
diff --git a/lib/onebox/open_graph.rb b/lib/onebox/open_graph.rb
index 5aae110fb04..4fb25793472 100644
--- a/lib/onebox/open_graph.rb
+++ b/lib/onebox/open_graph.rb
@@ -2,7 +2,6 @@
module Onebox
class OpenGraph < Normalizer
-
def initialize(doc)
@data = extract(doc)
end
@@ -17,26 +16,29 @@ module Onebox
def secure_image_url
secure_url = URI(get(:image))
- secure_url.scheme = 'https'
+ secure_url.scheme = "https"
secure_url.to_s
end
private
def extract(doc)
- return {} if Onebox::Helpers::blank?(doc)
+ return {} if Onebox::Helpers.blank?(doc)
data = {}
- doc.css('meta').each do |m|
- if (m["property"] && m["property"][/^(?:og|article|product):(.+)$/i]) || (m["name"] && m["name"][/^(?:og|article|product):(.+)$/i])
- value = (m["content"] || m["value"]).to_s
- data[$1.tr('-:', '_').to_sym] ||= value unless Onebox::Helpers::blank?(value)
+ doc
+ .css("meta")
+ .each do |m|
+ if (m["property"] && m["property"][/^(?:og|article|product):(.+)$/i]) ||
+ (m["name"] && m["name"][/^(?:og|article|product):(.+)$/i])
+ value = (m["content"] || m["value"]).to_s
+ data[$1.tr("-:", "_").to_sym] ||= value unless Onebox::Helpers.blank?(value)
+ end
end
- end
# Attempt to retrieve the title from the meta tag
- title_element = doc.at_css('title')
+ title_element = doc.at_css("title")
if title_element && title_element.text
data[:title] ||= title_element.text unless Onebox::Helpers.blank?(title_element.text)
end
diff --git a/lib/onebox/preview.rb b/lib/onebox/preview.rb
index ade0dbe4809..1e387aacd5c 100644
--- a/lib/onebox/preview.rb
+++ b/lib/onebox/preview.rb
@@ -3,8 +3,15 @@
module Onebox
class Preview
# see https://bugs.ruby-lang.org/issues/14688
- client_exception = defined?(Net::HTTPClientException) ? Net::HTTPClientException : Net::HTTPServerException
- WEB_EXCEPTIONS ||= [client_exception, OpenURI::HTTPError, Timeout::Error, Net::HTTPError, Errno::ECONNREFUSED]
+ client_exception =
+ defined?(Net::HTTPClientException) ? Net::HTTPClientException : Net::HTTPServerException
+ WEB_EXCEPTIONS ||= [
+ client_exception,
+ OpenURI::HTTPError,
+ Timeout::Error,
+ Net::HTTPError,
+ Errno::ECONNREFUSED,
+ ]
def initialize(url, options = Onebox.options)
@url = url
@@ -59,20 +66,22 @@ module Onebox
return "" unless html
if @options[:max_width]
- doc = Nokogiri::HTML5::fragment(html)
+ doc = Nokogiri::HTML5.fragment(html)
if doc
- doc.css('[width]').each do |e|
- width = e['width'].to_i
-
- if width > @options[:max_width]
- height = e['height'].to_i
- if (height > 0)
- ratio = (height.to_f / width.to_f)
- e['height'] = (@options[:max_width] * ratio).floor
+ doc
+ .css("[width]")
+ .each do |e|
+ width = e["width"].to_i
+
+ if width > @options[:max_width]
+ height = e["height"].to_i
+ if (height > 0)
+ ratio = (height.to_f / width.to_f)
+ e["height"] = (@options[:max_width] * ratio).floor
+ end
+ e["width"] = @options[:max_width]
end
- e['width'] = @options[:max_width]
end
- end
return doc.to_html
end
end
@@ -96,6 +105,7 @@ module Onebox
@engine
end
- class InvalidURI < StandardError; end
+ class InvalidURI < StandardError
+ end
end
end
diff --git a/lib/onebox/sanitize_config.rb b/lib/onebox/sanitize_config.rb
index 592077a1860..49c552f05be 100644
--- a/lib/onebox/sanitize_config.rb
+++ b/lib/onebox/sanitize_config.rb
@@ -2,81 +2,106 @@
module Onebox
module SanitizeConfig
- HTTP_PROTOCOLS ||= ['http', 'https', :relative].freeze
+ HTTP_PROTOCOLS ||= ["http", "https", :relative].freeze
- ONEBOX ||= Sanitize::Config.freeze_config(Sanitize::Config.merge(Sanitize::Config::RELAXED,
- elements: Sanitize::Config::RELAXED[:elements] + %w[audio details embed iframe source video svg path],
-
- attributes: {
- 'a' => Sanitize::Config::RELAXED[:attributes]['a'] + %w(target),
- 'audio' => %w[controls controlslist],
- 'embed' => %w[height src type width],
- 'iframe' => %w[allowfullscreen frameborder height scrolling src width data-original-href data-unsanitized-src],
- 'source' => %w[src type],
- 'video' => %w[controls height loop width autoplay muted poster controlslist playsinline],
- 'path' => %w[d fill-rule],
- 'svg' => ['aria-hidden', 'width', 'height', 'viewbox'],
- 'div' => [:data], # any data-* attributes,
- 'span' => [:data], # any data-* attributes
- },
-
- add_attributes: {
- 'iframe' => {
- 'seamless' => 'seamless',
- 'sandbox' => 'allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox' \
- ' allow-presentation',
- }
- },
-
- transformers: (Sanitize::Config::RELAXED[:transformers] || []) + [
- lambda do |env|
- next unless env[:node_name] == 'a'
- a_tag = env[:node]
- a_tag['href'] ||= '#'
- if a_tag['href'] =~ %r{^(?:[a-z]+:)?//}
- a_tag['rel'] = 'nofollow ugc noopener'
- else
- a_tag.remove_attribute('target')
- end
- end,
-
- lambda do |env|
- next unless env[:node_name] == 'iframe'
-
- iframe = env[:node]
- allowed_regexes = env[:config][:allowed_iframe_regexes] || [/.*/]
-
- allowed = allowed_regexes.any? { |r| iframe["src"] =~ r }
+ ONEBOX ||=
+ Sanitize::Config.freeze_config(
+ Sanitize::Config.merge(
+ Sanitize::Config::RELAXED,
+ elements:
+ Sanitize::Config::RELAXED[:elements] +
+ %w[audio details embed iframe source video svg path],
+ attributes: {
+ "a" => Sanitize::Config::RELAXED[:attributes]["a"] + %w[target],
+ "audio" => %w[controls controlslist],
+ "embed" => %w[height src type width],
+ "iframe" => %w[
+ allowfullscreen
+ frameborder
+ height
+ scrolling
+ src
+ width
+ data-original-href
+ data-unsanitized-src
+ ],
+ "source" => %w[src type],
+ "video" => %w[
+ controls
+ height
+ loop
+ width
+ autoplay
+ muted
+ poster
+ controlslist
+ playsinline
+ ],
+ "path" => %w[d fill-rule],
+ "svg" => %w[aria-hidden width height viewbox],
+ "div" => [:data], # any data-* attributes,
+ "span" => [:data], # any data-* attributes
+ },
+ add_attributes: {
+ "iframe" => {
+ "seamless" => "seamless",
+ "sandbox" =>
+ "allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox" \
+ " allow-presentation",
+ },
+ },
+ transformers:
+ (Sanitize::Config::RELAXED[:transformers] || []) +
+ [
+ lambda do |env|
+ next unless env[:node_name] == "a"
+ a_tag = env[:node]
+ a_tag["href"] ||= "#"
+ if a_tag["href"] =~ %r{^(?:[a-z]+:)?//}
+ a_tag["rel"] = "nofollow ugc noopener"
+ else
+ a_tag.remove_attribute("target")
+ end
+ end,
+ lambda do |env|
+ next unless env[:node_name] == "iframe"
- if !allowed
- # add a data attribute with the blocked src. This is not required
- # but makes it much easier to troubleshoot onebox issues
- iframe["data-unsanitized-src"] = iframe["src"]
- iframe.remove_attribute("src")
- end
- end
- ],
+ iframe = env[:node]
+ allowed_regexes = env[:config][:allowed_iframe_regexes] || [/.*/]
- protocols: {
- 'embed' => { 'src' => HTTP_PROTOCOLS },
- 'iframe' => { 'src' => HTTP_PROTOCOLS },
- 'source' => { 'src' => HTTP_PROTOCOLS },
- },
+ allowed = allowed_regexes.any? { |r| iframe["src"] =~ r }
- css: {
- properties: Sanitize::Config::RELAXED[:css][:properties] + %w[--aspect-ratio]
- }
- ))
+ if !allowed
+ # add a data attribute with the blocked src. This is not required
+ # but makes it much easier to troubleshoot onebox issues
+ iframe["data-unsanitized-src"] = iframe["src"]
+ iframe.remove_attribute("src")
+ end
+ end,
+ ],
+ protocols: {
+ "embed" => {
+ "src" => HTTP_PROTOCOLS,
+ },
+ "iframe" => {
+ "src" => HTTP_PROTOCOLS,
+ },
+ "source" => {
+ "src" => HTTP_PROTOCOLS,
+ },
+ },
+ css: {
+ properties: Sanitize::Config::RELAXED[:css][:properties] + %w[--aspect-ratio],
+ },
+ ),
+ )
DISCOURSE_ONEBOX ||=
Sanitize::Config.freeze_config(
Sanitize::Config.merge(
ONEBOX,
- attributes: Sanitize::Config.merge(
- ONEBOX[:attributes],
- 'aside' => [:data]
- )
- )
+ attributes: Sanitize::Config.merge(ONEBOX[:attributes], "aside" => [:data]),
+ ),
)
end
end
diff --git a/lib/oneboxer.rb b/lib/oneboxer.rb
index cd9e8115b86..2427b9b9b3c 100644
--- a/lib/oneboxer.rb
+++ b/lib/oneboxer.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
Dir["#{Rails.root}/lib/onebox/engine/*_onebox.rb"].sort.each { |f| require f }
@@ -10,38 +10,69 @@ module Oneboxer
VIDEO_REGEX = /^\.(mov|mp4|webm|m4v|3gp|ogv|avi|mpeg|ogv)$/i
# keep reloaders happy
- unless defined? Oneboxer::Result
- Result = Struct.new(:doc, :changed) do
- def to_html
- doc.to_html
- end
+ unless defined?(Oneboxer::Result)
+ Result =
+ Struct.new(:doc, :changed) do
+ def to_html
+ doc.to_html
+ end
- def changed?
- changed
+ def changed?
+ changed
+ end
end
- end
end
def self.ignore_redirects
- @ignore_redirects ||= ['http://www.dropbox.com', 'http://store.steampowered.com', 'http://vimeo.com', 'https://www.youtube.com', Discourse.base_url]
+ @ignore_redirects ||= [
+ "http://www.dropbox.com",
+ "http://store.steampowered.com",
+ "http://vimeo.com",
+ "https://www.youtube.com",
+ Discourse.base_url,
+ ]
end
def self.amazon_domains
- amazon_suffixes = %w(com com.br ca cn fr de in it co.jp com.mx nl pl sa sg es se com.tr ae co.uk)
+ amazon_suffixes = %w[
+ com
+ com.br
+ ca
+ cn
+ fr
+ de
+ in
+ it
+ co.jp
+ com.mx
+ nl
+ pl
+ sa
+ sg
+ es
+ se
+ com.tr
+ ae
+ co.uk
+ ]
amazon_suffixes.collect { |suffix| "https://www.amazon.#{suffix}" }
end
def self.force_get_hosts
hosts = []
- hosts += SiteSetting.force_get_hosts.split('|').collect { |domain| "https://#{domain}" }
- hosts += SiteSetting.cache_onebox_response_body_domains.split('|').collect { |domain| "https://www.#{domain}" }
+ hosts += SiteSetting.force_get_hosts.split("|").collect { |domain| "https://#{domain}" }
+ hosts +=
+ SiteSetting
+ .cache_onebox_response_body_domains
+ .split("|")
+ .collect { |domain| "https://www.#{domain}" }
hosts += amazon_domains
hosts.uniq
end
def self.force_custom_user_agent_hosts
- SiteSetting.force_custom_user_agent_hosts.split('|')
+ SiteSetting.force_custom_user_agent_hosts.split("|")
end
def self.allowed_post_types
@@ -97,7 +128,10 @@ module Oneboxer
uri = URI.parse(uri) if uri.is_a?(String)
if SiteSetting.cache_onebox_response_body?
- SiteSetting.cache_onebox_response_body_domains.split("|").any? { |domain| uri.hostname.ends_with?(domain) }
+ SiteSetting
+ .cache_onebox_response_body_domains
+ .split("|")
+ .any? { |domain| uri.hostname.ends_with?(domain) }
end
end
@@ -124,15 +158,51 @@ module Oneboxer
def self.each_onebox_link(doc, extra_paths: [])
onebox_links = doc.css("a.#{ONEBOX_CSS_CLASS}", *extra_paths)
if onebox_links.present?
- onebox_links.each do |link|
- yield(link['href'], link) if link['href'].present?
- end
+ onebox_links.each { |link| yield(link["href"], link) if link["href"].present? }
end
doc
end
- HTML5_BLOCK_ELEMENTS ||= %w{address article aside blockquote canvas center dd div dl dt fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li main nav noscript ol output p pre section table tfoot ul video}
+ HTML5_BLOCK_ELEMENTS ||= %w[
+ address
+ article
+ aside
+ blockquote
+ canvas
+ center
+ dd
+ div
+ dl
+ dt
+ fieldset
+ figcaption
+ figure
+ footer
+ form
+ h1
+ h2
+ h3
+ h4
+ h5
+ h6
+ header
+ hgroup
+ hr
+ li
+ main
+ nav
+ noscript
+ ol
+ output
+ p
+ pre
+ section
+ table
+ tfoot
+ ul
+ video
+ ]
def self.apply(string_or_doc, extra_paths: nil)
doc = string_or_doc
@@ -150,8 +220,9 @@ module Oneboxer
parent = element.parent
if parent&.node_name&.downcase == "p" &&
- parsed_onebox.children.any? { |child| HTML5_BLOCK_ELEMENTS.include?(child.node_name.downcase) }
-
+ parsed_onebox.children.any? { |child|
+ HTML5_BLOCK_ELEMENTS.include?(child.node_name.downcase)
+ }
siblings = parent.children
element_idx = siblings.find_index(element)
before_idx = first_significant_element_index(siblings, element_idx - 1, -1)
@@ -184,8 +255,13 @@ module Oneboxer
def self.first_significant_element_index(elements, index, step)
while index >= 0 && index < elements.size &&
- (elements[index].node_name.downcase == "br" ||
- (elements[index].node_name.downcase == "text" && elements[index].to_html.strip.blank?))
+ (
+ elements[index].node_name.downcase == "br" ||
+ (
+ elements[index].node_name.downcase == "text" &&
+ elements[index].to_html.strip.blank?
+ )
+ )
index = index + step
end
@@ -205,9 +281,10 @@ module Oneboxer
end
def self.engine(url)
- Onebox::Matcher.new(url, {
- allowed_iframe_regexes: Onebox::Engine.origins_to_regexes(allowed_iframe_origins)
- }).oneboxed
+ Onebox::Matcher.new(
+ url,
+ { allowed_iframe_regexes: Onebox::Engine.origins_to_regexes(allowed_iframe_origins) },
+ ).oneboxed
end
def self.recently_failed?(url)
@@ -252,10 +329,14 @@ module Oneboxer
html =
case route[:controller]
- when "uploads" then local_upload_html(url)
- when "topics" then local_topic_html(url, route, opts)
- when "users" then local_user_html(url, route)
- when "list" then local_category_html(url, route)
+ when "uploads"
+ local_upload_html(url)
+ when "topics"
+ local_topic_html(url, route, opts)
+ when "users"
+ local_user_html(url, route)
+ when "list"
+ local_category_html(url, route)
else
if handler = local_handlers[route[:controller]]
handler.call(url, route)
@@ -267,7 +348,7 @@ module Oneboxer
end
def self.local_upload_html(url)
- additional_controls = \
+ additional_controls =
if SiteSetting.disable_onebox_media_download_controls
"controlslist='nodownload'"
else
@@ -315,9 +396,14 @@ module Oneboxer
post_number = route[:post_number].to_i
- post = post_number > 1 ?
- topic.posts.where(post_number: post_number).first :
- topic.ordered_posts.first
+ post =
+ (
+ if post_number > 1
+ topic.posts.where(post_number: post_number).first
+ else
+ topic.ordered_posts.first
+ end
+ )
return if !post || post.hidden || !allowed_post_types.include?(post.post_type)
@@ -326,7 +412,8 @@ module Oneboxer
excerpt.gsub!(/[\r\n]+/, " ")
excerpt.gsub!("[/quote]", "[quote]") # don't break my quote
- quote = "[quote=\"#{post.user.username}, topic:#{topic.id}, post:#{post.post_number}\"]\n#{excerpt}\n[/quote]"
+ quote =
+ "[quote=\"#{post.user.username}, topic:#{topic.id}, post:#{post.post_number}\"]\n#{excerpt}\n[/quote]"
PrettyText.cook(quote)
else
@@ -335,9 +422,12 @@ module Oneboxer
post_number: post.post_number,
avatar: PrettyText.avatar_img(post.user.avatar_template_url, "tiny"),
original_url: url,
- title: PrettyText.unescape_emoji(CGI::escapeHTML(topic.title)),
+ title: PrettyText.unescape_emoji(CGI.escapeHTML(topic.title)),
category_html: CategoryBadge.html_for(topic.category),
- quote: PrettyText.unescape_emoji(post.excerpt(SiteSetting.post_onebox_maxlength, keep_svg: true)),
+ quote:
+ PrettyText.unescape_emoji(
+ post.excerpt(SiteSetting.post_onebox_maxlength, keep_svg: true),
+ ),
}
template = template("discourse_topic_onebox")
@@ -349,7 +439,6 @@ module Oneboxer
username = route[:username] || ""
if user = User.find_by(username_lower: username.downcase)
-
name = user.name if SiteSetting.enable_names
args = {
@@ -359,11 +448,11 @@ module Oneboxer
name: name,
bio: user.user_profile.bio_excerpt(230),
location: Onebox::Helpers.sanitize(user.user_profile.location),
- joined: I18n.t('joined'),
- created_at: user.created_at.strftime(I18n.t('datetime_formats.formats.date_only')),
+ joined: I18n.t("joined"),
+ created_at: user.created_at.strftime(I18n.t("datetime_formats.formats.date_only")),
website: user.user_profile.website,
website_name: UserSerializer.new(user).website_name,
- original_url: url
+ original_url: url,
}
Mustache.render(template("discourse_user_onebox"), args)
@@ -384,7 +473,8 @@ module Oneboxer
logo_url: category.uploaded_logo&.url,
description: category.description,
has_subcategories: category.subcategories.present?,
- subcategories: category.subcategories.collect { |sc| { name: sc.name, color: sc.color, url: sc.url } }
+ subcategories:
+ category.subcategories.collect { |sc| { name: sc.name, color: sc.color, url: sc.url } },
}
Mustache.render(template("discourse_category_onebox"), args)
@@ -392,107 +482,116 @@ module Oneboxer
end
def self.preserve_fragment_url_hosts
- @preserve_fragment_url_hosts ||= ['http://github.com']
+ @preserve_fragment_url_hosts ||= ["http://github.com"]
end
def self.allowed_iframe_origins
allowed = SiteSetting.allowed_onebox_iframes.split("|")
- if allowed.include?("*")
- allowed = Onebox::Engine.all_iframe_origins
- end
+ allowed = Onebox::Engine.all_iframe_origins if allowed.include?("*")
allowed += SiteSetting.allowed_iframes.split("|")
end
def self.external_onebox(url, available_strategies = nil)
- Discourse.cache.fetch(onebox_cache_key(url), expires_in: 1.day) do
- uri = URI(url)
- available_strategies ||= Oneboxer.ordered_strategies(uri.hostname)
- strategy = available_strategies.shift
+ Discourse
+ .cache
+ .fetch(onebox_cache_key(url), expires_in: 1.day) do
+ uri = URI(url)
+ available_strategies ||= Oneboxer.ordered_strategies(uri.hostname)
+ strategy = available_strategies.shift
+
+ max_redirects = 0 if SiteSetting.block_onebox_on_redirect
+ fd =
+ FinalDestination.new(
+ url,
+ get_final_destination_options(url, strategy).merge(
+ stop_at_blocked_pages: true,
+ max_redirects: max_redirects,
+ initial_https_redirect_ignore_limit: SiteSetting.block_onebox_on_redirect,
+ ),
+ )
+ uri = fd.resolve
+
+ return blank_onebox if fd.status == :blocked_page
+
+ if fd.status != :resolved
+ args = { link: url }
+ if fd.status == :invalid_address
+ args[:error_message] = I18n.t("errors.onebox.invalid_address", hostname: fd.hostname)
+ elsif (fd.status_code || uri.nil?) && available_strategies.present?
+ # Try a different oneboxing strategy, if we have any options left:
+ return external_onebox(url, available_strategies)
+ elsif fd.status_code
+ args[:error_message] = I18n.t(
+ "errors.onebox.error_response",
+ status_code: fd.status_code,
+ )
+ end
- if SiteSetting.block_onebox_on_redirect
- max_redirects = 0
- end
- fd = FinalDestination.new(
- url,
- get_final_destination_options(url, strategy).merge(
- stop_at_blocked_pages: true,
- max_redirects: max_redirects,
- initial_https_redirect_ignore_limit: SiteSetting.block_onebox_on_redirect
- )
- )
- uri = fd.resolve
-
- return blank_onebox if fd.status == :blocked_page
-
- if fd.status != :resolved
- args = { link: url }
- if fd.status == :invalid_address
- args[:error_message] = I18n.t("errors.onebox.invalid_address", hostname: fd.hostname)
- elsif (fd.status_code || uri.nil?) && available_strategies.present?
- # Try a different oneboxing strategy, if we have any options left:
- return external_onebox(url, available_strategies)
- elsif fd.status_code
- args[:error_message] = I18n.t("errors.onebox.error_response", status_code: fd.status_code)
+ error_box = blank_onebox
+ error_box[:preview] = preview_error_onebox(args)
+ return error_box
end
- error_box = blank_onebox
- error_box[:preview] = preview_error_onebox(args)
- return error_box
- end
-
- return blank_onebox if uri.blank?
-
- onebox_options = {
- max_width: 695,
- sanitize_config: Onebox::SanitizeConfig::DISCOURSE_ONEBOX,
- allowed_iframe_origins: allowed_iframe_origins,
- hostname: GlobalSetting.hostname,
- facebook_app_access_token: SiteSetting.facebook_app_access_token,
- disable_media_download_controls: SiteSetting.disable_onebox_media_download_controls,
- body_cacher: self,
- content_type: fd.content_type
- }
-
- onebox_options[:cookie] = fd.cookie if fd.cookie
-
- user_agent_override = SiteSetting.cache_onebox_user_agent if Oneboxer.cache_response_body?(url) && SiteSetting.cache_onebox_user_agent.present?
- onebox_options[:user_agent] = user_agent_override if user_agent_override
-
- preview_result = Onebox.preview(uri.to_s, onebox_options)
- result = {
- onebox: WordWatcher.censor(preview_result.to_s),
- preview: WordWatcher.censor(preview_result.placeholder_html.to_s)
- }
-
- # NOTE: Call preview_result.errors after calling placeholder_html
- if preview_result.errors.any?
- error_keys = preview_result.errors.keys
- skip_if_only_error = [:image]
- unless error_keys.length == 1 && skip_if_only_error.include?(error_keys.first)
- missing_attributes = error_keys.map(&:to_s).sort.join(I18n.t("word_connector.comma"))
- error_message = I18n.t("errors.onebox.missing_data", missing_attributes: missing_attributes, count: error_keys.size)
- args = preview_result.verified_data.merge(error_message: error_message)
-
- if result[:preview].blank?
- result[:preview] = preview_error_onebox(args)
- else
- doc = Nokogiri::HTML5::fragment(result[:preview])
- aside = doc.at('aside')
-
- if aside
- # Add an error message to the preview that was returned
- error_fragment = preview_error_onebox_fragment(args)
- aside.add_child(error_fragment)
- result[:preview] = doc.to_html
+ return blank_onebox if uri.blank?
+
+ onebox_options = {
+ max_width: 695,
+ sanitize_config: Onebox::SanitizeConfig::DISCOURSE_ONEBOX,
+ allowed_iframe_origins: allowed_iframe_origins,
+ hostname: GlobalSetting.hostname,
+ facebook_app_access_token: SiteSetting.facebook_app_access_token,
+ disable_media_download_controls: SiteSetting.disable_onebox_media_download_controls,
+ body_cacher: self,
+ content_type: fd.content_type,
+ }
+
+ onebox_options[:cookie] = fd.cookie if fd.cookie
+
+ user_agent_override = SiteSetting.cache_onebox_user_agent if Oneboxer.cache_response_body?(
+ url,
+ ) && SiteSetting.cache_onebox_user_agent.present?
+ onebox_options[:user_agent] = user_agent_override if user_agent_override
+
+ preview_result = Onebox.preview(uri.to_s, onebox_options)
+ result = {
+ onebox: WordWatcher.censor(preview_result.to_s),
+ preview: WordWatcher.censor(preview_result.placeholder_html.to_s),
+ }
+
+ # NOTE: Call preview_result.errors after calling placeholder_html
+ if preview_result.errors.any?
+ error_keys = preview_result.errors.keys
+ skip_if_only_error = [:image]
+ unless error_keys.length == 1 && skip_if_only_error.include?(error_keys.first)
+ missing_attributes = error_keys.map(&:to_s).sort.join(I18n.t("word_connector.comma"))
+ error_message =
+ I18n.t(
+ "errors.onebox.missing_data",
+ missing_attributes: missing_attributes,
+ count: error_keys.size,
+ )
+ args = preview_result.verified_data.merge(error_message: error_message)
+
+ if result[:preview].blank?
+ result[:preview] = preview_error_onebox(args)
+ else
+ doc = Nokogiri::HTML5.fragment(result[:preview])
+ aside = doc.at("aside")
+
+ if aside
+ # Add an error message to the preview that was returned
+ error_fragment = preview_error_onebox_fragment(args)
+ aside.add_child(error_fragment)
+ result[:preview] = doc.to_html
+ end
end
end
end
- end
- Oneboxer.cache_preferred_strategy(uri.hostname, strategy)
+ Oneboxer.cache_preferred_strategy(uri.hostname, strategy)
- result
- end
+ result
+ end
end
def self.preview_error_onebox(args, is_fragment = false)
@@ -526,7 +625,8 @@ module Oneboxer
def self.strategies
{
- default: {}, # don't override anything by default
+ default: {
+ }, # don't override anything by default
force_get_and_ua: {
force_get_host: true,
force_custom_user_agent_host: true,
@@ -561,14 +661,12 @@ module Oneboxer
force_get_hosts: force_get_hosts,
force_custom_user_agent_hosts: force_custom_user_agent_hosts,
preserve_fragment_url_hosts: preserve_fragment_url_hosts,
- timeout: 5
+ timeout: 5,
}
uri = URI(url)
- if strategy.blank?
- strategy = Oneboxer.ordered_strategies(uri.hostname).shift
- end
+ strategy = Oneboxer.ordered_strategies(uri.hostname).shift if strategy.blank?
if strategy && Oneboxer.strategies[strategy][:force_get_host]
fd_options[:force_get_hosts] = ["https://#{uri.hostname}"]
@@ -577,7 +675,9 @@ module Oneboxer
fd_options[:force_custom_user_agent_hosts] = ["https://#{uri.hostname}"]
end
- user_agent_override = SiteSetting.cache_onebox_user_agent if Oneboxer.cache_response_body?(url) && SiteSetting.cache_onebox_user_agent.present?
+ user_agent_override = SiteSetting.cache_onebox_user_agent if Oneboxer.cache_response_body?(
+ url,
+ ) && SiteSetting.cache_onebox_user_agent.present?
fd_options[:default_user_agent] = user_agent_override if user_agent_override
fd_options
diff --git a/lib/onpdiff.rb b/lib/onpdiff.rb
index 6c86a79327e..470b4174c85 100644
--- a/lib/onpdiff.rb
+++ b/lib/onpdiff.rb
@@ -4,7 +4,6 @@
# in https://publications.mpi-cbg.de/Wu_1990_6334.pdf
class ONPDiff
-
def initialize(a, b)
@a, @b = a, b
@m, @n = a.size, b.size
@@ -42,7 +41,7 @@ class ONPDiff
begin
p += 1
- return (@shortest_path = []) if p >= 1000
+ return(@shortest_path = []) if p >= 1000
k = -p
while k <= @delta - 1
@@ -57,7 +56,6 @@ class ONPDiff
end
fp[@delta + @offset] = snake(@delta, fp[@delta - 1 + @offset] + 1, fp[@delta + 1 + @offset])
-
end until fp[@delta + @offset] == @n
r = @path[@delta + @offset]
@@ -176,9 +174,7 @@ class ONPDiff
end
j = i + 1
- while j < ses.size && ses[j][1] == op_code
- j += 1
- end
+ j += 1 while j < ses.size && ses[j][1] == op_code
if j >= ses.size
paragraph_ses = paragraph_ses.concat(ses[i..j])
@@ -187,9 +183,7 @@ class ONPDiff
k = j
j -= 1
- while k < ses.size && ses[k][1] == opposite_op_code
- k += 1
- end
+ k += 1 while k < ses.size && ses[k][1] == opposite_op_code
k -= 1
num_before = j - i + 1
@@ -226,5 +220,4 @@ class ONPDiff
pairs
end
-
end
diff --git a/lib/pbkdf2.rb b/lib/pbkdf2.rb
index 933630fc1ba..5546e64d671 100644
--- a/lib/pbkdf2.rb
+++ b/lib/pbkdf2.rb
@@ -3,12 +3,11 @@
# Note: This logic was originally extracted from the Pbkdf2 gem to fix Ruby 2.0
# issues, but that gem has gone stale so we won't be returning to it.
-require 'openssl'
-require 'xorcist'
+require "openssl"
+require "xorcist"
class Pbkdf2
def self.hash_password(password, salt, iterations, algorithm = "sha256")
-
h = OpenSSL::Digest.new(algorithm)
u = ret = prf(h, password, salt + [1].pack("N"))
@@ -26,5 +25,4 @@ class Pbkdf2
def self.prf(hash_function, password, data)
OpenSSL::HMAC.digest(hash_function, password, data)
end
-
end
diff --git a/lib/permalink_constraint.rb b/lib/permalink_constraint.rb
index 2e049e6c7a7..9a9c24af08a 100644
--- a/lib/permalink_constraint.rb
+++ b/lib/permalink_constraint.rb
@@ -1,9 +1,7 @@
# frozen_string_literal: true
class PermalinkConstraint
-
def matches?(request)
Permalink.where(url: Permalink.normalize_url(request.fullpath)).exists?
end
-
end
diff --git a/lib/pinned_check.rb b/lib/pinned_check.rb
index eb9edcb84f8..980c0ee46fd 100644
--- a/lib/pinned_check.rb
+++ b/lib/pinned_check.rb
@@ -3,17 +3,12 @@
# Helps us determine whether a topic should be displayed as pinned or not,
# taking into account anonymous users and users who have dismissed it
class PinnedCheck
-
def self.unpinned?(topic, topic_user = nil)
- topic.pinned_at &&
- topic_user &&
- topic_user.cleared_pinned_at &&
- topic_user.cleared_pinned_at > topic.pinned_at
+ topic.pinned_at && topic_user && topic_user.cleared_pinned_at &&
+ topic_user.cleared_pinned_at > topic.pinned_at
end
def self.pinned?(topic, topic_user = nil)
- !!topic.pinned_at &&
- !unpinned?(topic, topic_user)
+ !!topic.pinned_at && !unpinned?(topic, topic_user)
end
-
end
diff --git a/lib/plain_text_to_markdown.rb b/lib/plain_text_to_markdown.rb
index 5cbe78a9347..8e582e6f365 100644
--- a/lib/plain_text_to_markdown.rb
+++ b/lib/plain_text_to_markdown.rb
@@ -25,7 +25,9 @@ class PlainTextToMarkdown
unless last_line_blank && current_line_blank
if line.quote_level > 0
quote_identifiers = ">" * line.quote_level
- markdown << quote_identifiers << "\n" unless line.quote_level >= last_quote_level || current_line_blank
+ unless line.quote_level >= last_quote_level || current_line_blank
+ markdown << quote_identifiers << "\n"
+ end
markdown << quote_identifiers
markdown << " " unless current_line_blank
else
@@ -112,7 +114,9 @@ class PlainTextToMarkdown
def merge_lines(line, previous_line)
return line if previous_line.nil? || line.text.blank?
return line if line.text == SIGNATURE_SEPARATOR || previous_line.text == SIGNATURE_SEPARATOR
- return line unless line.quote_level == previous_line.quote_level && previous_line.text.end_with?(" ")
+ unless line.quote_level == previous_line.quote_level && previous_line.text.end_with?(" ")
+ return line
+ end
previous_line.text = previous_line.text[0...-1] if @delete_flowed_space
previous_line.text += line.text
@@ -122,7 +126,8 @@ class PlainTextToMarkdown
# @param line [Line]
# @param previous_line [Line]
def classify_line_as_code!(line, previous_line)
- line.code_block = previous_line.code_block unless previous_line.nil? || previous_line.valid_code_block?
+ line.code_block = previous_line.code_block unless previous_line.nil? ||
+ previous_line.valid_code_block?
return unless line.text =~ /^\s{0,3}```/
if line.code_block.present?
@@ -148,9 +153,9 @@ class PlainTextToMarkdown
converted_text
end
- URL_REGEX ||= URI.regexp(%w{http https ftp mailto})
+ URL_REGEX ||= URI.regexp(%w[http https ftp mailto])
BEFORE ||= Regexp.escape(%Q|([<«"“'‘|)
- AFTER ||= Regexp.escape(%Q|)]>»"”'’|)
+ AFTER ||= Regexp.escape(%Q|)]>»"”'’|)
def replace_duplicate_links(text)
urls = Set.new
@@ -158,7 +163,10 @@ class PlainTextToMarkdown
urls.each do |url|
escaped = Regexp.escape(url)
- text.gsub!(Regexp.new(%Q|#{escaped}\s*[#{BEFORE}]?#{escaped}[#{AFTER}]?|, Regexp::IGNORECASE), url)
+ text.gsub!(
+ Regexp.new(%Q|#{escaped}\s*[#{BEFORE}]?#{escaped}[#{AFTER}]?|, Regexp::IGNORECASE),
+ url,
+ )
end
text
@@ -178,9 +186,7 @@ class PlainTextToMarkdown
urls = Set.new
text.scan(URL_REGEX) { urls << $& }
- hoisted = urls
- .map { |url| [SecureRandom.hex, url] }
- .to_h
+ hoisted = urls.map { |url| [SecureRandom.hex, url] }.to_h
hoisted.each { |h, url| text.gsub!(url, h) }
diff --git a/lib/plugin.rb b/lib/plugin.rb
index 6a788379a8d..44e90530a6a 100644
--- a/lib/plugin.rb
+++ b/lib/plugin.rb
@@ -5,25 +5,37 @@ module Plugin
begin
block.call
rescue => error
- plugins_directory = Rails.root + 'plugins'
+ plugins_directory = Rails.root + "plugins"
if error.backtrace && error.backtrace_locations
- plugin_path = error.backtrace_locations.lazy.map do |location|
- Pathname.new(location.absolute_path)
- .ascend
+ plugin_path =
+ error
+ .backtrace_locations
.lazy
- .find { |path| path.parent == plugins_directory }
- end.next
+ .map do |location|
+ Pathname
+ .new(location.absolute_path)
+ .ascend
+ .lazy
+ .find { |path| path.parent == plugins_directory }
+ end
+ .next
raise unless plugin_path
- stack_trace = error.backtrace.each_with_index.inject([]) do |messages, (line, index)|
- if index == 0
- messages << "#{line}: #{error} (#{error.class})"
- else
- messages << "\t#{index}: from #{line}"
- end
- end.reverse.join("\n")
+ stack_trace =
+ error
+ .backtrace
+ .each_with_index
+ .inject([]) do |messages, (line, index)|
+ if index == 0
+ messages << "#{line}: #{error} (#{error.class})"
+ else
+ messages << "\t#{index}: from #{line}"
+ end
+ end
+ .reverse
+ .join("\n")
STDERR.puts <<~TEXT
#{stack_trace}
diff --git a/lib/plugin/filter.rb b/lib/plugin/filter.rb
index 27a1a483a94..2307a0bd763 100644
--- a/lib/plugin/filter.rb
+++ b/lib/plugin/filter.rb
@@ -14,6 +14,5 @@ module Plugin
def self.apply(name, context, result)
manager.apply(name, context, result)
end
-
end
end
diff --git a/lib/plugin/filter_manager.rb b/lib/plugin/filter_manager.rb
index 7342197b759..ff9efe68f34 100644
--- a/lib/plugin/filter_manager.rb
+++ b/lib/plugin/filter_manager.rb
@@ -2,7 +2,6 @@
module Plugin
class FilterManager
-
def initialize
@map = {}
end
@@ -15,9 +14,7 @@ module Plugin
def apply(name, context, result)
if filters = @map[name]
- filters.each do |blk|
- result = blk.call(context, result)
- end
+ filters.each { |blk| result = blk.call(context, result) }
end
result
end
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index 350bd3a8d20..fc69c104760 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -1,9 +1,9 @@
# frozen_string_literal: true
-require 'digest/sha1'
-require 'fileutils'
-require 'plugin/metadata'
-require 'auth'
+require "digest/sha1"
+require "fileutils"
+require "plugin/metadata"
+require "auth"
class Plugin::CustomEmoji
CACHE_KEY ||= "plugin-emoji"
@@ -43,23 +43,23 @@ class Plugin::CustomEmoji
end
class Plugin::Instance
-
attr_accessor :path, :metadata
attr_reader :admin_route
# Memoized array readers
- [:assets,
- :color_schemes,
- :before_auth_initializers,
- :initializers,
- :javascripts,
- :locales,
- :service_workers,
- :styles,
- :themes,
- :csp_extensions,
- :asset_filters
- ].each do |att|
+ %i[
+ assets
+ color_schemes
+ before_auth_initializers
+ initializers
+ javascripts
+ locales
+ service_workers
+ styles
+ themes
+ csp_extensions
+ asset_filters
+ ].each do |att|
class_eval %Q{
def #{att}
@#{att} ||= []
@@ -76,14 +76,14 @@ class Plugin::Instance
end
def self.find_all(parent_path)
- [].tap { |plugins|
+ [].tap do |plugins|
# also follows symlinks - http://stackoverflow.com/q/357754
Dir["#{parent_path}/*/plugin.rb"].sort.each do |path|
source = File.read(path)
metadata = Plugin::Metadata.parse(source)
plugins << self.new(metadata, path)
end
- }
+ end
end
def initialize(metadata = nil, path = nil)
@@ -111,7 +111,12 @@ class Plugin::Instance
def add_to_serializer(serializer, attr, define_include_method = true, &block)
reloadable_patch do |plugin|
- base = "#{serializer.to_s.classify}Serializer".constantize rescue "#{serializer.to_s}Serializer".constantize
+ base =
+ begin
+ "#{serializer.to_s.classify}Serializer".constantize
+ rescue StandardError
+ "#{serializer.to_s}Serializer".constantize
+ end
# we have to work through descendants cause serializers may already be baked and cached
([base] + base.descendants).each do |klass|
@@ -131,9 +136,7 @@ class Plugin::Instance
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def add_report(name, &block)
- reloadable_patch do |plugin|
- Report.add_report(name, &block)
- end
+ reloadable_patch { |plugin| Report.add_report(name, &block) }
end
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
@@ -150,7 +153,11 @@ class Plugin::Instance
end
def whitelist_staff_user_custom_field(field)
- Discourse.deprecate("whitelist_staff_user_custom_field is deprecated, use the allow_staff_user_custom_field.", drop_from: "2.6", raise_error: true)
+ Discourse.deprecate(
+ "whitelist_staff_user_custom_field is deprecated, use the allow_staff_user_custom_field.",
+ drop_from: "2.6",
+ raise_error: true,
+ )
allow_staff_user_custom_field(field)
end
@@ -159,7 +166,11 @@ class Plugin::Instance
end
def whitelist_public_user_custom_field(field)
- Discourse.deprecate("whitelist_public_user_custom_field is deprecated, use the allow_public_user_custom_field.", drop_from: "2.6", raise_error: true)
+ Discourse.deprecate(
+ "whitelist_public_user_custom_field is deprecated, use the allow_public_user_custom_field.",
+ drop_from: "2.6",
+ raise_error: true,
+ )
allow_public_user_custom_field(field)
end
@@ -262,22 +273,23 @@ class Plugin::Instance
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def add_body_class(class_name)
- reloadable_patch do |plugin|
- ::ApplicationHelper.extra_body_classes << class_name
- end
+ reloadable_patch { |plugin| ::ApplicationHelper.extra_body_classes << class_name }
end
def rescue_from(exception, &block)
- reloadable_patch do |plugin|
- ::ApplicationController.rescue_from(exception, &block)
- end
+ reloadable_patch { |plugin| ::ApplicationController.rescue_from(exception, &block) }
end
# Extend a class but check that the plugin is enabled
# for class methods use `add_class_method`
def add_to_class(class_name, attr, &block)
reloadable_patch do |plugin|
- klass = class_name.to_s.classify.constantize rescue class_name.to_s.constantize
+ klass =
+ begin
+ class_name.to_s.classify.constantize
+ rescue StandardError
+ class_name.to_s.constantize
+ end
hidden_method_name = :"#{attr}_without_enable_check"
klass.public_send(:define_method, hidden_method_name, &block)
@@ -290,7 +302,12 @@ class Plugin::Instance
# Adds a class method to a class, respecting if plugin is enabled
def add_class_method(klass_name, attr, &block)
reloadable_patch do |plugin|
- klass = klass_name.to_s.classify.constantize rescue klass_name.to_s.constantize
+ klass =
+ begin
+ klass_name.to_s.classify.constantize
+ rescue StandardError
+ klass_name.to_s.constantize
+ end
hidden_method_name = :"#{attr}_without_enable_check"
klass.public_send(:define_singleton_method, hidden_method_name, &block)
@@ -303,7 +320,12 @@ class Plugin::Instance
def add_model_callback(klass_name, callback, options = {}, &block)
reloadable_patch do |plugin|
- klass = klass_name.to_s.classify.constantize rescue klass_name.to_s.constantize
+ klass =
+ begin
+ klass_name.to_s.classify.constantize
+ rescue StandardError
+ klass_name.to_s.constantize
+ end
# generate a unique method name
method_name = "#{plugin.name}_#{klass.name}_#{callback}#{@idx}".underscore
@@ -320,7 +342,11 @@ class Plugin::Instance
end
def topic_view_post_custom_fields_whitelister(&block)
- Discourse.deprecate("topic_view_post_custom_fields_whitelister is deprecated, use the topic_view_post_custom_fields_allowlister.", drop_from: "2.6", raise_error: true)
+ Discourse.deprecate(
+ "topic_view_post_custom_fields_whitelister is deprecated, use the topic_view_post_custom_fields_allowlister.",
+ drop_from: "2.6",
+ raise_error: true,
+ )
topic_view_post_custom_fields_allowlister(&block)
end
@@ -344,16 +370,12 @@ class Plugin::Instance
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def add_preloaded_group_custom_field(field)
- reloadable_patch do |plugin|
- ::Group.preloaded_custom_field_names << field
- end
+ reloadable_patch { |plugin| ::Group.preloaded_custom_field_names << field }
end
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def add_preloaded_topic_list_custom_field(field)
- reloadable_patch do |plugin|
- ::TopicList.preloaded_custom_fields << field
- end
+ reloadable_patch { |plugin| ::TopicList.preloaded_custom_fields << field }
end
# Add a permitted_create_param to Post, respecting if the plugin is enabled
@@ -420,7 +442,11 @@ class Plugin::Instance
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)
+ DirectoryColumn.find_or_create_plugin_directory_column(
+ column_name: column_name,
+ icon: icon,
+ query: query,
+ )
end
end
@@ -430,7 +456,7 @@ class Plugin::Instance
filenames = good_paths.map { |f| File.basename(f) }
# nuke old files
Dir.foreach(auto_generated_path) do |p|
- next if [".", ".."].include?(p)
+ next if %w[. ..].include?(p)
next if filenames.include?(p)
File.delete(auto_generated_path + "/#{p}")
end
@@ -438,9 +464,7 @@ class Plugin::Instance
def ensure_directory(path)
dirname = File.dirname(path)
- unless File.directory?(dirname)
- FileUtils.mkdir_p(dirname)
- end
+ FileUtils.mkdir_p(dirname) unless File.directory?(dirname)
end
def directory
@@ -456,15 +480,15 @@ class Plugin::Instance
end
def before_auth(&block)
- raise "Auth providers must be registered before omniauth middleware. after_initialize is too late!" if @before_auth_complete
+ if @before_auth_complete
+ raise "Auth providers must be registered before omniauth middleware. after_initialize is too late!"
+ end
before_auth_initializers << block
end
# A proxy to `DiscourseEvent.on` which does nothing if the plugin is disabled
def on(event_name, &block)
- DiscourseEvent.on(event_name) do |*args, **kwargs|
- block.call(*args, **kwargs) if enabled?
- end
+ DiscourseEvent.on(event_name) { |*args, **kwargs| block.call(*args, **kwargs) if enabled? }
end
def notify_after_initialize
@@ -487,45 +511,33 @@ class Plugin::Instance
end
def notify_before_auth
- before_auth_initializers.each do |callback|
- callback.call(self)
- end
+ before_auth_initializers.each { |callback| callback.call(self) }
@before_auth_complete = true
end
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def register_category_custom_field_type(name, type)
- reloadable_patch do |plugin|
- Category.register_custom_field_type(name, type)
- end
+ reloadable_patch { |plugin| Category.register_custom_field_type(name, type) }
end
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def register_topic_custom_field_type(name, type)
- reloadable_patch do |plugin|
- ::Topic.register_custom_field_type(name, type)
- end
+ reloadable_patch { |plugin| ::Topic.register_custom_field_type(name, type) }
end
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def register_post_custom_field_type(name, type)
- reloadable_patch do |plugin|
- ::Post.register_custom_field_type(name, type)
- end
+ reloadable_patch { |plugin| ::Post.register_custom_field_type(name, type) }
end
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def register_group_custom_field_type(name, type)
- reloadable_patch do |plugin|
- ::Group.register_custom_field_type(name, type)
- end
+ reloadable_patch { |plugin| ::Group.register_custom_field_type(name, type) }
end
# Applies to all sites in a multisite environment. Ignores plugin.enabled?
def register_user_custom_field_type(name, type)
- reloadable_patch do |plugin|
- ::User.register_custom_field_type(name, type)
- end
+ reloadable_patch { |plugin| ::User.register_custom_field_type(name, type) }
end
def register_seedfu_fixtures(paths)
@@ -586,12 +598,10 @@ class Plugin::Instance
end
def register_asset(file, opts = nil)
- if file.end_with?(".hbs", ".handlebars")
- raise <<~ERROR
+ 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
- end
if opts && opts == :vendored_core_pretty_text
full_path = DiscoursePluginRegistry.core_asset_for_name(file)
@@ -603,10 +613,7 @@ class Plugin::Instance
end
def register_service_worker(file, opts = nil)
- service_workers << [
- File.join(File.dirname(path), 'assets', file),
- opts
- ]
+ service_workers << [File.join(File.dirname(path), "assets", file), opts]
end
def register_color_scheme(name, colors)
@@ -638,8 +645,8 @@ class Plugin::Instance
js = "(function(){#{js}})();" if js.present?
result = []
- result << [css, 'css'] if css.present?
- result << [js, 'js'] if js.present?
+ result << [css, "css"] if css.present?
+ result << [js, "js"] if js.present?
result.map do |asset, extension|
hash = Digest::SHA1.hexdigest asset
@@ -656,22 +663,31 @@ class Plugin::Instance
# Automatically include all ES6 JS and hbs files
root_path = "#{root_dir_name}/assets/javascripts"
- DiscoursePluginRegistry.register_glob(root_path, 'js')
- DiscoursePluginRegistry.register_glob(root_path, 'js.es6')
- DiscoursePluginRegistry.register_glob(root_path, 'hbs')
- DiscoursePluginRegistry.register_glob(root_path, 'hbr')
+ DiscoursePluginRegistry.register_glob(root_path, "js")
+ DiscoursePluginRegistry.register_glob(root_path, "js.es6")
+ DiscoursePluginRegistry.register_glob(root_path, "hbs")
+ DiscoursePluginRegistry.register_glob(root_path, "hbr")
admin_path = "#{root_dir_name}/admin/assets/javascripts"
- DiscoursePluginRegistry.register_glob(admin_path, 'js', admin: true)
- DiscoursePluginRegistry.register_glob(admin_path, 'js.es6', admin: true)
- DiscoursePluginRegistry.register_glob(admin_path, 'hbs', admin: true)
- DiscoursePluginRegistry.register_glob(admin_path, 'hbr', admin: true)
-
- DiscourseJsProcessor.plugin_transpile_paths << root_path.sub(Rails.root.to_s, '').sub(/^\/*/, '')
- DiscourseJsProcessor.plugin_transpile_paths << admin_path.sub(Rails.root.to_s, '').sub(/^\/*/, '')
+ DiscoursePluginRegistry.register_glob(admin_path, "js", admin: true)
+ DiscoursePluginRegistry.register_glob(admin_path, "js.es6", admin: true)
+ DiscoursePluginRegistry.register_glob(admin_path, "hbs", admin: true)
+ DiscoursePluginRegistry.register_glob(admin_path, "hbr", admin: true)
+
+ DiscourseJsProcessor.plugin_transpile_paths << root_path.sub(Rails.root.to_s, "").sub(
+ %r{^/*},
+ "",
+ )
+ DiscourseJsProcessor.plugin_transpile_paths << admin_path.sub(Rails.root.to_s, "").sub(
+ %r{^/*},
+ "",
+ )
test_path = "#{root_dir_name}/test/javascripts"
- DiscourseJsProcessor.plugin_transpile_paths << test_path.sub(Rails.root.to_s, '').sub(/^\/*/, '')
+ DiscourseJsProcessor.plugin_transpile_paths << test_path.sub(Rails.root.to_s, "").sub(
+ %r{^/*},
+ "",
+ )
end
self.instance_eval File.read(path), path
@@ -683,9 +699,7 @@ class Plugin::Instance
register_locales!
register_service_workers!
- seed_data.each do |key, value|
- DiscoursePluginRegistry.register_seed_data(key, value)
- end
+ seed_data.each { |key, value| DiscoursePluginRegistry.register_seed_data(key, value) }
# TODO: possibly amend this to a rails engine
@@ -710,7 +724,7 @@ class Plugin::Instance
if Dir.exist?(public_data)
target = Rails.root.to_s + "/public/plugins/"
- Discourse::Utils.execute_command('mkdir', '-p', target)
+ Discourse::Utils.execute_command("mkdir", "-p", target)
target << name.gsub(/\s/, "_")
Discourse::Utils.atomic_ln_s(public_data, target)
@@ -752,12 +766,20 @@ class Plugin::Instance
begin
provider.authenticator.enabled?
rescue NotImplementedError
- provider.authenticator.define_singleton_method(:enabled?) do
- Discourse.deprecate("#{provider.authenticator.class.name} should define an `enabled?` function. Patching for now.", drop_from: '2.9.0')
- return SiteSetting.get(provider.enabled_setting) if provider.enabled_setting
- Discourse.deprecate("#{provider.authenticator.class.name} has not defined an enabled_setting. Defaulting to true.", drop_from: '2.9.0')
- true
- end
+ provider
+ .authenticator
+ .define_singleton_method(:enabled?) do
+ Discourse.deprecate(
+ "#{provider.authenticator.class.name} should define an `enabled?` function. Patching for now.",
+ drop_from: "2.9.0",
+ )
+ return SiteSetting.get(provider.enabled_setting) if provider.enabled_setting
+ Discourse.deprecate(
+ "#{provider.authenticator.class.name} has not defined an enabled_setting. Defaulting to true.",
+ drop_from: "2.9.0",
+ )
+ true
+ end
end
DiscoursePluginRegistry.register_auth_provider(provider)
@@ -791,20 +813,24 @@ class Plugin::Instance
end
def handlebars_includes
- assets.map do |asset, opts|
- next if opts == :admin
- next unless asset =~ DiscoursePluginRegistry::HANDLEBARS_REGEX
- asset
- end.compact
+ assets
+ .map do |asset, opts|
+ next if opts == :admin
+ next unless asset =~ DiscoursePluginRegistry::HANDLEBARS_REGEX
+ asset
+ end
+ .compact
end
def javascript_includes
- assets.map do |asset, opts|
- next if opts == :vendored_core_pretty_text
- next if opts == :admin
- next unless asset =~ DiscoursePluginRegistry::JS_REGEX
- asset
- end.compact
+ assets
+ .map do |asset, opts|
+ next if opts == :vendored_core_pretty_text
+ next if opts == :admin
+ next unless asset =~ DiscoursePluginRegistry::JS_REGEX
+ asset
+ end
+ .compact
end
def each_globbed_asset
@@ -813,16 +839,19 @@ class Plugin::Instance
root_path = "#{File.dirname(@path)}/assets/javascripts"
admin_path = "#{File.dirname(@path)}/admin/assets/javascripts"
- Dir.glob(["#{root_path}/**/*", "#{admin_path}/**/*"]).sort.each do |f|
- f_str = f.to_s
- if File.directory?(f)
- yield [f, true]
- elsif f_str.end_with?(".js.es6") || f_str.end_with?(".hbs") || f_str.end_with?(".hbr")
- yield [f, false]
- elsif f_str.end_with?(".js")
- yield [f, false]
+ Dir
+ .glob(["#{root_path}/**/*", "#{admin_path}/**/*"])
+ .sort
+ .each do |f|
+ f_str = f.to_s
+ if File.directory?(f)
+ yield [f, true]
+ elsif f_str.end_with?(".js.es6") || f_str.end_with?(".hbs") || f_str.end_with?(".hbr")
+ yield [f, false]
+ elsif f_str.end_with?(".js")
+ yield [f, false]
+ end
end
- end
end
end
@@ -834,9 +863,7 @@ class Plugin::Instance
current_list = klass.public_send(method)
current_list.concat(new_attributes)
- reloadable_patch do
- klass.public_send(:define_singleton_method, method) { current_list }
- end
+ reloadable_patch { klass.public_send(:define_singleton_method, method) { current_list } }
end
def directory_name
@@ -865,9 +892,7 @@ class Plugin::Instance
# 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 do
- Reviewable.add_custom_filter(filter)
- end
+ reloadable_patch { Reviewable.add_custom_filter(filter) }
end
# Register a new API key scope.
@@ -905,9 +930,9 @@ class Plugin::Instance
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)
+ { prefixed_scope_name => matcher_parameters&.map { |m| RouteMatcher.new(**m) } },
+ self,
+ )
end
# Register a route which can be authenticated using an api key or user api key
@@ -921,30 +946,40 @@ class Plugin::Instance
#
# See Auth::DefaultCurrentUserProvider::PARAMETER_API_PATTERNS for more examples
# and Auth::DefaultCurrentUserProvider#api_parameter_allowed? for implementation
- def add_api_parameter_route(method: nil, methods: nil,
- route: nil, actions: nil,
- format: nil, formats: nil)
-
+ def add_api_parameter_route(
+ method: nil,
+ methods: nil,
+ route: nil,
+ actions: nil,
+ format: nil,
+ formats: nil
+ )
if Array(format).include?("*")
- Discourse.deprecate("* is no longer a valid api_parameter_route format matcher. Use `nil` instead", drop_from: "2.7", raise_error: true)
+ Discourse.deprecate(
+ "* is no longer a valid api_parameter_route format matcher. Use `nil` instead",
+ drop_from: "2.7",
+ raise_error: true,
+ )
# Old API used * as wildcard. New api uses `nil`
format = nil
end
# Backwards compatibility with old parameter names:
if method || route || format
- Discourse.deprecate("method, route and format parameters for api_parameter_routes are deprecated. Use methods, actions and formats instead.", drop_from: "2.7", raise_error: true)
+ Discourse.deprecate(
+ "method, route and format parameters for api_parameter_routes are deprecated. Use methods, actions and formats instead.",
+ drop_from: "2.7",
+ raise_error: true,
+ )
methods ||= method
actions ||= route
formats ||= format
end
DiscoursePluginRegistry.register_api_parameter_route(
- RouteMatcher.new(
- methods: methods,
- actions: actions,
- formats: formats
- ), self)
+ RouteMatcher.new(methods: methods, actions: actions, formats: formats),
+ self,
+ )
end
# Register a new demon process to be forked by the Unicorn master.
@@ -957,10 +992,7 @@ class Plugin::Instance
end
def add_permitted_reviewable_param(type, param)
- DiscoursePluginRegistry.register_reviewable_param({
- type: type,
- param: param
- }, self)
+ DiscoursePluginRegistry.register_reviewable_param({ type: type, param: param }, self)
end
# Register a new PresenceChannel prefix. See {PresenceChannel.register_prefix}
@@ -992,7 +1024,10 @@ class Plugin::Instance
# 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)
+ DiscoursePluginRegistry.register_reviewable_score_link(
+ { reason: reason.to_sym, setting: setting_name },
+ self,
+ )
end
# If your plugin creates notifications, and you'd like to consolidate/collapse similar ones,
@@ -1009,7 +1044,9 @@ class Plugin::Instance
# - Create a new notification and delete previous versions plan: https://github.com/discourse/discourse/blob/main/app/services/notifications/delete_previous_notifications.rb
# - Base plans: https://github.com/discourse/discourse/blob/main/app/services/notifications/consolidation_planner.rb
def register_notification_consolidation_plan(plan)
- raise ArgumentError.new("Not a consolidation plan") if !plan.class.ancestors.include?(Notifications::ConsolidationPlan)
+ if !plan.class.ancestors.include?(Notifications::ConsolidationPlan)
+ raise ArgumentError.new("Not a consolidation plan")
+ end
DiscoursePluginRegistry.register_notification_consolidation_plan(plan, self)
end
@@ -1046,8 +1083,10 @@ class Plugin::Instance
# - 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)
- raise ArgumentError.new('Not an email unsubscriber') if !unsubscriber.ancestors.include?(EmailControllerHelper::BaseEmailUnsubscriber)
+ raise ArgumentError.new("Type already exists") if core_types.include?(type)
+ if !unsubscriber.ancestors.include?(EmailControllerHelper::BaseEmailUnsubscriber)
+ raise ArgumentError.new("Not an email unsubscriber")
+ end
DiscoursePluginRegistry.register_email_unsubscriber({ type => unsubscriber }, self)
end
@@ -1156,7 +1195,8 @@ class Plugin::Instance
# or lookups occur. Priority is ordered by DESCENDING order.
def register_hashtag_type_priority_for_context(type, context, priority)
DiscoursePluginRegistry.register_hashtag_autocomplete_contextual_type_priority(
- { type: type, context: context, priority: priority }, self
+ { type: type, context: context, priority: priority },
+ self,
)
end
@@ -1202,8 +1242,10 @@ class Plugin::Instance
locales.each do |locale, opts|
opts = opts.dup
- 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 || ""
+ 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 ||
+ ""
opts[:js_locale_file] = File.join(root_path, "assets/locales/#{locale}.js.erb")
locale_chain = opts[:fallbackLocale] ? [locale, opts[:fallbackLocale]] : [locale]
@@ -1211,7 +1253,10 @@ class Plugin::Instance
path = File.join(lib_locale_path, "message_format")
opts[:message_format] = find_locale_file(locale_chain, path)
- opts[:message_format] = JsLocaleHelper.find_message_format_locale(locale_chain, fallback_to_english: false) unless opts[:message_format]
+ opts[:message_format] = JsLocaleHelper.find_message_format_locale(
+ locale_chain,
+ fallback_to_english: false,
+ ) unless opts[:message_format]
path = File.join(lib_locale_path, "moment_js")
opts[:moment_js] = find_locale_file(locale_chain, path)
@@ -1219,7 +1264,10 @@ class Plugin::Instance
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]
+ opts[:moment_js_timezones] = JsLocaleHelper.find_moment_locale(
+ locale_chain,
+ timezone_names: true,
+ ) unless opts[:moment_js_timezones]
if valid_locale?(opts)
DiscoursePluginRegistry.register_locale(locale, opts)
@@ -1237,9 +1285,7 @@ class Plugin::Instance
end
def allow_new_queued_post_payload_attribute(attribute_name)
- reloadable_patch do
- NewPostManager.add_plugin_payload_attribute(attribute_name)
- end
+ reloadable_patch { NewPostManager.add_plugin_payload_attribute(attribute_name) }
end
def register_topic_preloader_associations(fields)
@@ -1250,7 +1296,9 @@ class Plugin::Instance
def validate_directory_column_name(column_name)
match = /^[_a-z]+$/.match(column_name)
- raise "Invalid directory column name '#{column_name}'. Can only contain a-z and underscores" unless match
+ unless match
+ raise "Invalid directory column name '#{column_name}'. Can only contain a-z and underscores"
+ end
end
def write_asset(path, contents)
@@ -1275,14 +1323,14 @@ class Plugin::Instance
def valid_locale?(custom_locale)
File.exist?(custom_locale[:client_locale_file]) &&
File.exist?(custom_locale[:server_locale_file]) &&
- File.exist?(custom_locale[:js_locale_file]) &&
- custom_locale[:message_format] && custom_locale[:moment_js]
+ File.exist?(custom_locale[:js_locale_file]) && custom_locale[:message_format] &&
+ custom_locale[:moment_js]
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)
+ return locale, filename if File.exist?(filename)
end
nil
end
diff --git a/lib/plugin/metadata.rb b/lib/plugin/metadata.rb
index 6eb4ffbd19a..ab59144079c 100644
--- a/lib/plugin/metadata.rb
+++ b/lib/plugin/metadata.rb
@@ -1,109 +1,110 @@
# frozen_string_literal: true
# loaded really early
-module Plugin; end
+module Plugin
+end
class Plugin::Metadata
+ OFFICIAL_PLUGINS ||=
+ Set.new(
+ [
+ # TODO: Remove this after everyone upgraded `discourse-canned-replies`
+ # to the renamed version.
+ "Canned Replies",
+ "discourse-adplugin",
+ "discourse-affiliate",
+ "discourse-akismet",
+ "discourse-algolia",
+ "discourse-apple-auth",
+ "discourse-assign",
+ "discourse-auto-deactivate",
+ "discourse-automation",
+ "discourse-bbcode",
+ "discourse-bbcode-color",
+ "discourse-bcc",
+ "discourse-cakeday",
+ "discourse-calendar",
+ "discourse-canned-replies",
+ "discourse-categories-suppressed",
+ "discourse-category-experts",
+ "discourse-characters-required",
+ "discourse-chat-integration",
+ "discourse-checklist",
+ "discourse-code-review",
+ "discourse-crowd",
+ "discourse-data-explorer",
+ "discourse-details",
+ "discourse-docs",
+ "discourse-encrypt",
+ "discourse-follow",
+ "discourse-fontawesome-pro",
+ "discourse-footnote",
+ "discourse-gamification",
+ "discourse-github",
+ "discourse-gradle-issue",
+ "discourse-graphviz",
+ "discourse-group-tracker",
+ "discourse-invite-tokens",
+ "discourse-local-dates",
+ "discourse-login-with-amazon",
+ "discourse-logster-rate-limit-checker",
+ "discourse-logster-transporter",
+ "discourse-lti",
+ "discourse-math",
+ "discourse-moderator-attention",
+ "discourse-narrative-bot",
+ "discourse-no-bump",
+ "discourse-oauth2-basic",
+ "discourse-openid-connect",
+ "discourse-patreon",
+ "discourse-perspective-api",
+ "discourse-linkedin-auth",
+ "discourse-microsoft-auth",
+ "discourse-policy",
+ "discourse-post-voting",
+ "discourse-presence",
+ "discourse-prometheus",
+ "discourse-prometheus-alert-receiver",
+ "discourse-push-notifications",
+ "discourse-reactions",
+ "discourse-restricted-replies",
+ "discourse-rss-polling",
+ "discourse-salesforce",
+ "discourse-saml",
+ "discourse-saved-searches",
+ "discourse-shared-edits",
+ "discourse-signatures",
+ "discourse-sitemap",
+ "discourse-solved",
+ "discourse-spoiler-alert",
+ "discourse-staff-alias",
+ "discourse-steam-login",
+ "discourse-subscriptions",
+ "discourse-teambuild",
+ "discourse-templates",
+ "discourse-tooltips",
+ "discourse-topic-voting",
+ "discourse-translator",
+ "discourse-user-card-badges",
+ "discourse-user-notes",
+ "discourse-vk-auth",
+ "discourse-whos-online",
+ "discourse-yearly-review",
+ "discourse-zendesk-plugin",
+ "docker_manager",
+ "chat",
+ "lazy-yt",
+ "poll",
+ "styleguide",
+ ],
+ )
- OFFICIAL_PLUGINS ||= Set.new([
- # TODO: Remove this after everyone upgraded `discourse-canned-replies`
- # to the renamed version.
- "Canned Replies",
- "discourse-adplugin",
- "discourse-affiliate",
- "discourse-akismet",
- "discourse-algolia",
- "discourse-apple-auth",
- "discourse-assign",
- "discourse-auto-deactivate",
- "discourse-automation",
- "discourse-bbcode",
- "discourse-bbcode-color",
- "discourse-bcc",
- "discourse-cakeday",
- "discourse-calendar",
- "discourse-canned-replies",
- "discourse-categories-suppressed",
- "discourse-category-experts",
- "discourse-characters-required",
- "discourse-chat-integration",
- "discourse-checklist",
- "discourse-code-review",
- "discourse-crowd",
- "discourse-data-explorer",
- "discourse-details",
- "discourse-docs",
- "discourse-encrypt",
- "discourse-follow",
- "discourse-fontawesome-pro",
- "discourse-footnote",
- "discourse-gamification",
- "discourse-github",
- "discourse-gradle-issue",
- "discourse-graphviz",
- "discourse-group-tracker",
- "discourse-invite-tokens",
- "discourse-local-dates",
- "discourse-login-with-amazon",
- "discourse-logster-rate-limit-checker",
- "discourse-logster-transporter",
- "discourse-lti",
- "discourse-math",
- "discourse-moderator-attention",
- "discourse-narrative-bot",
- "discourse-no-bump",
- "discourse-oauth2-basic",
- "discourse-openid-connect",
- "discourse-patreon",
- "discourse-perspective-api",
- "discourse-linkedin-auth",
- "discourse-microsoft-auth",
- "discourse-policy",
- "discourse-post-voting",
- "discourse-presence",
- "discourse-prometheus",
- "discourse-prometheus-alert-receiver",
- "discourse-push-notifications",
- "discourse-reactions",
- "discourse-restricted-replies",
- "discourse-rss-polling",
- "discourse-salesforce",
- "discourse-saml",
- "discourse-saved-searches",
- "discourse-shared-edits",
- "discourse-signatures",
- "discourse-sitemap",
- "discourse-solved",
- "discourse-spoiler-alert",
- "discourse-staff-alias",
- "discourse-steam-login",
- "discourse-subscriptions",
- "discourse-teambuild",
- "discourse-templates",
- "discourse-tooltips",
- "discourse-topic-voting",
- "discourse-translator",
- "discourse-user-card-badges",
- "discourse-user-notes",
- "discourse-vk-auth",
- "discourse-whos-online",
- "discourse-yearly-review",
- "discourse-zendesk-plugin",
- "docker_manager",
- "chat",
- "lazy-yt",
- "poll",
- "styleguide",
- ])
-
- FIELDS ||= [:name, :about, :version, :authors, :contact_emails, :url, :required_version, :transpile_js]
+ FIELDS ||= %i[name about version authors contact_emails url required_version transpile_js]
attr_accessor(*FIELDS)
def self.parse(text)
metadata = self.new
- text.each_line do |line|
- break unless metadata.parse_line(line)
- end
+ text.each_line { |line| break unless metadata.parse_line(line) }
metadata
end
@@ -119,11 +120,9 @@ class Plugin::Metadata
attribute, *description = line[1..-1].split(":")
description = description.join(":")
- attribute = attribute.strip.gsub(/ /, '_').to_sym
+ attribute = attribute.strip.gsub(/ /, "_").to_sym
- if FIELDS.include?(attribute)
- self.public_send("#{attribute}=", description.strip)
- end
+ self.public_send("#{attribute}=", description.strip) if FIELDS.include?(attribute)
end
true
diff --git a/lib/plugin_gem.rb b/lib/plugin_gem.rb
index 49882b2cd92..bba295f43e1 100644
--- a/lib/plugin_gem.rb
+++ b/lib/plugin_gem.rb
@@ -8,27 +8,24 @@ module PluginGem
spec_path = gems_path + "/specifications"
- spec_file = spec_path + "/#{name}-#{version}"
+ spec_file = spec_path + "/#{name}-#{version}"
spec_file += "-#{opts[:platform]}" if opts[:platform]
spec_file += ".gemspec"
unless File.exist? spec_file
- command = "gem install #{name} -v #{version} -i #{gems_path} --no-document --ignore-dependencies --no-user-install"
+ command =
+ "gem install #{name} -v #{version} -i #{gems_path} --no-document --ignore-dependencies --no-user-install"
command += " --source #{opts[:source]}" if opts[:source]
puts command
- Bundler.with_unbundled_env do
- puts `#{command}`
- end
+ Bundler.with_unbundled_env { puts `#{command}` }
end
if File.exist? spec_file
Gem.path << gems_path
Gem::Specification.load(spec_file).activate
- unless opts[:require] == false
- require opts[:require_name] ? opts[:require_name] : name
- end
+ require opts[:require_name] ? opts[:require_name] : name unless opts[:require] == false
else
puts "You are specifying the gem #{name} in #{path}, however it does not exist!"
puts "Looked for: #{spec_file}"
diff --git a/lib/post_action_creator.rb b/lib/post_action_creator.rb
index ccfc08b3207..32049c79f4d 100644
--- a/lib/post_action_creator.rb
+++ b/lib/post_action_creator.rb
@@ -7,7 +7,15 @@ class PostActionCreator
# Shortcut methods for easier invocation
class << self
- def create(created_by, post, action_key, message: nil, created_at: nil, reason: nil, silent: false)
+ def create(
+ created_by,
+ post,
+ action_key,
+ message: nil,
+ created_at: nil,
+ reason: nil,
+ silent: false
+ )
new(
created_by,
post,
@@ -15,16 +23,16 @@ class PostActionCreator
message: message,
created_at: created_at,
reason: reason,
- silent: silent
+ silent: silent,
).perform
end
- [:like, :off_topic, :spam, :inappropriate].each do |action|
+ %i[like off_topic spam inappropriate].each do |action|
define_method(action) do |created_by, post, silent = false|
create(created_by, post, action, silent: silent)
end
end
- [:notify_moderators, :notify_user].each do |action|
+ %i[notify_moderators notify_user].each do |action|
define_method(action) do |created_by, post, message = nil|
create(created_by, post, action, message: message)
end
@@ -61,9 +69,7 @@ class PostActionCreator
@reason = reason
@queue_for_review = queue_for_review
- if reason.nil? && @queue_for_review
- @reason = 'queued_by_staff'
- end
+ @reason = "queued_by_staff" if reason.nil? && @queue_for_review
@silent = silent
end
@@ -74,8 +80,8 @@ class PostActionCreator
@post_action_name,
opts: {
is_warning: @is_warning,
- taken_actions: PostAction.counts_for([@post].compact, @created_by)[@post&.id]
- }
+ taken_actions: PostAction.counts_for([@post].compact, @created_by)[@post&.id],
+ },
)
end
@@ -98,7 +104,7 @@ class PostActionCreator
end
# create meta topic / post if needed
- if @message.present? && [:notify_moderators, :notify_user, :spam].include?(@post_action_name)
+ if @message.present? && %i[notify_moderators notify_user spam].include?(@post_action_name)
creator = create_message_creator
post = creator.create
if creator.errors.present?
@@ -128,23 +134,23 @@ class PostActionCreator
result.success = true
result.post_action = post_action
-
end
rescue ActiveRecord::RecordNotUnique
# If the user already performed this action, it's probably due to a different browser tab
# or non-debounced clicking. We can ignore.
result.success = true
- result.post_action = PostAction.find_by(
- user: @created_by,
- post: @post,
- post_action_type_id: @post_action_type_id
- )
+ result.post_action =
+ PostAction.find_by(
+ user: @created_by,
+ post: @post,
+ post_action_type_id: @post_action_type_id,
+ )
end
result
end
-private
+ private
def flagging_post?
PostActionType.notify_flag_type_ids.include?(@post_action_type_id)
@@ -152,16 +158,25 @@ private
def cannot_flag_again?(reviewable)
return false if @post_action_type_id == PostActionType.types[:notify_moderators]
- flag_type_already_used = reviewable.reviewable_scores.any? { |rs| rs.reviewable_score_type == @post_action_type_id && !rs.pending? }
- not_edited_since_last_review = @post.last_version_at.blank? || reviewable.updated_at > @post.last_version_at
- handled_recently = reviewable.updated_at > SiteSetting.cooldown_hours_until_reflag.to_i.hours.ago
+ flag_type_already_used =
+ reviewable.reviewable_scores.any? do |rs|
+ rs.reviewable_score_type == @post_action_type_id && !rs.pending?
+ end
+ not_edited_since_last_review =
+ @post.last_version_at.blank? || reviewable.updated_at > @post.last_version_at
+ handled_recently =
+ reviewable.updated_at > SiteSetting.cooldown_hours_until_reflag.to_i.hours.ago
flag_type_already_used && not_edited_since_last_review && handled_recently
end
def notify_subscribers
if @post_action_name == :like
- @post.publish_change_to_clients! :liked, { likes_count: @post.like_count + 1, user_id: @created_by.id }
+ @post.publish_change_to_clients! :liked,
+ {
+ likes_count: @post.like_count + 1,
+ user_id: @created_by.id,
+ }
elsif self.class.notify_types.include?(@post_action_name)
@post.publish_change_to_clients! :acted
end
@@ -182,17 +197,18 @@ private
return unless topic.auto_close_threshold_reached?
# the threshold has been reached, we will close the topic waiting for intervention
- topic.update_status("closed", true, Discourse.system_user,
- message: I18n.t(
- "temporarily_closed_due_to_flags",
- count: SiteSetting.num_hours_to_close_topic
- )
+ topic.update_status(
+ "closed",
+ true,
+ Discourse.system_user,
+ message:
+ I18n.t("temporarily_closed_due_to_flags", count: SiteSetting.num_hours_to_close_topic),
)
topic.set_or_create_timer(
TopicTimer.types[:open],
SiteSetting.num_hours_to_close_topic,
- by_user: Discourse.system_user
+ by_user: Discourse.system_user,
)
end
@@ -204,12 +220,12 @@ private
return if not_auto_action_flag_type && !@queue_for_review
if @queue_for_review
- @post.topic.update_status('visible', false, @created_by) if @post.is_first_post?
+ @post.topic.update_status("visible", false, @created_by) if @post.is_first_post?
@post.hide!(
@post_action_type_id,
Post.hidden_reasons[:flag_threshold_reached],
- custom_message: :queued_by_staff
+ custom_message: :queued_by_staff,
)
return
end
@@ -220,45 +236,34 @@ private
end
score = ReviewableFlaggedPost.find_by(target: @post)&.score || 0
- if score >= Reviewable.score_required_to_hide_post
- @post.hide!(@post_action_type_id)
- end
+ @post.hide!(@post_action_type_id) if score >= Reviewable.score_required_to_hide_post
end
# Special case: If you have TL3 and the user is TL0, and the flag is spam,
# hide it immediately.
def trusted_spam_flagger?
- SiteSetting.high_trust_flaggers_auto_hide_posts &&
- @post_action_name == :spam &&
- @created_by.has_trust_level?(TrustLevel[3]) &&
- @post.user&.trust_level == TrustLevel[0]
+ SiteSetting.high_trust_flaggers_auto_hide_posts && @post_action_name == :spam &&
+ @created_by.has_trust_level?(TrustLevel[3]) && @post.user&.trust_level == TrustLevel[0]
end
def create_post_action
- @targets_topic = !!(
- if @flag_topic && @post.topic
- @post.topic.reload.posts_count != 1
- end
- )
+ @targets_topic = !!(@post.topic.reload.posts_count != 1 if @flag_topic && @post.topic)
where_attrs = {
post_id: @post.id,
user_id: @created_by.id,
- post_action_type_id: @post_action_type_id
+ post_action_type_id: @post_action_type_id,
}
action_attrs = {
staff_took_action: @take_action,
related_post_id: @meta_post&.id,
targets_topic: @targets_topic,
- created_at: @created_at
+ created_at: @created_at,
}
# First try to revive a trashed record
- post_action = PostAction.where(where_attrs)
- .with_deleted
- .where("deleted_at IS NOT NULL")
- .first
+ post_action = PostAction.where(where_attrs).with_deleted.where("deleted_at IS NOT NULL").first
if post_action
post_action.recover!
@@ -280,7 +285,9 @@ private
end
end
- GivenDailyLike.increment_for(@created_by.id) if @post_action_type_id == PostActionType.types[:like]
+ if @post_action_type_id == PostActionType.types[:like]
+ GivenDailyLike.increment_for(@created_by.id)
+ end
post_action
rescue ActiveRecord::RecordNotUnique
@@ -289,44 +296,46 @@ private
end
def create_message_creator
- title = I18n.t(
- "post_action_types.#{@post_action_name}.email_title",
- title: @post.topic.title,
- locale: SiteSetting.default_locale
- )
+ title =
+ I18n.t(
+ "post_action_types.#{@post_action_name}.email_title",
+ title: @post.topic.title,
+ locale: SiteSetting.default_locale,
+ )
- body = I18n.t(
- "post_action_types.#{@post_action_name}.email_body",
- message: @message,
- link: "#{Discourse.base_url}#{@post.url}",
- locale: SiteSetting.default_locale
- )
+ body =
+ I18n.t(
+ "post_action_types.#{@post_action_name}.email_body",
+ message: @message,
+ link: "#{Discourse.base_url}#{@post.url}",
+ locale: SiteSetting.default_locale,
+ )
create_args = {
archetype: Archetype.private_message,
is_warning: @is_warning,
title: title.truncate(SiteSetting.max_topic_title_length, separator: /\s/),
- raw: body
+ raw: body,
}
- if [:notify_moderators, :spam].include?(@post_action_name)
+ if %i[notify_moderators spam].include?(@post_action_name)
create_args[:subtype] = TopicSubtype.notify_moderators
create_args[:target_group_names] = [Group[:moderators].name]
- if SiteSetting.enable_category_group_moderation? && @post.topic&.category&.reviewable_by_group_id?
+ if SiteSetting.enable_category_group_moderation? &&
+ @post.topic&.category&.reviewable_by_group_id?
create_args[:target_group_names] << @post.topic.category.reviewable_by_group.name
end
else
create_args[:subtype] = TopicSubtype.notify_user
- create_args[:target_usernames] =
- if @post_action_name == :notify_user
- @post.user.username
- elsif @post_action_name != :notify_moderators
- # this is a hack to allow a PM with no recipients, we should think through
- # a cleaner technique, a PM with myself is valid for flagging
- 'x'
- end
+ create_args[:target_usernames] = if @post_action_name == :notify_user
+ @post.user.username
+ elsif @post_action_name != :notify_moderators
+ # this is a hack to allow a PM with no recipients, we should think through
+ # a cleaner technique, a PM with myself is valid for flagging
+ "x"
+ end
end
PostCreator.new(@created_by, create_args)
@@ -336,26 +345,28 @@ private
return unless flagging_post?
return if @post.user_id.to_i < 0
- result.reviewable = ReviewableFlaggedPost.needs_review!(
- created_by: @created_by,
- target: @post,
- topic: @post.topic,
- reviewable_by_moderator: true,
- potential_spam: @post_action_type_id == PostActionType.types[:spam],
- payload: {
- targets_topic: @targets_topic
- }
- )
+ result.reviewable =
+ ReviewableFlaggedPost.needs_review!(
+ created_by: @created_by,
+ target: @post,
+ topic: @post.topic,
+ reviewable_by_moderator: true,
+ potential_spam: @post_action_type_id == PostActionType.types[:spam],
+ payload: {
+ targets_topic: @targets_topic,
+ },
+ )
- result.reviewable_score = result.reviewable.add_score(
- @created_by,
- @post_action_type_id,
- created_at: @created_at,
- take_action: @take_action,
- meta_topic_id: @meta_post&.topic_id,
- reason: @reason,
- force_review: trusted_spam_flagger?
- )
+ result.reviewable_score =
+ result.reviewable.add_score(
+ @created_by,
+ @post_action_type_id,
+ created_at: @created_at,
+ take_action: @take_action,
+ meta_topic_id: @meta_post&.topic_id,
+ reason: @reason,
+ force_review: trusted_spam_flagger?,
+ )
end
def guardian
@@ -365,5 +376,4 @@ private
def topic
@post.topic
end
-
end
diff --git a/lib/post_action_destroyer.rb b/lib/post_action_destroyer.rb
index 697047de906..16d7c94a693 100644
--- a/lib/post_action_destroyer.rb
+++ b/lib/post_action_destroyer.rb
@@ -6,7 +6,11 @@ class PostActionDestroyer
end
def initialize(destroyed_by, post, post_action_type_id, opts = {})
- @destroyed_by, @post, @post_action_type_id, @opts = destroyed_by, post, post_action_type_id, opts
+ @destroyed_by, @post, @post_action_type_id, @opts =
+ destroyed_by,
+ post,
+ post_action_type_id,
+ opts
end
def self.destroy(destroyed_by, post, action_key, opts = {})
@@ -21,11 +25,8 @@ class PostActionDestroyer
return result
end
- finder = PostAction.where(
- user: @destroyed_by,
- post: @post,
- post_action_type_id: @post_action_type_id
- )
+ finder =
+ PostAction.where(user: @destroyed_by, post: @post, post_action_type_id: @post_action_type_id)
finder = finder.with_deleted if @destroyed_by.staff?
post_action = finder.first
@@ -40,11 +41,18 @@ class PostActionDestroyer
return result
end
- RateLimiter.new(@destroyed_by, "post_action-#{@post.id}_#{@post_action_type_id}", 4, 1.minute).performed!
+ RateLimiter.new(
+ @destroyed_by,
+ "post_action-#{@post.id}_#{@post_action_type_id}",
+ 4,
+ 1.minute,
+ ).performed!
post_action.remove_act!(@destroyed_by)
post_action.post.unhide! if post_action.staff_took_action
- GivenDailyLike.decrement_for(@destroyed_by.id) if @post_action_type_id == PostActionType.types[:like]
+ if @post_action_type_id == PostActionType.types[:like]
+ GivenDailyLike.decrement_for(@destroyed_by.id)
+ end
UserActionManager.post_action_destroyed(post_action)
PostActionNotifier.post_action_deleted(post_action)
@@ -56,7 +64,7 @@ class PostActionDestroyer
result
end
-protected
+ protected
def self.notify_types
@notify_types ||= PostActionType.notify_flag_types.keys
@@ -65,7 +73,10 @@ protected
def notify_subscribers
name = PostActionType.types[@post_action_type_id]
if name == :like
- @post.publish_change_to_clients!(:unliked, { likes_count: @post.like_count, user_id: @destroyed_by.id })
+ @post.publish_change_to_clients!(
+ :unliked,
+ { likes_count: @post.like_count, user_id: @destroyed_by.id },
+ )
elsif self.class.notify_types.include?(name)
@post.publish_change_to_clients!(:acted)
end
diff --git a/lib/post_action_result.rb b/lib/post_action_result.rb
index 88a7b5d0ce5..2bec74c719a 100644
--- a/lib/post_action_result.rb
+++ b/lib/post_action_result.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'has_errors'
+require "has_errors"
class PostActionResult
include HasErrors
diff --git a/lib/post_creator.rb b/lib/post_creator.rb
index 7cded3c4863..b233de35403 100644
--- a/lib/post_creator.rb
+++ b/lib/post_creator.rb
@@ -97,7 +97,7 @@ class PostCreator
end
if @opts[:target_usernames].present? && !skip_validations? && [email protected]?
- names = @opts[:target_usernames].split(',').flatten.map(&:downcase)
+ names = @opts[:target_usernames].split(",").flatten.map(&:downcase)
# Make sure max_allowed_message_recipients setting is respected
max_allowed_message_recipients = SiteSetting.max_allowed_message_recipients
@@ -105,7 +105,7 @@ class PostCreator
if names.length > max_allowed_message_recipients
errors.add(
:base,
- I18n.t(:max_pm_recipients, recipients_limit: max_allowed_message_recipients)
+ I18n.t(:max_pm_recipients, recipients_limit: max_allowed_message_recipients),
)
return false
@@ -114,9 +114,12 @@ class PostCreator
# Make sure none of the users have muted or ignored the creator or prevented
# PMs from being sent to them
target_users = User.where(username_lower: names.map(&:downcase)).pluck(:id, :username).to_h
- UserCommScreener.new(acting_user: @user, target_user_ids: target_users.keys).preventing_actor_communication.each do |user_id|
- errors.add(:base, I18n.t(:not_accepting_pms, username: target_users[user_id]))
- end
+ UserCommScreener
+ .new(acting_user: @user, target_user_ids: target_users.keys)
+ .preventing_actor_communication
+ .each do |user_id|
+ errors.add(:base, I18n.t(:not_accepting_pms, username: target_users[user_id]))
+ end
return false if errors[:base].present?
end
@@ -215,9 +218,7 @@ class PostCreator
if !opts[:import_mode]
handle_spam if (@spam || @post)
- if !@spam && @post && errors.blank?
- ReviewablePost.queue_for_review_if_possible(@post, @user)
- end
+ ReviewablePost.queue_for_review_if_possible(@post, @user) if !@spam && @post && errors.blank?
end
@post
@@ -236,9 +237,12 @@ class PostCreator
def enqueue_jobs
return unless @post && [email protected]?
- PostJobsEnqueuer.new(@post, @topic, new_topic?,
+ PostJobsEnqueuer.new(
+ @post,
+ @topic,
+ new_topic?,
import_mode: @opts[:import_mode],
- post_alert_options: @opts[:post_alert_options]
+ post_alert_options: @opts[:post_alert_options],
).enqueue_jobs
end
@@ -269,11 +273,15 @@ class PostCreator
post.word_count = post.raw.scan(/[[:word:]]+/).size
whisper = post.post_type == Post.types[:whisper]
- increase_posts_count = !post.topic&.private_message? || post.post_type != Post.types[:small_action]
- post.post_number ||= Topic.next_post_number(post.topic_id,
- reply: post.reply_to_post_number.present?,
- whisper: whisper,
- post: increase_posts_count)
+ increase_posts_count =
+ !post.topic&.private_message? || post.post_type != Post.types[:small_action]
+ post.post_number ||=
+ Topic.next_post_number(
+ post.topic_id,
+ reply: post.reply_to_post_number.present?,
+ whisper: whisper,
+ post: increase_posts_count,
+ )
cooking_options = post.cooking_options || {}
cooking_options[:topic_id] = post.topic_id
@@ -295,10 +303,12 @@ class PostCreator
# Here, we lock the replied to post before getting the topic lock so that
# we can update the replied to post later without causing a deadlock.
- reply_info = Post.where(topic_id: post.topic_id, post_number: post.reply_to_post_number)
- .select(:user_id, :post_type)
- .lock
- .first
+ reply_info =
+ Post
+ .where(topic_id: post.topic_id, post_number: post.reply_to_post_number)
+ .select(:user_id, :post_type)
+ .lock
+ .first
if reply_info.present?
post.reply_to_user_id ||= reply_info.user_id
@@ -317,14 +327,15 @@ class PostCreator
def build_post_stats
if PostCreator.track_post_stats
sequence = DraftSequence.current(@user, draft_key)
- revisions = Draft.where(sequence: sequence,
- user_id: @user.id,
- draft_key: draft_key).pluck_first(:revisions) || 0
+ revisions =
+ Draft.where(sequence: sequence, user_id: @user.id, draft_key: draft_key).pluck_first(
+ :revisions,
+ ) || 0
@post.build_post_stat(
drafts_saved: revisions,
typing_duration_msecs: @opts[:typing_duration_msecs] || 0,
- composer_open_duration_msecs: @opts[:composer_open_duration_msecs] || 0
+ composer_open_duration_msecs: @opts[:composer_open_duration_msecs] || 0,
)
end
end
@@ -334,31 +345,31 @@ class PostCreator
is_private_message = topic.private_message?
topic_posts_count = @post.topic.posts_count
- if is_private_message &&
- !topic.closed &&
- SiteSetting.auto_close_messages_post_count > 0 &&
- SiteSetting.auto_close_messages_post_count <= topic_posts_count
-
+ if is_private_message && !topic.closed && SiteSetting.auto_close_messages_post_count > 0 &&
+ SiteSetting.auto_close_messages_post_count <= topic_posts_count
@post.topic.update_status(
- :closed, true, Discourse.system_user,
- message: I18n.t(
- 'topic_statuses.autoclosed_message_max_posts',
- count: SiteSetting.auto_close_messages_post_count,
- locale: SiteSetting.default_locale
- )
+ :closed,
+ true,
+ Discourse.system_user,
+ message:
+ I18n.t(
+ "topic_statuses.autoclosed_message_max_posts",
+ count: SiteSetting.auto_close_messages_post_count,
+ locale: SiteSetting.default_locale,
+ ),
)
- elsif !is_private_message &&
- !topic.closed &&
- SiteSetting.auto_close_topics_post_count > 0 &&
- SiteSetting.auto_close_topics_post_count <= topic_posts_count
-
+ elsif !is_private_message && !topic.closed && SiteSetting.auto_close_topics_post_count > 0 &&
+ SiteSetting.auto_close_topics_post_count <= topic_posts_count
topic.update_status(
- :closed, true, Discourse.system_user,
- message: I18n.t(
- 'topic_statuses.autoclosed_topic_max_posts',
- count: SiteSetting.auto_close_topics_post_count,
- locale: SiteSetting.default_locale
- )
+ :closed,
+ true,
+ Discourse.system_user,
+ message:
+ I18n.t(
+ "topic_statuses.autoclosed_topic_max_posts",
+ count: SiteSetting.auto_close_topics_post_count,
+ locale: SiteSetting.default_locale,
+ ),
)
if SiteSetting.auto_close_topics_create_linked_topic?
@@ -370,17 +381,11 @@ class PostCreator
def transaction(&blk)
if new_topic?
- Post.transaction do
- blk.call
- end
+ Post.transaction { blk.call }
else
# we need to ensure post_number is monotonically increasing with no gaps
# so we serialize creation to avoid needing rollbacks
- DistributedMutex.synchronize("topic_id_#{@opts[:topic_id]}") do
- Post.transaction do
- blk.call
- end
- end
+ DistributedMutex.synchronize("topic_id_#{@opts[:topic_id]}") { Post.transaction { blk.call } }
end
end
@@ -393,7 +398,8 @@ class PostCreator
original_uri = URI.parse(@opts[:embed_url])
raise Discourse::InvalidParameters.new(:embed_url) unless original_uri.is_a?(URI::HTTP)
- embed = TopicEmbed.new(topic_id: @post.topic_id, post_id: @post.id, embed_url: @opts[:embed_url])
+ embed =
+ TopicEmbed.new(topic_id: @post.topic_id, post_id: @post.id, embed_url: @opts[:embed_url])
rollback_from_errors!(embed) unless embed.save
end
@@ -406,17 +412,21 @@ class PostCreator
BookmarkManager.new(@user).destroy_for_topic(
Topic.with_deleted.find(@post.topic_id),
{ auto_delete_preference: Bookmark.auto_delete_preferences[:on_owner_reply] },
- @opts
+ @opts,
)
end
def handle_spam
if @spam
- GroupMessage.create(Group[:moderators].name,
- :spam_post_blocked,
- user: @user,
- limit_once_per: 24.hours,
- message_params: { domains: @post.linked_hosts.keys.join(', ') })
+ GroupMessage.create(
+ Group[:moderators].name,
+ :spam_post_blocked,
+ user: @user,
+ limit_once_per: 24.hours,
+ message_params: {
+ domains: @post.linked_hosts.keys.join(", "),
+ },
+ )
elsif @post && errors.blank? && !skip_validations?
SpamRule::FlagSockpuppets.new(@post).perform
end
@@ -426,7 +436,10 @@ class PostCreator
return unless @post && @post.errors.count == 0 && @topic && @topic.category_id
if @post.is_first_post?
- Category.where(id: @topic.category_id).update_all(latest_topic_id: @topic.id, latest_post_id: @post.id)
+ Category.where(id: @topic.category_id).update_all(
+ latest_topic_id: @topic.id,
+ latest_post_id: @post.id,
+ )
else
Category.where(id: @topic.category_id).update_all(latest_post_id: @post.id)
end
@@ -437,13 +450,12 @@ class PostCreator
return if @post.whisper? || @post.post_type == Post.types[:small_action]
return if @topic.topic_allowed_users.exists?(user_id: @user.id)
- return if @topic
- .topic_allowed_groups
- .where(
- "group_id IN (SELECT group_id FROM group_users where user_id = ?)",
- @user.id
- )
- .exists?
+ if @topic
+ .topic_allowed_groups
+ .where("group_id IN (SELECT group_id FROM group_users where user_id = ?)", @user.id)
+ .exists?
+ return
+ end
@topic.topic_allowed_users.create!(user_id: @user.id)
end
@@ -451,13 +463,17 @@ class PostCreator
def unarchive_message
return unless @topic.private_message? && @topic.id
- UserArchivedMessage.where(topic_id: @topic.id).pluck(:user_id).each do |user_id|
- UserArchivedMessage.move_to_inbox!(user_id, @topic)
- end
+ UserArchivedMessage
+ .where(topic_id: @topic.id)
+ .pluck(:user_id)
+ .each { |user_id| UserArchivedMessage.move_to_inbox!(user_id, @topic) }
- GroupArchivedMessage.where(topic_id: @topic.id).pluck(:group_id).each do |group_id|
- GroupArchivedMessage.move_to_inbox!(group_id, @topic, acting_user_id: @user.id)
- end
+ GroupArchivedMessage
+ .where(topic_id: @topic.id)
+ .pluck(:group_id)
+ .each do |group_id|
+ GroupArchivedMessage.move_to_inbox!(group_id, @topic, acting_user_id: @user.id)
+ end
end
private
@@ -473,9 +489,7 @@ class PostCreator
end
@post.topic_id = @topic.id
@post.topic = @topic
- if @topic && @topic.category && @topic.category.all_topics_wiki
- @post.wiki = true
- end
+ @post.wiki = true if @topic && @topic.category && @topic.category.all_topics_wiki
end
def update_topic_stats
@@ -500,39 +514,50 @@ class PostCreator
else
topic_timer = @topic.public_topic_timer
- if topic_timer &&
- topic_timer.based_on_last_post &&
- topic_timer.duration_minutes.to_i > 0
-
- @topic.set_or_create_timer(TopicTimer.types[:close],
+ if topic_timer && topic_timer.based_on_last_post && topic_timer.duration_minutes.to_i > 0
+ @topic.set_or_create_timer(
+ TopicTimer.types[:close],
nil,
based_on_last_post: topic_timer.based_on_last_post,
- duration_minutes: topic_timer.duration_minutes
+ duration_minutes: topic_timer.duration_minutes,
)
end
end
end
def setup_post
- @opts[:raw] = TextCleaner.normalize_whitespaces(@opts[:raw] || '').rstrip
-
- post = Post.new(raw: @opts[:raw],
- topic_id: @topic.try(:id),
- user: @user,
- reply_to_post_number: @opts[:reply_to_post_number])
+ @opts[:raw] = TextCleaner.normalize_whitespaces(@opts[:raw] || "").rstrip
+
+ post =
+ Post.new(
+ raw: @opts[:raw],
+ topic_id: @topic.try(:id),
+ user: @user,
+ reply_to_post_number: @opts[:reply_to_post_number],
+ )
# Attributes we pass through to the post instance if present
- [:post_type, :no_bump, :cooking_options, :image_sizes, :acting_user, :invalidate_oneboxes, :cook_method, :via_email, :raw_email, :action_code].each do |a|
- post.public_send("#{a}=", @opts[a]) if @opts[a].present?
- end
+ %i[
+ post_type
+ no_bump
+ cooking_options
+ image_sizes
+ acting_user
+ invalidate_oneboxes
+ cook_method
+ via_email
+ raw_email
+ action_code
+ ].each { |a| post.public_send("#{a}=", @opts[a]) if @opts[a].present? }
post.extract_quoted_post_numbers
- post.created_at = if @opts[:created_at].is_a?(Time)
- @opts[:created_at]
- elsif @opts[:created_at].present?
- Time.zone.parse(@opts[:created_at].to_s)
- end
+ post.created_at =
+ if @opts[:created_at].is_a?(Time)
+ @opts[:created_at]
+ elsif @opts[:created_at].present?
+ Time.zone.parse(@opts[:created_at].to_s)
+ end
if fields = @opts[:custom_fields]
post.custom_fields = fields
@@ -567,9 +592,7 @@ class PostCreator
@user.user_stat.update!(first_post_created_at: @post.created_at)
end
- if [email protected] || @post.topic.visible
- UserStatCountUpdater.increment!(@post)
- end
+ UserStatCountUpdater.increment!(@post) if [email protected] || @post.topic.visible
if [email protected]_message? && @post.post_type != Post.types[:whisper]
@user.update(last_posted_at: @post.created_at)
@@ -579,18 +602,16 @@ class PostCreator
def create_post_notice
return if @opts[:import_mode] || @user.anonymous? || @user.bot? || @user.staged
- last_post_time = Post.where(user_id: @user.id)
- .order(created_at: :desc)
- .limit(1)
- .pluck(:created_at)
- .first
+ last_post_time =
+ Post.where(user_id: @user.id).order(created_at: :desc).limit(1).pluck(:created_at).first
if !last_post_time
@post.custom_fields[Post::NOTICE] = { type: Post.notices[:new_user] }
- elsif SiteSetting.returning_users_days > 0 && last_post_time < SiteSetting.returning_users_days.days.ago
+ elsif SiteSetting.returning_users_days > 0 &&
+ last_post_time < SiteSetting.returning_users_days.days.ago
@post.custom_fields[Post::NOTICE] = {
type: Post.notices[:returning_user],
- last_posted_at: last_post_time.iso8601
+ last_posted_at: last_post_time.iso8601,
}
end
end
@@ -608,28 +629,42 @@ class PostCreator
def track_topic
return if @opts[:import_mode] || @opts[:auto_track] == false
- TopicUser.change(@post.user_id,
- @topic.id,
- posted: true,
- last_read_post_number: @post.post_number,
- last_posted_at: Time.zone.now)
+ TopicUser.change(
+ @post.user_id,
+ @topic.id,
+ posted: true,
+ last_read_post_number: @post.post_number,
+ last_posted_at: Time.zone.now,
+ )
# assume it took us 5 seconds of reading time to make a post
- PostTiming.record_timing(topic_id: @post.topic_id,
- user_id: @post.user_id,
- post_number: @post.post_number,
- msecs: 5000)
+ PostTiming.record_timing(
+ topic_id: @post.topic_id,
+ user_id: @post.user_id,
+ post_number: @post.post_number,
+ msecs: 5000,
+ )
if @user.staged
- TopicUser.auto_notification_for_staging(@user.id, @topic.id, TopicUser.notification_reasons[:auto_watch])
+ TopicUser.auto_notification_for_staging(
+ @user.id,
+ @topic.id,
+ TopicUser.notification_reasons[:auto_watch],
+ )
elsif [email protected]_message?
- notification_level = @user.user_option.notification_level_when_replying || NotificationLevels.topic_levels[:tracking]
- TopicUser.auto_notification(@user.id, @topic.id, TopicUser.notification_reasons[:created_post], notification_level)
+ notification_level =
+ @user.user_option.notification_level_when_replying ||
+ NotificationLevels.topic_levels[:tracking]
+ TopicUser.auto_notification(
+ @user.id,
+ @topic.id,
+ TopicUser.notification_reasons[:created_post],
+ notification_level,
+ )
end
end
def new_topic?
@opts[:topic_id].blank?
end
-
end
diff --git a/lib/post_destroyer.rb b/lib/post_destroyer.rb
index 7d5975747bb..5dc04721a5d 100644
--- a/lib/post_destroyer.rb
+++ b/lib/post_destroyer.rb
@@ -6,36 +6,38 @@
#
class PostDestroyer
def self.destroy_old_hidden_posts
- Post.where(deleted_at: nil, hidden: true)
+ Post
+ .where(deleted_at: nil, hidden: true)
.where("hidden_at < ?", 30.days.ago)
- .find_each do |post|
- PostDestroyer.new(Discourse.system_user, post).destroy
- end
+ .find_each { |post| PostDestroyer.new(Discourse.system_user, post).destroy }
end
def self.destroy_stubs
- context = I18n.t('remove_posts_deleted_by_author')
+ context = I18n.t("remove_posts_deleted_by_author")
# exclude deleted topics and posts that are actively flagged
- Post.where(deleted_at: nil, user_deleted: true)
- .where("NOT EXISTS (
+ Post
+ .where(deleted_at: nil, user_deleted: true)
+ .where(
+ "NOT EXISTS (
SELECT 1 FROM topics t
WHERE t.deleted_at IS NOT NULL AND
t.id = posts.topic_id
- )")
+ )",
+ )
.where("updated_at < ?", SiteSetting.delete_removed_posts_after.hours.ago)
- .where("NOT EXISTS (
+ .where(
+ "NOT EXISTS (
SELECT 1
FROM post_actions pa
WHERE pa.post_id = posts.id
AND pa.deleted_at IS NULL
AND pa.deferred_at IS NULL
AND pa.post_action_type_id IN (?)
- )", PostActionType.notify_flag_type_ids)
- .find_each do |post|
-
- PostDestroyer.new(Discourse.system_user, post, context: context).destroy
- end
+ )",
+ PostActionType.notify_flag_type_ids,
+ )
+ .find_each { |post| PostDestroyer.new(Discourse.system_user, post, context: context).destroy }
end
def self.delete_with_replies(performed_by, post, reviewable = nil, defer_reply_flags: true)
@@ -44,7 +46,9 @@ class PostDestroyer
PostDestroyer.new(performed_by, post, reviewable: reviewable).destroy
options = { defer_flags: defer_reply_flags }
- options.merge!({ reviewable: reviewable, notify_responders: true, parent_post: post }) if SiteSetting.notify_users_after_responses_deleted_on_flagged_post
+ if SiteSetting.notify_users_after_responses_deleted_on_flagged_post
+ options.merge!({ reviewable: reviewable, notify_responders: true, parent_post: post })
+ end
replies.each { |reply| PostDestroyer.new(performed_by, reply, options).destroy }
end
@@ -66,9 +70,11 @@ class PostDestroyer
topic_payload = WebHook.generate_payload(:topic, topic_view, WebHookTopicViewSerializer)
end
- delete_removed_posts_after = @opts[:delete_removed_posts_after] || SiteSetting.delete_removed_posts_after
+ delete_removed_posts_after =
+ @opts[:delete_removed_posts_after] || SiteSetting.delete_removed_posts_after
- if delete_removed_posts_after < 1 || post_is_reviewable? || Guardian.new(@user).can_moderate_topic?(topic) || permanent?
+ if delete_removed_posts_after < 1 || post_is_reviewable? ||
+ Guardian.new(@user).can_moderate_topic?(topic) || permanent?
perform_delete
elsif @user.id == @post.user_id
mark_for_deletion(delete_removed_posts_after)
@@ -89,7 +95,8 @@ class PostDestroyer
end
def recover
- if (post_is_reviewable? || Guardian.new(@user).can_moderate_topic?(@post.topic)) && @post.deleted_at
+ if (post_is_reviewable? || Guardian.new(@user).can_moderate_topic?(@post.topic)) &&
+ @post.deleted_at
staff_recovered
elsif @user.staff? || @user.id == @post.user_id
user_recovered
@@ -107,7 +114,13 @@ class PostDestroyer
if @post.is_first_post?
UserActionManager.topic_created(topic)
DiscourseEvent.trigger(:topic_recovered, topic, @user)
- StaffActionLogger.new(@user).log_topic_delete_recover(topic, "recover_topic", @opts.slice(:context)) if @user.id != @post.user_id
+ if @user.id != @post.user_id
+ StaffActionLogger.new(@user).log_topic_delete_recover(
+ topic,
+ "recover_topic",
+ @opts.slice(:context),
+ )
+ end
update_imap_sync(@post, false)
end
end
@@ -170,7 +183,11 @@ class PostDestroyer
if @user.id != @post.user_id && !@opts[:skip_staff_log]
if @post.topic && @post.is_first_post?
- StaffActionLogger.new(@user).log_topic_delete_recover(@post.topic, "delete_topic", @opts.slice(:context))
+ StaffActionLogger.new(@user).log_topic_delete_recover(
+ @post.topic,
+ "delete_topic",
+ @opts.slice(:context),
+ )
else
StaffActionLogger.new(@user).log_post_deletion(@post, @opts.slice(:context))
end
@@ -187,8 +204,14 @@ class PostDestroyer
DB.after_commit do
if @opts[:reviewable]
- notify_deletion(@opts[:reviewable], { notify_responders: @opts[:notify_responders], parent_post: @opts[:parent_post] })
- ignore(@post.reviewable_flag) if @post.reviewable_flag && SiteSetting.notify_users_after_responses_deleted_on_flagged_post
+ notify_deletion(
+ @opts[:reviewable],
+ { notify_responders: @opts[:notify_responders], parent_post: @opts[:parent_post] },
+ )
+ if @post.reviewable_flag &&
+ SiteSetting.notify_users_after_responses_deleted_on_flagged_post
+ ignore(@post.reviewable_flag)
+ end
elsif reviewable = @post.reviewable_flag
@opts[:defer_flags] ? ignore(reviewable) : agree(reviewable)
end
@@ -198,24 +221,34 @@ class PostDestroyer
update_imap_sync(@post, true) if @post.topic&.deleted_at
feature_users_in_the_topic if @post.topic
@post.publish_change_to_clients!(permanent? ? :destroyed : :deleted) if @post.topic
- TopicTrackingState.send(permanent? ? :publish_destroy : :publish_delete, @post.topic) if @post.topic && @post.post_number == 1
+ if @post.topic && @post.post_number == 1
+ TopicTrackingState.send(permanent? ? :publish_destroy : :publish_delete, @post.topic)
+ end
end
def permanent?
- @opts[:force_destroy] || (@opts[:permanent] && @user == @post.user && @post.topic.private_message?)
+ @opts[:force_destroy] ||
+ (@opts[:permanent] && @user == @post.user && @post.topic.private_message?)
end
# When a user 'deletes' their own post. We just change the text.
def mark_for_deletion(delete_removed_posts_after = SiteSetting.delete_removed_posts_after)
I18n.with_locale(SiteSetting.default_locale) do
-
# don't call revise from within transaction, high risk of deadlock
- key = @post.is_first_post? ? 'js.topic.deleted_by_author_simple' : 'js.post.deleted_by_author_simple'
- @post.revise(@user,
+ key =
+ (
+ if @post.is_first_post?
+ "js.topic.deleted_by_author_simple"
+ else
+ "js.post.deleted_by_author_simple"
+ end
+ )
+ @post.revise(
+ @user,
{ raw: I18n.t(key) },
force_new_version: true,
deleting_post: true,
- skip_validations: true
+ skip_validations: true,
)
Post.transaction do
@@ -237,7 +270,7 @@ class PostDestroyer
# has internal transactions, if we nest then there are some very high risk deadlocks
last_revision = @post.revisions.last
- if last_revision.present? && last_revision.modifications['raw'].present?
+ if last_revision.present? && last_revision.modifications["raw"].present?
@post.revise(@user, { raw: last_revision.modifications["raw"][0] }, force_new_version: true)
end
end
@@ -264,14 +297,16 @@ class PostDestroyer
end
def make_previous_post_the_last_one
- last_post = Post.where("topic_id = ? and id <> ?", @post.topic_id, @post.id)
- .select(:created_at, :user_id, :post_number)
- .where("topic_id = ? and id <> ?", @post.topic_id, @post.id)
- .where.not(user_id: nil)
- .where.not(post_type: Post.types[:whisper])
- .order('created_at desc')
- .limit(1)
- .first
+ last_post =
+ Post
+ .where("topic_id = ? and id <> ?", @post.topic_id, @post.id)
+ .select(:created_at, :user_id, :post_number)
+ .where("topic_id = ? and id <> ?", @post.topic_id, @post.id)
+ .where.not(user_id: nil)
+ .where.not(post_type: Post.types[:whisper])
+ .order("created_at desc")
+ .limit(1)
+ .first
if last_post.present?
topic = @post.topic
@@ -285,8 +320,10 @@ class PostDestroyer
end
def clear_user_posted_flag
- unless Post.exists?(["topic_id = ? and user_id = ? and id <> ?", @post.topic_id, @post.user_id, @post.id])
- TopicUser.where(topic_id: @post.topic_id, user_id: @post.user_id).update_all 'posted = false'
+ unless Post.exists?(
+ ["topic_id = ? and user_id = ? and id <> ?", @post.topic_id, @post.user_id, @post.id],
+ )
+ TopicUser.where(topic_id: @post.topic_id, user_id: @post.user_id).update_all "posted = false"
end
end
@@ -328,7 +365,7 @@ class PostDestroyer
return if @post.user.blank?
allowed_user = @user.human? && @user.staff?
- return unless allowed_user && rs = reviewable.reviewable_scores.order('created_at DESC').first
+ return unless allowed_user && rs = reviewable.reviewable_scores.order("created_at DESC").first
# ReviewableScore#types is a superset of PostActionType#flag_types.
# If the reviewable score type is not on the latter, it means it's not a flag by a user and
@@ -341,31 +378,41 @@ class PostDestroyer
Jobs.enqueue(
:send_system_message,
user_id: @post.user_id,
- message_type: notify_responders ? "flags_agreed_and_post_deleted_for_responders" : "flags_agreed_and_post_deleted",
+ message_type:
+ (
+ if notify_responders
+ "flags_agreed_and_post_deleted_for_responders"
+ else
+ "flags_agreed_and_post_deleted"
+ end
+ ),
message_options: {
flagged_post_raw_content: notify_responders ? options[:parent_post].raw : @post.raw,
flagged_post_response_raw_content: @post.raw,
url: notify_responders ? options[:parent_post].url : @post.url,
- flag_reason: I18n.t(
- "flag_reasons#{".responder" if notify_responders}.#{flag_type}",
- locale: SiteSetting.default_locale,
- base_path: Discourse.base_path
- )
- }
+ flag_reason:
+ I18n.t(
+ "flag_reasons#{".responder" if notify_responders}.#{flag_type}",
+ locale: SiteSetting.default_locale,
+ base_path: Discourse.base_path,
+ ),
+ },
)
end
def trash_user_actions
- UserAction.where(target_post_id: @post.id).each do |ua|
- row = {
- action_type: ua.action_type,
- user_id: ua.user_id,
- acting_user_id: ua.acting_user_id,
- target_topic_id: ua.target_topic_id,
- target_post_id: ua.target_post_id
- }
- UserAction.remove_action!(row)
- end
+ UserAction
+ .where(target_post_id: @post.id)
+ .each do |ua|
+ row = {
+ action_type: ua.action_type,
+ user_id: ua.user_id,
+ acting_user_id: ua.acting_user_id,
+ target_topic_id: ua.target_topic_id,
+ target_post_id: ua.target_post_id,
+ }
+ UserAction.remove_action!(row)
+ end
end
def remove_associated_replies
@@ -378,14 +425,15 @@ class PostDestroyer
end
def remove_associated_notifications
- Notification
- .where(topic_id: @post.topic_id, post_number: @post.post_number)
- .delete_all
+ Notification.where(topic_id: @post.topic_id, post_number: @post.post_number).delete_all
end
def update_associated_category_latest_topic
return unless @post.topic && @post.topic.category
- return unless @post.id == @post.topic.category.latest_post_id || (@post.is_first_post? && @post.topic_id == @post.topic.category.latest_topic_id)
+ unless @post.id == @post.topic.category.latest_post_id ||
+ (@post.is_first_post? && @post.topic_id == @post.topic.category.latest_topic_id)
+ return
+ end
@post.topic.category.update_latest
end
@@ -398,13 +446,18 @@ class PostDestroyer
author.create_user_stat if author.user_stat.nil?
if @post.created_at == author.user_stat.first_post_created_at
- author.user_stat.update!(first_post_created_at: author.posts.order('created_at ASC').first.try(:created_at))
+ author.user_stat.update!(
+ first_post_created_at: author.posts.order("created_at ASC").first.try(:created_at),
+ )
end
UserStatCountUpdater.decrement!(@post)
if @post.created_at == author.last_posted_at
- author.update_column(:last_posted_at, author.posts.order('created_at DESC').first.try(:created_at))
+ author.update_column(
+ :last_posted_at,
+ author.posts.order("created_at DESC").first.try(:created_at),
+ )
end
if @post.is_first_post? && @post.topic && [email protected]_message?
@@ -421,16 +474,27 @@ class PostDestroyer
end
def update_post_counts(operator)
- counts = Post.where(
- post_type: Post.types[:regular], topic_id: @post.topic_id
- ).where('post_number > 1').group(:user_id).count
+ counts =
+ Post
+ .where(post_type: Post.types[:regular], topic_id: @post.topic_id)
+ .where("post_number > 1")
+ .group(:user_id)
+ .count
counts.each do |user_id, count|
if user_stat = UserStat.where(user_id: user_id).first
if operator == :decrement
- UserStatCountUpdater.set!(user_stat: user_stat, count: user_stat.post_count - count, count_column: :post_count)
+ UserStatCountUpdater.set!(
+ user_stat: user_stat,
+ count: user_stat.post_count - count,
+ count_column: :post_count,
+ )
else
- UserStatCountUpdater.set!(user_stat: user_stat, count: user_stat.post_count + count, count_column: :post_count)
+ UserStatCountUpdater.set!(
+ user_stat: user_stat,
+ count: user_stat.post_count + count,
+ count_column: :post_count,
+ )
end
end
end
diff --git a/lib/post_jobs_enqueuer.rb b/lib/post_jobs_enqueuer.rb
index 93a29f5663f..a1c0573f084 100644
--- a/lib/post_jobs_enqueuer.rb
+++ b/lib/post_jobs_enqueuer.rb
@@ -25,7 +25,8 @@ class PostJobsEnqueuer
private
def enqueue_post_alerts
- Jobs.enqueue(:post_alert,
+ Jobs.enqueue(
+ :post_alert,
post_id: @post.id,
new_record: true,
options: @opts[:post_alert_options],
@@ -47,9 +48,7 @@ class PostJobsEnqueuer
return if @topic.visible?
return if @post.post_type != Post.types[:regular]
- if @topic.topic_embed.present?
- Jobs.enqueue(:make_embedded_topic_visible, topic_id: @topic.id)
- end
+ Jobs.enqueue(:make_embedded_topic_visible, topic_id: @topic.id) if @topic.topic_embed.present?
end
def after_post_create
@@ -83,8 +82,7 @@ class PostJobsEnqueuer
end
def skip_after_create?
- @opts[:import_mode] ||
- @post.post_type == Post.types[:moderator_action] ||
+ @opts[:import_mode] || @post.post_type == Post.types[:moderator_action] ||
@post.post_type == Post.types[:small_action]
end
end
diff --git a/lib/post_merger.rb b/lib/post_merger.rb
index 81356f3a500..22c32adfbf9 100644
--- a/lib/post_merger.rb
+++ b/lib/post_merger.rb
@@ -1,7 +1,8 @@
# frozen_string_literal: true
class PostMerger
- class CannotMergeError < StandardError; end
+ class CannotMergeError < StandardError
+ end
def initialize(user, posts)
@user = user
@@ -17,10 +18,11 @@ class PostMerger
guardian = Guardian.new(@user)
ensure_can_merge!(guardian)
- posts = @posts.sort_by do |post|
- guardian.ensure_can_delete!(post)
- post.post_number
- end
+ posts =
+ @posts.sort_by do |post|
+ guardian.ensure_can_delete!(post)
+ post.post_number
+ end
post_content = posts.map(&:raw)
post = posts.pop
@@ -28,13 +30,13 @@ class PostMerger
merged_post_raw = post_content.join("\n\n")
changes = {
raw: merged_post_raw,
- edit_reason: I18n.t("merge_posts.edit_reason", count: posts.length, username: @user.username)
+ edit_reason: I18n.t("merge_posts.edit_reason", count: posts.length, username: @user.username),
}
ensure_max_post_length!(merged_post_raw)
- PostRevisor.new(post, post.topic).revise!(@user, changes) do
- posts.each { |p| PostDestroyer.new(@user, p).destroy }
- end
+ PostRevisor
+ .new(post, post.topic)
+ .revise!(@user, changes) { posts.each { |p| PostDestroyer.new(@user, p).destroy } }
end
private
diff --git a/lib/post_revisor.rb b/lib/post_revisor.rb
index d6dd390ec9d..1ce1ef284be 100644
--- a/lib/post_revisor.rb
+++ b/lib/post_revisor.rb
@@ -1,10 +1,9 @@
# frozen_string_literal: true
require "edit_rate_limiter"
-require 'post_locker'
+require "post_locker"
class PostRevisor
-
# Helps us track changes to a topic.
#
# It's passed to `track_topic_fields` callbacks so they can record if they
@@ -41,7 +40,7 @@ class PostRevisor
end
end
- POST_TRACKED_FIELDS = %w{raw cooked edit_reason user_id wiki post_type}
+ POST_TRACKED_FIELDS = %w[raw cooked edit_reason user_id wiki post_type]
attr_reader :category_changed, :post_revision
@@ -68,11 +67,7 @@ class PostRevisor
end
def self.track_and_revise(topic_changes, field, attribute)
- topic_changes.record_change(
- field,
- topic_changes.topic.public_send(field),
- attribute
- )
+ topic_changes.record_change(field, topic_changes.topic.public_send(field), attribute)
topic_changes.topic.public_send("#{field}=", attribute)
end
@@ -86,16 +81,22 @@ class PostRevisor
track_topic_field(:category_id) do |tc, category_id, fields|
if category_id == 0 && tc.topic.private_message?
- tc.record_change('category_id', tc.topic.category_id, nil)
+ tc.record_change("category_id", tc.topic.category_id, nil)
tc.topic.category_id = nil
elsif category_id == 0 || tc.guardian.can_move_topic_to_category?(category_id)
tags = fields[:tags] || tc.topic.tags.map(&:name)
- if category_id != 0 && !DiscourseTagging.validate_min_required_tags_for_category(tc.guardian, tc.topic, Category.find(category_id), tags)
+ if category_id != 0 &&
+ !DiscourseTagging.validate_min_required_tags_for_category(
+ tc.guardian,
+ tc.topic,
+ Category.find(category_id),
+ tags,
+ )
tc.check_result(false)
next
end
- tc.record_change('category_id', tc.topic.category_id, category_id)
+ tc.record_change("category_id", tc.topic.category_id, category_id)
tc.check_result(tc.topic.change_category_to_id(category_id))
end
end
@@ -109,7 +110,7 @@ class PostRevisor
next
end
if prev_tags.sort != tags.sort
- tc.record_change('tags', prev_tags, tags)
+ tc.record_change("tags", prev_tags, tags)
DB.after_commit do
post = tc.topic.ordered_posts.first
notified_user_ids = [post.user_id, post.last_editor_id].uniq
@@ -118,7 +119,7 @@ class PostRevisor
:notify_tag_change,
post_id: post.id,
notified_user_ids: notified_user_ids,
- diff_tags: ((tags - prev_tags) | (prev_tags - tags))
+ diff_tags: ((tags - prev_tags) | (prev_tags - tags)),
)
end
end
@@ -128,10 +129,10 @@ class PostRevisor
track_topic_field(:featured_link) do |topic_changes, featured_link|
if !SiteSetting.topic_featured_link_enabled ||
- !topic_changes.guardian.can_edit_featured_link?(topic_changes.topic.category_id)
+ !topic_changes.guardian.can_edit_featured_link?(topic_changes.topic.category_id)
topic_changes.check_result(false)
else
- topic_changes.record_change('featured_link', topic_changes.topic.featured_link, featured_link)
+ topic_changes.record_change("featured_link", topic_changes.topic.featured_link, featured_link)
topic_changes.topic.featured_link = featured_link
end
end
@@ -161,9 +162,7 @@ class PostRevisor
@fields.delete(:edit_reason) if @fields[:edit_reason].blank?
Post.plugin_permitted_update_params.each do |field, val|
- if @fields.key?(field) && val[:plugin].enabled?
- val[:handler].call(@post, @fields[field])
- end
+ val[:handler].call(@post, @fields[field]) if @fields.key?(field) && val[:plugin].enabled?
end
if !should_revise?
@@ -182,7 +181,8 @@ class PostRevisor
@revised_at = @opts[:revised_at] || Time.now
@last_version_at = @post.last_version_at || Time.now
- if guardian.affected_by_slow_mode?(@topic) && !grace_period_edit? && SiteSetting.slow_mode_prevents_editing
+ if guardian.affected_by_slow_mode?(@topic) && !grace_period_edit? &&
+ SiteSetting.slow_mode_prevents_editing
@post.errors.add(:base, I18n.t("cannot_edit_on_slow_mode"))
return false
end
@@ -201,9 +201,7 @@ class PostRevisor
@skip_revision = false
@skip_revision = @opts[:skip_revision] if @opts.has_key?(:skip_revision)
- if @post.incoming_email&.imap_uid
- @post.incoming_email&.update(imap_sync: true)
- end
+ @post.incoming_email&.update(imap_sync: true) if @post.incoming_email&.imap_uid
old_raw = @post.raw
@@ -225,27 +223,23 @@ class PostRevisor
# Lock the post by default if the appropriate setting is true
if (
- SiteSetting.staff_edit_locks_post? &&
- @fields.has_key?('raw') &&
- @editor.staff? &&
- @editor != Discourse.system_user &&
- )
+ SiteSetting.staff_edit_locks_post? && [email protected]? && @fields.has_key?("raw") &&
+ @editor.staff? && @editor != Discourse.system_user && [email protected]&.staff?
+ )
PostLocker.new(@post, @editor).lock
end
# We log staff/group moderator edits to posts
if (
- (@editor.staff? || (@post.is_category_description? && guardian.can_edit_category_description?(@post.topic.category))) &&
- @editor.id != @post.user_id &&
- @fields.has_key?('raw') &&
- !@opts[:skip_staff_log]
- )
- StaffActionLogger.new(@editor).log_post_edit(
- @post,
- old_raw: old_raw
- )
+ (
+ @editor.staff? ||
+ (
+ @post.is_category_description? &&
+ guardian.can_edit_category_description?(@post.topic.category)
+ )
+ ) && @editor.id != @post.user_id && @fields.has_key?("raw") && !@opts[:skip_staff_log]
+ )
+ StaffActionLogger.new(@editor).log_post_edit(@post, old_raw: old_raw)
end
# WARNING: do not pull this into the transaction
@@ -266,9 +260,7 @@ class PostRevisor
TopicLink.extract_from(@post)
- if should_create_new_version?
- ReviewablePost.queue_for_review_if_possible(@post, @editor)
- end
+ ReviewablePost.queue_for_review_if_possible(@post, @editor) if should_create_new_version?
successfully_saved_post_and_topic
end
@@ -283,9 +275,7 @@ class PostRevisor
def post_changed?
POST_TRACKED_FIELDS.each do |field|
- if @fields.has_key?(field) && @fields[field] != @post.public_send(field)
- return true
- end
+ return true if @fields.has_key?(field) && @fields[field] != @post.public_send(field)
end
false
end
@@ -308,7 +298,8 @@ class PostRevisor
def should_create_new_version?
return false if @skip_revision
- edited_by_another_user? || !grace_period_edit? || owner_changed? || force_new_version? || edit_reason_specified?
+ edited_by_another_user? || !grace_period_edit? || owner_changed? || force_new_version? ||
+ edit_reason_specified?
end
def edit_reason_specified?
@@ -350,11 +341,10 @@ class PostRevisor
end
def diff_size(before, after)
- @diff_size ||= begin
- ONPDiff.new(before, after).short_diff.sum do |str, type|
- type == :common ? 0 : str.size
+ @diff_size ||=
+ begin
+ ONPDiff.new(before, after).short_diff.sum { |str, type| type == :common ? 0 : str.size }
end
- end
end
def grace_period_edit?
@@ -362,14 +352,13 @@ class PostRevisor
return false if @post.reviewable_flag.present?
if new_raw = @fields[:raw]
-
max_diff = SiteSetting.editing_grace_period_max_diff.to_i
if @editor.staff? || (@editor.trust_level > 1)
max_diff = SiteSetting.editing_grace_period_max_diff_high_trust.to_i
end
if (original_raw.size - new_raw.size).abs > max_diff ||
- diff_size(original_raw, new_raw) > max_diff
+ diff_size(original_raw, new_raw) > max_diff
return false
end
end
@@ -410,13 +399,15 @@ class PostRevisor
prev_owner = User.find(@post.user_id)
new_owner = User.find(@fields["user_id"])
- UserAction.where(target_post_id: @post.id)
+ UserAction
+ .where(target_post_id: @post.id)
.where(user_id: prev_owner.id)
.where(action_type: USER_ACTIONS_TO_REMOVE)
.update_all(user_id: new_owner.id)
if @post.post_number == 1
- UserAction.where(target_topic_id: @post.topic_id)
+ UserAction
+ .where(target_topic_id: @post.topic_id)
.where(user_id: prev_owner.id)
.where(action_type: UserAction::NEW_TOPIC)
.update_all(user_id: new_owner.id)
@@ -424,15 +415,13 @@ class PostRevisor
end
POST_TRACKED_FIELDS.each do |field|
- if @fields.has_key?(field)
- @post.public_send("#{field}=", @fields[field])
- end
+ @post.public_send("#{field}=", @fields[field]) if @fields.has_key?(field)
end
- @post.edit_reason = @fields[:edit_reason] if should_create_new_version?
+ @post.edit_reason = @fields[:edit_reason] if should_create_new_version?
@post.last_editor_id = @editor.id
- @post.word_count = @fields[:raw].scan(/[[:word:]]+/).size if @fields.has_key?(:raw)
- @post.self_edits += 1 if self_edit?
+ @post.word_count = @fields[:raw].scan(/[[:word:]]+/).size if @fields.has_key?(:raw)
+ @post.self_edits += 1 if self_edit?
@post.extract_quoted_post_numbers
@@ -444,10 +433,12 @@ class PostRevisor
# post owner changed
if prev_owner && new_owner && prev_owner != new_owner
- likes = UserAction.where(target_post_id: @post.id)
- .where(user_id: prev_owner.id)
- .where(action_type: UserAction::WAS_LIKED)
- .update_all(user_id: new_owner.id)
+ likes =
+ UserAction
+ .where(target_post_id: @post.id)
+ .where(user_id: prev_owner.id)
+ .where(action_type: UserAction::WAS_LIKED)
+ .update_all(user_id: new_owner.id)
private_message = @topic.private_message?
@@ -459,7 +450,9 @@ class PostRevisor
end
if @post.created_at == prev_owner.user_stat.first_post_created_at
- prev_owner_user_stat.update!(first_post_created_at: prev_owner.posts.order('created_at ASC').first.try(:created_at))
+ prev_owner_user_stat.update!(
+ first_post_created_at: prev_owner.posts.order("created_at ASC").first.try(:created_at),
+ )
end
new_owner_user_stat = new_owner.user_stat
@@ -480,19 +473,21 @@ class PostRevisor
return unless editing_a_flagged_and_hidden_post?
flaggers = []
- @post.post_actions.where(post_action_type_id: PostActionType.flag_types_without_custom.values).each do |action|
- flaggers << action.user if action.user
- action.remove_act!(Discourse.system_user)
- end
+ @post
+ .post_actions
+ .where(post_action_type_id: PostActionType.flag_types_without_custom.values)
+ .each do |action|
+ flaggers << action.user if action.user
+ action.remove_act!(Discourse.system_user)
+ end
@post.unhide!
PostActionNotifier.after_post_unhide(@post, flaggers)
end
def editing_a_flagged_and_hidden_post?
- self_edit? &&
- @post.hidden &&
- @post.hidden_reason_id == Post.hidden_reasons[:flag_threshold_reached]
+ self_edit? && @post.hidden &&
+ @post.hidden_reason_id == Post.hidden_reasons[:flag_threshold_reached]
end
def update_topic
@@ -519,21 +514,20 @@ class PostRevisor
def create_revision
modifications = post_changes.merge(@topic_changes.diff)
- if modifications["raw"]
- modifications["raw"][0] = cached_original_raw || modifications["raw"][0]
- end
+ modifications["raw"][0] = cached_original_raw || modifications["raw"][0] if modifications["raw"]
if modifications["cooked"]
modifications["cooked"][0] = cached_original_cooked || modifications["cooked"][0]
end
- @post_revision = PostRevision.create!(
- user_id: @post.last_editor_id,
- post_id: @post.id,
- number: @post.version,
- modifications: modifications,
- hidden: only_hidden_tags_changed?
- )
+ @post_revision =
+ PostRevision.create!(
+ user_id: @post.last_editor_id,
+ post_id: @post.id,
+ number: @post.version,
+ modifications: modifications,
+ hidden: only_hidden_tags_changed?,
+ )
end
def update_revision
@@ -557,7 +551,9 @@ class PostRevisor
# should probably do this before saving the post!
if revision.modifications.empty?
revision.destroy
- @post.last_editor_id = PostRevision.where(post_id: @post.id).order(number: :desc).pluck_first(:user_id) || @post.user_id
+ @post.last_editor_id =
+ PostRevision.where(post_id: @post.id).order(number: :desc).pluck_first(:user_id) ||
+ @post.user_id
@post.version -= 1
@post.public_version -= 1
@post.save(validate: @validate_post)
@@ -592,11 +588,8 @@ class PostRevisor
end
def bypass_bump?
- !@post_successfully_saved ||
- @topic_changes.errored? ||
- @opts[:bypass_bump] == true ||
- @post.whisper? ||
- only_hidden_tags_changed?
+ !@post_successfully_saved || @topic_changes.errored? || @opts[:bypass_bump] == true ||
+ @post.whisper? || only_hidden_tags_changed?
end
def only_hidden_tags_changed?
@@ -606,18 +599,14 @@ class PostRevisor
if modifications.keys.size == 1 && (tags_diff = modifications["tags"]).present?
a, b = tags_diff[0] || [], tags_diff[1] || []
changed_tags = ((a + b) - (a & b)).map(&:presence).compact
- if (changed_tags - hidden_tag_names).empty?
- return true
- end
+ return true if (changed_tags - hidden_tag_names).empty?
end
false
end
def is_last_post?
- !Post.where(topic_id: @topic.id)
- .where("post_number > ?", @post.post_number)
- .exists?
+ !Post.where(topic_id: @topic.id).where("post_number > ?", @post.post_number).exists?
end
def plugin_callbacks
@@ -672,13 +661,16 @@ class PostRevisor
end
def update_topic_word_counts
- DB.exec("UPDATE topics
+ DB.exec(
+ "UPDATE topics
SET word_count = (
SELECT SUM(COALESCE(posts.word_count, 0))
FROM posts
WHERE posts.topic_id = :topic_id
)
- WHERE topics.id = :topic_id", topic_id: @topic.id)
+ WHERE topics.id = :topic_id",
+ topic_id: @topic.id,
+ )
end
def alert_users
@@ -710,5 +702,4 @@ class PostRevisor
def guardian
@guardian ||= Guardian.new(@editor)
end
-
end
diff --git a/lib/presence_channel.rb b/lib/presence_channel.rb
index 83d6cd066ee..ff6fa3d0f07 100644
--- a/lib/presence_channel.rb
+++ b/lib/presence_channel.rb
@@ -3,10 +3,14 @@
# The server-side implementation of PresenceChannels. See also {PresenceController}
# and +app/assets/javascripts/discourse/app/services/presence.js+
class PresenceChannel
- class NotFound < StandardError; end
- class InvalidAccess < StandardError; end
- class ConfigNotLoaded < StandardError; end
- class InvalidConfig < StandardError; end
+ class NotFound < StandardError
+ end
+ class InvalidAccess < StandardError
+ end
+ class ConfigNotLoaded < StandardError
+ end
+ class InvalidConfig < StandardError
+ end
class State
include ActiveModel::Serialization
@@ -15,7 +19,7 @@ class PresenceChannel
attr_reader :user_ids
attr_reader :count
- def initialize(message_bus_last_id: , user_ids: nil, count: nil)
+ def initialize(message_bus_last_id:, user_ids: nil, count: nil)
raise "user_ids or count required" if user_ids.nil? && count.nil?
@message_bus_last_id = message_bus_last_id
@user_ids = user_ids
@@ -39,7 +43,13 @@ class PresenceChannel
attr_accessor :public, :allowed_user_ids, :allowed_group_ids, :count_only, :timeout
- def initialize(public: false, allowed_user_ids: nil, allowed_group_ids: nil, count_only: false, timeout: nil)
+ def initialize(
+ public: false,
+ allowed_user_ids: nil,
+ allowed_group_ids: nil,
+ count_only: false,
+ timeout: nil
+ )
@public = public
@allowed_user_ids = allowed_user_ids
@allowed_group_ids = allowed_group_ids
@@ -114,13 +124,14 @@ class PresenceChannel
raise PresenceChannel::InvalidAccess if !can_enter?(user_id: user_id)
mutex_value = SecureRandom.hex
- result = retry_on_mutex_error do
- PresenceChannel.redis_eval(
- :present,
- redis_keys,
- [name, user_id, client_id, (Time.zone.now + timeout).to_i, mutex_value]
- )
- end
+ result =
+ retry_on_mutex_error do
+ PresenceChannel.redis_eval(
+ :present,
+ redis_keys,
+ [name, user_id, client_id, (Time.zone.now + timeout).to_i, mutex_value],
+ )
+ end
if result == 1
begin
@@ -134,13 +145,10 @@ class PresenceChannel
# Immediately mark a user's client as leaving the channel
def leave(user_id:, client_id:)
mutex_value = SecureRandom.hex
- result = retry_on_mutex_error do
- PresenceChannel.redis_eval(
- :leave,
- redis_keys,
- [name, user_id, client_id, nil, mutex_value]
- )
- end
+ result =
+ retry_on_mutex_error do
+ PresenceChannel.redis_eval(:leave, redis_keys, [name, user_id, client_id, nil, mutex_value])
+ end
if result == 1
begin
@@ -156,19 +164,9 @@ class PresenceChannel
# @param [Boolean] count_only set true to skip fetching the list of user ids from redis
def state(count_only: config.count_only)
if count_only
- last_id, count = retry_on_mutex_error do
- PresenceChannel.redis_eval(
- :count,
- redis_keys,
- )
- end
+ last_id, count = retry_on_mutex_error { PresenceChannel.redis_eval(:count, redis_keys) }
else
- last_id, ids = retry_on_mutex_error do
- PresenceChannel.redis_eval(
- :user_ids,
- redis_keys,
- )
- end
+ last_id, ids = retry_on_mutex_error { PresenceChannel.redis_eval(:user_ids, redis_keys) }
end
count ||= ids&.count
last_id = nil if last_id == -1
@@ -193,13 +191,10 @@ class PresenceChannel
# Automatically expire all users which have not been 'present' for more than +DEFAULT_TIMEOUT+
def auto_leave
mutex_value = SecureRandom.hex
- left_user_ids = retry_on_mutex_error do
- PresenceChannel.redis_eval(
- :auto_leave,
- redis_keys,
- [name, Time.zone.now.to_i, mutex_value]
- )
- end
+ left_user_ids =
+ retry_on_mutex_error do
+ PresenceChannel.redis_eval(:auto_leave, redis_keys, [name, Time.zone.now.to_i, mutex_value])
+ end
if !left_user_ids.empty?
begin
@@ -222,20 +217,21 @@ class PresenceChannel
# Designed to be run periodically. Checks the channel list for channels with expired members,
# and runs auto_leave for each eligible channel
def self.auto_leave_all
- channels_with_expiring_members = PresenceChannel.redis.zrangebyscore(redis_key_channel_list, '-inf', Time.zone.now.to_i)
- channels_with_expiring_members.each do |name|
- new(name, raise_not_found: false).auto_leave
- end
+ channels_with_expiring_members =
+ PresenceChannel.redis.zrangebyscore(redis_key_channel_list, "-inf", Time.zone.now.to_i)
+ channels_with_expiring_members.each { |name| new(name, raise_not_found: false).auto_leave }
end
# Clear all known channels. This is intended for debugging/development only
def self.clear_all!
- channels = PresenceChannel.redis.zrangebyscore(redis_key_channel_list, '-inf', '+inf')
- channels.each do |name|
- new(name, raise_not_found: false).clear
- end
-
- config_cache_keys = PresenceChannel.redis.scan_each(match: Discourse.redis.namespace_key("_presence_*_config")).to_a
+ channels = PresenceChannel.redis.zrangebyscore(redis_key_channel_list, "-inf", "+inf")
+ channels.each { |name| new(name, raise_not_found: false).clear }
+
+ config_cache_keys =
+ PresenceChannel
+ .redis
+ .scan_each(match: Discourse.redis.namespace_key("_presence_*_config"))
+ .to_a
PresenceChannel.redis.del(*config_cache_keys) if config_cache_keys.present?
end
@@ -275,8 +271,12 @@ class PresenceChannel
#
# Plugins should use the {Plugin::Instance.register_presence_channel_prefix} API instead
def self.register_prefix(prefix, &block)
- raise "PresenceChannel prefix #{prefix} must match [a-zA-Z0-9_-]+" unless prefix.match? /[a-zA-Z0-9_-]+/
- raise "PresenceChannel prefix #{prefix} already registered" if @@configuration_blocks&.[](prefix)
+ unless prefix.match? /[a-zA-Z0-9_-]+/
+ raise "PresenceChannel prefix #{prefix} must match [a-zA-Z0-9_-]+"
+ end
+ if @@configuration_blocks&.[](prefix)
+ raise "PresenceChannel prefix #{prefix} already registered"
+ end
@@configuration_blocks[prefix] = block
end
@@ -289,30 +289,30 @@ class PresenceChannel
private
def fetch_config(use_cache: true)
- cached_config = if use_cache
- PresenceChannel.redis.get(redis_key_config)
- end
+ cached_config = (PresenceChannel.redis.get(redis_key_config) if use_cache)
if cached_config == Config::NOT_FOUND
raise PresenceChannel::NotFound
elsif cached_config
Config.from_json(cached_config)
else
- prefix = name[/\/([a-zA-Z0-9_-]+)\/.*/, 1]
+ prefix = name[%r{/([a-zA-Z0-9_-]+)/.*}, 1]
raise PresenceChannel::NotFound if prefix.nil?
config_block = @@configuration_blocks[prefix]
- config_block ||= DiscoursePluginRegistry.presence_channel_prefixes.find { |t| t[0] == prefix }&.[](1)
+ config_block ||=
+ DiscoursePluginRegistry.presence_channel_prefixes.find { |t| t[0] == prefix }&.[](1)
raise PresenceChannel::NotFound if config_block.nil?
result = config_block.call(name)
- to_cache = if result.is_a? Config
- result.to_json
- elsif result.nil?
- Config::NOT_FOUND
- else
- raise InvalidConfig.new "Expected PresenceChannel::Config or nil. Got a #{result.class.name}"
- end
+ to_cache =
+ if result.is_a? Config
+ result.to_json
+ elsif result.nil?
+ Config::NOT_FOUND
+ else
+ raise InvalidConfig.new "Expected PresenceChannel::Config or nil. Got a #{result.class.name}"
+ end
PresenceChannel.redis.set(redis_key_config, to_cache, ex: CONFIG_CACHE_SECONDS)
raise PresenceChannel::NotFound if result.nil?
@@ -330,7 +330,10 @@ class PresenceChannel
message["leaving_user_ids"] = leaving_user_ids if leaving_user_ids.present?
if entering_user_ids.present?
users = User.where(id: entering_user_ids)
- message["entering_users"] = ActiveModel::ArraySerializer.new(users, each_serializer: BasicUserSerializer)
+ message["entering_users"] = ActiveModel::ArraySerializer.new(
+ users,
+ each_serializer: BasicUserSerializer,
+ )
end
end
@@ -367,11 +370,7 @@ class PresenceChannel
end
def release_mutex(mutex_value)
- PresenceChannel.redis_eval(
- :release_mutex,
- [redis_key_mutex],
- [mutex_value]
- )
+ PresenceChannel.redis_eval(:release_mutex, [redis_key_mutex], [mutex_value])
end
def retry_on_mutex_error
@@ -398,7 +397,13 @@ class PresenceChannel
end
def redis_keys
- [redis_key_zlist, redis_key_hash, self.class.redis_key_channel_list, message_bus_last_id_key, redis_key_mutex]
+ [
+ redis_key_zlist,
+ redis_key_hash,
+ self.class.redis_key_channel_list,
+ message_bus_last_id_key,
+ redis_key_mutex,
+ ]
end
# The zlist is a list of client_ids, ranked by their expiration timestamp
diff --git a/lib/pretty_text.rb b/lib/pretty_text.rb
index 632dcabd915..56a4f0349ff 100644
--- a/lib/pretty_text.rb
+++ b/lib/pretty_text.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-require 'mini_racer'
-require 'nokogiri'
-require 'erb'
+require "mini_racer"
+require "nokogiri"
+require "erb"
module PrettyText
DANGEROUS_BIDI_CHARACTERS = [
@@ -57,21 +57,19 @@ module PrettyText
# Look for vendored stuff
vendor_root = "#{Rails.root}/vendor/assets/javascripts/"
filename = find_file(vendor_root, part_name)
- if filename
- ctx.eval(File.read("#{vendor_root}#{filename}"))
- end
+ ctx.eval(File.read("#{vendor_root}#{filename}")) if filename
end
end
def self.ctx_load_directory(ctx, path)
root_path = "#{Rails.root}/app/assets/javascripts/"
Dir["#{root_path}#{path}/**/*"].sort.each do |f|
- apply_es6_file(ctx, root_path, f.sub(root_path, '').sub(/\.js(.es6)?$/, ''))
+ apply_es6_file(ctx, root_path, f.sub(root_path, "").sub(/\.js(.es6)?$/, ""))
end
end
def self.create_es6_context
- ctx = MiniRacer::Context.new(timeout: 25000, ensure_gc_after_idle: 2000)
+ ctx = MiniRacer::Context.new(timeout: 25_000, ensure_gc_after_idle: 2000)
ctx.eval("window = {}; window.devicePixelRatio = 2;") # hack to make code think stuff is retina
@@ -118,19 +116,15 @@ module PrettyText
to_load << a if File.file?(a) && a =~ /discourse-markdown/
end
to_load.uniq.each do |f|
- if f =~ /^.+assets\/javascripts\//
+ if f =~ %r{^.+assets/javascripts/}
root = Regexp.last_match[0]
- apply_es6_file(ctx, root, f.sub(root, '').sub(/\.js(\.es6)?$/, ''))
+ apply_es6_file(ctx, root, f.sub(root, "").sub(/\.js(\.es6)?$/, ""))
end
end
- DiscoursePluginRegistry.vendored_core_pretty_text.each do |vpt|
- ctx.eval(File.read(vpt))
- end
+ DiscoursePluginRegistry.vendored_core_pretty_text.each { |vpt| ctx.eval(File.read(vpt)) }
- DiscoursePluginRegistry.vendored_pretty_text.each do |vpt|
- ctx.eval(File.read(vpt))
- end
+ DiscoursePluginRegistry.vendored_pretty_text.each { |vpt| ctx.eval(File.read(vpt)) }
ctx
end
@@ -209,15 +203,13 @@ module PrettyText
__optInput.customEmojiTranslation = #{Plugin::CustomEmoji.translations.to_json};
__optInput.emojiUnicodeReplacer = __emojiUnicodeReplacer;
__optInput.lookupUploadUrls = __lookupUploadUrls;
- __optInput.censoredRegexp = #{WordWatcher.serializable_word_matcher_regexp(:censor).to_json };
+ __optInput.censoredRegexp = #{WordWatcher.serializable_word_matcher_regexp(:censor).to_json};
__optInput.watchedWordsReplace = #{WordWatcher.word_matcher_regexps(:replace).to_json};
__optInput.watchedWordsLink = #{WordWatcher.word_matcher_regexps(:link).to_json};
__optInput.additionalOptions = #{Site.markdown_additional_options.to_json};
JS
- if opts[:topic_id]
- buffer << "__optInput.topicId = #{opts[:topic_id].to_i};\n"
- end
+ buffer << "__optInput.topicId = #{opts[:topic_id].to_i};\n" if opts[:topic_id]
if opts[:force_quote_link]
buffer << "__optInput.forceQuoteLink = #{opts[:force_quote_link]};\n"
@@ -235,10 +227,13 @@ module PrettyText
end
opts[:hashtag_context] = opts[:hashtag_context] || "topic-composer"
- hashtag_types_as_js = HashtagAutocompleteService.ordered_types_for_context(
- opts[:hashtag_context]
- ).map { |t| "'#{t}'" }.join(",")
- hashtag_icons_as_js = HashtagAutocompleteService.data_source_icons.map { |i| "'#{i}'" }.join(",")
+ hashtag_types_as_js =
+ HashtagAutocompleteService
+ .ordered_types_for_context(opts[:hashtag_context])
+ .map { |t| "'#{t}'" }
+ .join(",")
+ hashtag_icons_as_js =
+ HashtagAutocompleteService.data_source_icons.map { |i| "'#{i}'" }.join(",")
buffer << "__optInput.hashtagTypesInPriorityOrder = [#{hashtag_types_as_js}];\n"
buffer << "__optInput.hashtagIcons = [#{hashtag_icons_as_js}];\n"
@@ -246,9 +241,7 @@ module PrettyText
buffer << ("__pt = new __PrettyText(__textOptions);")
# Be careful disabling sanitization. We allow for custom emails
- if opts[:sanitize] == false
- buffer << ('__pt.disableSanitizer();')
- end
+ buffer << ("__pt.disableSanitizer();") if opts[:sanitize] == false
opts = context.eval(buffer)
@@ -260,15 +253,10 @@ module PrettyText
end
def self.paths_json
- paths = {
- baseUri: Discourse.base_path,
- CDN: Rails.configuration.action_controller.asset_host,
- }
+ paths = { baseUri: Discourse.base_path, CDN: Rails.configuration.action_controller.asset_host }
if SiteSetting.Upload.enable_s3_uploads
- if SiteSetting.Upload.s3_cdn_url.present?
- paths[:S3CDN] = SiteSetting.Upload.s3_cdn_url
- end
+ paths[:S3CDN] = SiteSetting.Upload.s3_cdn_url if SiteSetting.Upload.s3_cdn_url.present?
paths[:S3BaseUrl] = Discourse.store.absolute_base_url
end
@@ -277,12 +265,10 @@ module PrettyText
# leaving this here, cause it invokes v8, don't want to implement twice
def self.avatar_img(avatar_template, size)
- protect do
- v8.eval(<<~JS)
+ protect { v8.eval(<<~JS) }
__paths = #{paths_json};
__utils.avatarImg({size: #{size.inspect}, avatarTemplate: #{avatar_template.inspect}}, __getURL);
JS
- end
end
def self.unescape_emoji(title)
@@ -291,8 +277,7 @@ module PrettyText
set = SiteSetting.emoji_set.inspect
custom = Emoji.custom.map { |e| [e.name, e.url] }.to_h.to_json
- protect do
- v8.eval(<<~JS)
+ protect { v8.eval(<<~JS) }
__paths = #{paths_json};
__performEmojiUnescape(#{title.inspect}, {
getURL: __getURL,
@@ -303,7 +288,6 @@ module PrettyText
inlineEmoji: #{SiteSetting.enable_inline_emoji_translation}
});
JS
- end
end
def self.escape_emoji(title)
@@ -311,14 +295,12 @@ module PrettyText
replace_emoji_shortcuts = SiteSetting.enable_emoji && SiteSetting.enable_emoji_shortcuts
- protect do
- v8.eval(<<~JS)
+ protect { v8.eval(<<~JS) }
__performEmojiEscape(#{title.inspect}, {
emojiShortcuts: #{replace_emoji_shortcuts},
inlineEmoji: #{SiteSetting.enable_inline_emoji_translation}
});
JS
- end
end
def self.cook(text, opts = {})
@@ -334,13 +316,9 @@ module PrettyText
strip_hidden_unicode_bidirectional_characters(doc)
sanitize_hotlinked_media(doc)
- if SiteSetting.enable_mentions
- add_mentions(doc, user_id: opts[:user_id])
- end
+ add_mentions(doc, user_id: opts[:user_id]) if SiteSetting.enable_mentions
- scrubber = Loofah::Scrubber.new do |node|
- node.remove if node.name == 'script'
- end
+ scrubber = Loofah::Scrubber.new { |node| node.remove if node.name == "script" }
loofah_fragment = Loofah.fragment(doc.to_html)
loofah_fragment.scrub!(scrubber).to_html
end
@@ -348,19 +326,22 @@ module PrettyText
def self.strip_hidden_unicode_bidirectional_characters(doc)
return if !DANGEROUS_BIDI_REGEXP.match?(doc.content)
- doc.css("code,pre").each do |code_tag|
- next if !DANGEROUS_BIDI_REGEXP.match?(code_tag.content)
+ doc
+ .css("code,pre")
+ .each do |code_tag|
+ next if !DANGEROUS_BIDI_REGEXP.match?(code_tag.content)
- DANGEROUS_BIDI_CHARACTERS.each do |bidi|
- next if !code_tag.content.include?(bidi)
+ DANGEROUS_BIDI_CHARACTERS.each do |bidi|
+ next if !code_tag.content.include?(bidi)
- formatted = "&lt;U+#{bidi.ord.to_s(16).upcase}&gt;"
- code_tag.inner_html = code_tag.inner_html.gsub(
- bidi,
- "<span class=\"bidi-warning\" title=\"#{I18n.t("post.hidden_bidi_character")}\">#{formatted}</span>"
- )
+ formatted = "&lt;U+#{bidi.ord.to_s(16).upcase}&gt;"
+ code_tag.inner_html =
+ code_tag.inner_html.gsub(
+ bidi,
+ "<span class=\"bidi-warning\" title=\"#{I18n.t("post.hidden_bidi_character")}\">#{formatted}</span>",
+ )
+ end
end
- end
end
def self.sanitize_hotlinked_media(doc)
@@ -368,56 +349,63 @@ module PrettyText
allowed_pattern = allowed_src_pattern
- doc.css("img[src], source[src], source[srcset], track[src]").each do |el|
- if el["src"] && !el["src"].match?(allowed_pattern)
- el[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR] = el.delete("src")
- end
+ doc
+ .css("img[src], source[src], source[srcset], track[src]")
+ .each do |el|
+ if el["src"] && !el["src"].match?(allowed_pattern)
+ el[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR] = el.delete("src")
+ end
- if el["srcset"]
- srcs = el["srcset"].split(',').map { |e| e.split(' ', 2)[0].presence }
- if srcs.any? { |src| !src.match?(allowed_pattern) }
- el[PrettyText::BLOCKED_HOTLINKED_SRCSET_ATTR] = el.delete("srcset")
+ if el["srcset"]
+ srcs = el["srcset"].split(",").map { |e| e.split(" ", 2)[0].presence }
+ if srcs.any? { |src| !src.match?(allowed_pattern) }
+ el[PrettyText::BLOCKED_HOTLINKED_SRCSET_ATTR] = el.delete("srcset")
+ end
end
end
- end
end
def self.add_rel_attributes_to_user_content(doc, add_nofollow)
allowlist = []
domains = SiteSetting.exclude_rel_nofollow_domains
- allowlist = domains.split('|') if domains.present?
+ allowlist = domains.split("|") if domains.present?
site_uri = nil
- doc.css("a").each do |l|
- href = l["href"].to_s
- l["rel"] = "noopener" if l["target"] == "_blank"
-
- begin
- uri = URI(UrlHelper.encode_component(href))
- site_uri ||= URI(Discourse.base_url)
-
- same_domain = !uri.host.present? ||
- uri.host == site_uri.host ||
- uri.host.ends_with?(".#{site_uri.host}") ||
- allowlist.any? { |u| uri.host == u || uri.host.ends_with?(".#{u}") }
-
- l["rel"] = "noopener nofollow ugc" if add_nofollow && !same_domain
- rescue URI::Error
- # add a nofollow anyway
- l["rel"] = "noopener nofollow ugc"
+ doc
+ .css("a")
+ .each do |l|
+ href = l["href"].to_s
+ l["rel"] = "noopener" if l["target"] == "_blank"
+
+ begin
+ uri = URI(UrlHelper.encode_component(href))
+ site_uri ||= URI(Discourse.base_url)
+
+ same_domain =
+ !uri.host.present? || uri.host == site_uri.host ||
+ uri.host.ends_with?(".#{site_uri.host}") ||
+ allowlist.any? { |u| uri.host == u || uri.host.ends_with?(".#{u}") }
+
+ l["rel"] = "noopener nofollow ugc" if add_nofollow && !same_domain
+ rescue URI::Error
+ # add a nofollow anyway
+ l["rel"] = "noopener nofollow ugc"
+ end
end
- end
end
- class DetectedLink < Struct.new(:url, :is_quote); end
+ class DetectedLink < Struct.new(:url, :is_quote)
+ end
def self.extract_links(html)
links = []
doc = Nokogiri::HTML5.fragment(html)
# extract onebox links
- doc.css("aside.onebox[data-onebox-src]").each { |onebox| links << DetectedLink.new(onebox["data-onebox-src"], false) }
+ doc
+ .css("aside.onebox[data-onebox-src]")
+ .each { |onebox| links << DetectedLink.new(onebox["data-onebox-src"], false) }
# remove href inside quotes & oneboxes & elided part
doc.css("aside.quote a, aside.onebox a, .elided a").remove
@@ -426,39 +414,49 @@ module PrettyText
doc.css("a.onebox > img").each { |img| img.parent.remove }
# extract all links
- doc.css("a").each do |a|
- if a["href"].present? && a["href"][0] != "#"
- links << DetectedLink.new(a["href"], false)
+ doc
+ .css("a")
+ .each do |a|
+ links << DetectedLink.new(a["href"], false) if a["href"].present? && a["href"][0] != "#"
end
- end
# extract quotes
- doc.css("aside.quote[data-topic]").each do |aside|
- if aside["data-topic"].present?
- url = +"/t/#{aside["data-topic"]}"
- url << "/#{aside["data-post"]}" if aside["data-post"].present?
- links << DetectedLink.new(url, true)
+ doc
+ .css("aside.quote[data-topic]")
+ .each do |aside|
+ if aside["data-topic"].present?
+ url = +"/t/#{aside["data-topic"]}"
+ url << "/#{aside["data-post"]}" if aside["data-post"].present?
+ links << DetectedLink.new(url, true)
+ end
end
- end
# extract Youtube links
- doc.css("div[data-youtube-id]").each do |div|
- if div["data-youtube-id"].present?
- links << DetectedLink.new("https://www.youtube.com/watch?v=#{div['data-youtube-id']}", false)
+ doc
+ .css("div[data-youtube-id]")
+ .each do |div|
+ if div["data-youtube-id"].present?
+ links << DetectedLink.new(
+ "https://www.youtube.com/watch?v=#{div["data-youtube-id"]}",
+ false,
+ )
+ end
end
- end
links
end
def self.extract_mentions(cooked)
- mentions = cooked.css('.mention, .mention-group').map do |e|
- if (name = e.inner_text)
- name = name[1..-1]
- name = User.normalize_username(name)
- name
- end
- end
+ mentions =
+ cooked
+ .css(".mention, .mention-group")
+ .map do |e|
+ if (name = e.inner_text)
+ name = name[1..-1]
+ name = User.normalize_username(name)
+ name
+ end
+ end
mentions.compact!
mentions.uniq!
@@ -480,24 +478,26 @@ module PrettyText
# If the user is not basic, strip links from their bio
fragment = Nokogiri::HTML5.fragment(string)
- fragment.css('a').each { |a| a.replace(a.inner_html) }
+ fragment.css("a").each { |a| a.replace(a.inner_html) }
fragment.to_html
end
def self.make_all_links_absolute(doc)
site_uri = nil
- doc.css("a").each do |link|
- href = link["href"].to_s
- begin
- uri = URI(href)
- site_uri ||= URI(Discourse.base_url)
- unless uri.host.present? || href.start_with?('mailto')
- link["href"] = "#{site_uri}#{link['href']}"
+ doc
+ .css("a")
+ .each do |link|
+ href = link["href"].to_s
+ begin
+ uri = URI(href)
+ site_uri ||= URI(Discourse.base_url)
+ unless uri.host.present? || href.start_with?("mailto")
+ link["href"] = "#{site_uri}#{link["href"]}"
+ end
+ rescue URI::Error
+ # leave it
end
- rescue URI::Error
- # leave it
end
- end
end
def self.strip_image_wrapping(doc)
@@ -510,94 +510,119 @@ module PrettyText
end
def self.convert_vimeo_iframes(doc)
- doc.css("iframe[src*='player.vimeo.com']").each do |iframe|
- if iframe["data-original-href"].present?
- vimeo_url = UrlHelper.normalized_encode(iframe["data-original-href"])
- else
- vimeo_id = iframe['src'].split('/').last
- vimeo_url = "https://vimeo.com/#{vimeo_id}"
+ doc
+ .css("iframe[src*='player.vimeo.com']")
+ .each do |iframe|
+ if iframe["data-original-href"].present?
+ vimeo_url = UrlHelper.normalized_encode(iframe["data-original-href"])
+ else
+ vimeo_id = iframe["src"].split("/").last
+ vimeo_url = "https://vimeo.com/#{vimeo_id}"
+ end
+ iframe.replace Nokogiri::HTML5.fragment("<p><a href='#{vimeo_url}'>#{vimeo_url}</a></p>")
end
- iframe.replace Nokogiri::HTML5.fragment("<p><a href='#{vimeo_url}'>#{vimeo_url}</a></p>")
- end
end
def self.strip_secure_uploads(doc)
# images inside a lightbox or other link
- doc.css('a[href]').each do |a|
- next if !Upload.secure_uploads_url?(a['href'])
-
- non_image_media = %w(video audio).include?(a&.parent&.name)
- target = non_image_media ? a.parent : a
- next if target.to_s.include?('stripped-secure-view-media') || target.to_s.include?('stripped-secure-view-upload')
-
- next if a.css('img[src]').empty? && !non_image_media
-
- if a.classes.include?('lightbox')
- img = a.css('img[src]').first
- srcset = img&.attributes['srcset']&.value
- if srcset
- # if available, use the first image from the srcset here
- # so we get the optimized image instead of the possibly huge original
- url = srcset.split(',').first
+ doc
+ .css("a[href]")
+ .each do |a|
+ next if !Upload.secure_uploads_url?(a["href"])
+
+ non_image_media = %w[video audio].include?(a&.parent&.name)
+ target = non_image_media ? a.parent : a
+ if target.to_s.include?("stripped-secure-view-media") ||
+ target.to_s.include?("stripped-secure-view-upload")
+ next
+ end
+
+ next if a.css("img[src]").empty? && !non_image_media
+
+ if a.classes.include?("lightbox")
+ img = a.css("img[src]").first
+ srcset = img&.attributes["srcset"]&.value
+ if srcset
+ # if available, use the first image from the srcset here
+ # so we get the optimized image instead of the possibly huge original
+ url = srcset.split(",").first
+ else
+ url = img["src"]
+ end
+ a.add_next_sibling secure_uploads_placeholder(
+ doc,
+ url,
+ width: img["width"],
+ height: img["height"],
+ )
+ a.remove
else
- url = img['src']
+ width = non_image_media ? nil : a.at_css("img").attr("width")
+ height = non_image_media ? nil : a.at_css("img").attr("height")
+ target.add_next_sibling secure_uploads_placeholder(
+ doc,
+ a["href"],
+ width: width,
+ height: height,
+ )
+ target.remove
end
- a.add_next_sibling secure_uploads_placeholder(doc, url, width: img['width'], height: img['height'])
- a.remove
- else
- width = non_image_media ? nil : a.at_css('img').attr('width')
- height = non_image_media ? nil : a.at_css('img').attr('height')
- target.add_next_sibling secure_uploads_placeholder(doc, a['href'], width: width, height: height)
- target.remove
end
- end
# images by themselves or inside a onebox
- doc.css('img[src]').each do |img|
- url = if img.parent.classes.include?("aspect-image") && img.attributes["srcset"].present?
-
- # we are using the first image from the srcset here so we get the
- # optimized image instead of the original, because an optimized
- # image may be used for the onebox thumbnail
- srcset = img.attributes["srcset"].value
- srcset.split(",").first
- else
- img['src']
- end
-
- width = img['width']
- height = img['height']
- onebox_type = nil
+ doc
+ .css("img[src]")
+ .each do |img|
+ url =
+ if img.parent.classes.include?("aspect-image") && img.attributes["srcset"].present?
+ # we are using the first image from the srcset here so we get the
+ # optimized image instead of the original, because an optimized
+ # image may be used for the onebox thumbnail
+ srcset = img.attributes["srcset"].value
+ srcset.split(",").first
+ else
+ img["src"]
+ end
+
+ width = img["width"]
+ height = img["height"]
+ onebox_type = nil
- if img.ancestors.css(".onebox-body").any?
- if img.classes.include?("onebox-avatar-inline")
- onebox_type = "avatar-inline"
- else
- onebox_type = "thumbnail"
+ if img.ancestors.css(".onebox-body").any?
+ if img.classes.include?("onebox-avatar-inline")
+ onebox_type = "avatar-inline"
+ else
+ onebox_type = "thumbnail"
+ end
end
- end
- # we always want this to be tiny and without any special styles
- if img.classes.include?('site-icon')
- onebox_type = nil
- width = 16
- height = 16
- end
+ # we always want this to be tiny and without any special styles
+ if img.classes.include?("site-icon")
+ onebox_type = nil
+ width = 16
+ height = 16
+ end
- if Upload.secure_uploads_url?(url)
- img.add_next_sibling secure_uploads_placeholder(doc, url, onebox_type: onebox_type, width: width, height: height)
- img.remove
+ if Upload.secure_uploads_url?(url)
+ img.add_next_sibling secure_uploads_placeholder(
+ doc,
+ url,
+ onebox_type: onebox_type,
+ width: width,
+ height: height,
+ )
+ img.remove
+ end
end
- end
end
def self.secure_uploads_placeholder(doc, url, onebox_type: false, width: nil, height: nil)
- data_width = width ? "data-width=#{width}" : ''
- data_height = height ? "data-height=#{height}" : ''
- data_onebox_type = onebox_type ? "data-onebox-type='#{onebox_type}'" : ''
+ data_width = width ? "data-width=#{width}" : ""
+ data_height = height ? "data-height=#{height}" : ""
+ data_onebox_type = onebox_type ? "data-onebox-type='#{onebox_type}'" : ""
<<~HTML
<div class="secure-upload-notice" data-stripped-secure-upload="#{url}" #{data_onebox_type} #{data_width} #{data_height}>
- #{I18n.t('emails.secure_uploads_placeholder')} <a class='stripped-secure-view-upload' href="#{url}">#{I18n.t("emails.view_redacted_media")}</a>.
+ #{I18n.t("emails.secure_uploads_placeholder")} <a class='stripped-secure-view-upload' href="#{url}">#{I18n.t("emails.view_redacted_media")}</a>.
</div>
HTML
end
@@ -621,28 +646,23 @@ module PrettyText
@message = message
@backtrace = backtrace
end
-
end
def self.protect
rval = nil
- @mutex.synchronize do
- rval = yield
- end
+ @mutex.synchronize { rval = yield }
rval
end
def self.ctx_load(ctx, *files)
- files.each do |file|
- ctx.load(app_root + file)
- end
+ files.each { |file| ctx.load(app_root + file) }
end
private
- USER_TYPE ||= 'user'
- GROUP_TYPE ||= 'group'
- GROUP_MENTIONABLE_TYPE ||= 'group-mentionable'
+ USER_TYPE ||= "user"
+ GROUP_TYPE ||= "group"
+ GROUP_MENTIONABLE_TYPE ||= "group-mentionable"
def self.add_mentions(doc, user_id: nil)
elements = doc.css("span.mention")
@@ -655,21 +675,19 @@ module PrettyText
name.downcase!
if type = mentions[name]
- element.name = 'a'
+ element.name = "a"
- element.children = PrettyText::Helpers.format_username(
- element.children.text
- )
+ element.children = PrettyText::Helpers.format_username(element.children.text)
case type
when USER_TYPE
- element['href'] = "#{Discourse.base_path}/u/#{UrlHelper.encode_component(name)}"
+ element["href"] = "#{Discourse.base_path}/u/#{UrlHelper.encode_component(name)}"
when GROUP_MENTIONABLE_TYPE
- element['class'] = 'mention-group notify'
- element['href'] = "#{Discourse.base_path}/groups/#{UrlHelper.encode_component(name)}"
+ element["class"] = "mention-group notify"
+ element["href"] = "#{Discourse.base_path}/groups/#{UrlHelper.encode_component(name)}"
when GROUP_TYPE
- element['class'] = 'mention-group'
- element['href'] = "#{Discourse.base_path}/groups/#{UrlHelper.encode_component(name)}"
+ element["class"] = "mention-group"
+ element["href"] = "#{Discourse.base_path}/groups/#{UrlHelper.encode_component(name)}"
end
end
end
@@ -707,14 +725,16 @@ module PrettyText
user = User.find_by(id: user_id)
names.each(&:downcase!)
- results = DB.query(sql,
- names: names,
- user_type: USER_TYPE,
- group_type: GROUP_TYPE,
- group_mentionable_type: GROUP_MENTIONABLE_TYPE,
- levels: Group.alias_levels(user),
- user_id: user_id
- )
+ results =
+ DB.query(
+ sql,
+ names: names,
+ user_type: USER_TYPE,
+ group_type: GROUP_TYPE,
+ group_mentionable_type: GROUP_MENTIONABLE_TYPE,
+ levels: Group.alias_levels(user),
+ user_id: user_id,
+ )
mentions = {}
results.each { |result| mentions[result.name] = result.type }
@@ -728,17 +748,18 @@ module PrettyText
GlobalSetting.s3_cdn_url,
GlobalSetting.cdn_url,
SiteSetting.external_emoji_url.presence,
- *SiteSetting.block_hotlinked_media_exceptions.split("|")
+ *SiteSetting.block_hotlinked_media_exceptions.split("|"),
]
- patterns = allowed_src_prefixes.compact.map do |url|
- pattern = Regexp.escape(url)
+ patterns =
+ allowed_src_prefixes.compact.map do |url|
+ pattern = Regexp.escape(url)
- # If 'https://example.com' is allowed, ensure 'https://example.com.blah.com' is not
- pattern += '(?:/|\z)' if !pattern.ends_with?("\/")
+ # If 'https://example.com' is allowed, ensure 'https://example.com.blah.com' is not
+ pattern += '(?:/|\z)' if !pattern.ends_with?("\/")
- pattern
- end
+ pattern
+ end
/\A(data:|#{patterns.join("|")})/
end
diff --git a/lib/pretty_text/helpers.rb b/lib/pretty_text/helpers.rb
index 819dc060eff..621f59d7f8e 100644
--- a/lib/pretty_text/helpers.rb
+++ b/lib/pretty_text/helpers.rb
@@ -58,21 +58,31 @@ module PrettyText
reverse_map[value] << key
end
- Upload.where(sha1: map.values).pluck(:sha1, :url, :extension, :original_filename, :secure).each do |row|
- sha1, url, extension, original_filename, secure = row
-
- if short_urls = reverse_map[sha1]
- secure_uploads = SiteSetting.secure_uploads? && secure
-
- short_urls.each do |short_url|
- result[short_url] = {
- url: secure_uploads ? Upload.secure_uploads_url_from_upload_url(url) : Discourse.store.cdn_url(url),
- short_path: Upload.short_path(sha1: sha1, extension: extension),
- base62_sha1: Upload.base62_sha1(sha1)
- }
+ Upload
+ .where(sha1: map.values)
+ .pluck(:sha1, :url, :extension, :original_filename, :secure)
+ .each do |row|
+ sha1, url, extension, original_filename, secure = row
+
+ if short_urls = reverse_map[sha1]
+ secure_uploads = SiteSetting.secure_uploads? && secure
+
+ short_urls.each do |short_url|
+ result[short_url] = {
+ url:
+ (
+ if secure_uploads
+ Upload.secure_uploads_url_from_upload_url(url)
+ else
+ Discourse.store.cdn_url(url)
+ end
+ ),
+ short_path: Upload.short_path(sha1: sha1, extension: extension),
+ base62_sha1: Upload.base62_sha1(sha1),
+ }
+ end
end
end
- end
end
result
@@ -83,15 +93,9 @@ module PrettyText
# TODO this only handles public topics, secured one do not get this
topic = Topic.find_by(id: topic_id)
if topic && Guardian.new.can_see?(topic)
- {
- title: Rack::Utils.escape_html(topic.title),
- href: topic.url
- }
+ { title: Rack::Utils.escape_html(topic.title), href: topic.url }
elsif topic
- {
- title: I18n.t("on_another_topic"),
- href: Discourse.base_url + topic.slugless_url
- }
+ { title: I18n.t("on_another_topic"), href: Discourse.base_url + topic.slugless_url }
end
end
@@ -103,7 +107,7 @@ module PrettyText
if !is_tag && category = Category.query_from_hashtag_slug(text)
[category.url, text]
elsif (!is_tag && tag = Tag.find_by(name: text)) ||
- (is_tag && tag = Tag.find_by(name: text.gsub!(TAG_HASHTAG_POSTFIX, '')))
+ (is_tag && tag = Tag.find_by(name: text.gsub!(TAG_HASHTAG_POSTFIX, "")))
[tag.url, text]
else
nil
@@ -124,9 +128,11 @@ module PrettyText
cooking_user = User.find(cooking_user_id)
end
- result = HashtagAutocompleteService.new(
- Guardian.new(cooking_user)
- ).lookup([slug], types_in_priority_order)
+ result =
+ HashtagAutocompleteService.new(Guardian.new(cooking_user)).lookup(
+ [slug],
+ types_in_priority_order,
+ )
found_hashtag = nil
types_in_priority_order.each do |type|
diff --git a/lib/promotion.rb b/lib/promotion.rb
index da0f89916fa..b817ae64414 100644
--- a/lib/promotion.rb
+++ b/lib/promotion.rb
@@ -4,7 +4,6 @@
# Check whether a user is ready for a new trust level.
#
class Promotion
-
def initialize(user)
@user = user
end
@@ -26,7 +25,8 @@ class Promotion
def review_tl0
if Promotion.tl1_met?(@user) && change_trust_level!(TrustLevel[1])
- if Badge.exists?(id: Badge::BasicUser, enabled: true) && [email protected]?(id: Badge::BasicUser)
+ if Badge.exists?(id: Badge::BasicUser, enabled: true) &&
+ [email protected]?(id: Badge::BasicUser)
@user.enqueue_member_welcome_message
end
return true
@@ -56,10 +56,13 @@ class Promotion
next_up = new_level + 1
key = "tl#{next_up}_met?"
if self.class.respond_to?(key) && self.class.public_send(key, @user)
- raise Discourse::InvalidAccess.new, I18n.t('trust_levels.change_failed_explanation',
- user_name: @user.name,
- new_trust_level: new_level,
- current_trust_level: old_level)
+ raise Discourse::InvalidAccess.new,
+ I18n.t(
+ "trust_levels.change_failed_explanation",
+ user_name: @user.name,
+ new_trust_level: new_level,
+ current_trust_level: old_level,
+ )
end
end
@@ -72,15 +75,22 @@ class Promotion
if admin
StaffActionLogger.new(admin).log_trust_level_change(@user, old_level, new_level)
else
- UserHistory.create!(action: UserHistory.actions[:auto_trust_level_change],
- target_user_id: @user.id,
- previous_value: old_level,
- new_value: new_level)
+ UserHistory.create!(
+ action: UserHistory.actions[:auto_trust_level_change],
+ target_user_id: @user.id,
+ previous_value: old_level,
+ new_value: new_level,
+ )
end
@user.save!
@user.user_profile.recook_bio
@user.user_profile.save!
- DiscourseEvent.trigger(:user_promoted, user_id: @user.id, new_trust_level: new_level, old_trust_level: old_level)
+ DiscourseEvent.trigger(
+ :user_promoted,
+ user_id: @user.id,
+ new_trust_level: new_level,
+ old_trust_level: old_level,
+ )
Group.user_trust_level_change!(@user.id, @user.trust_level)
BadgeGranter.queue_badge_grant(Badge::Trigger::TrustLevelChange, user: @user)
end
@@ -122,12 +132,9 @@ class Promotion
# Figure out what a user's trust level should be from scratch
def self.recalculate(user, performed_by = nil, use_previous_trust_level: false)
- granted_trust_level = TrustLevel.calculate(
- user, use_previous_trust_level: use_previous_trust_level
- )
- if granted_trust_level.present?
- return user.update(trust_level: granted_trust_level)
- end
+ granted_trust_level =
+ TrustLevel.calculate(user, use_previous_trust_level: use_previous_trust_level)
+ return user.update(trust_level: granted_trust_level) if granted_trust_level.present?
user.update_column(:trust_level, TrustLevel[0])
diff --git a/lib/quote_comparer.rb b/lib/quote_comparer.rb
index 5f25c7138f6..55b7a8ceab2 100644
--- a/lib/quote_comparer.rb
+++ b/lib/quote_comparer.rb
@@ -23,7 +23,8 @@ class QuoteComparer
return true if @text.blank?
if @parent_post
- parent_text = Nokogiri::HTML5::fragment(@parent_post.cooked).text.delete(QuoteComparer.whitespace)
+ parent_text =
+ Nokogiri::HTML5.fragment(@parent_post.cooked).text.delete(QuoteComparer.whitespace)
text = @text.delete(QuoteComparer.whitespace)
!parent_text.include?(text)
diff --git a/lib/rake_helpers.rb b/lib/rake_helpers.rb
index adc5adcd32d..dd8f6c20cbe 100644
--- a/lib/rake_helpers.rb
+++ b/lib/rake_helpers.rb
@@ -2,12 +2,13 @@
class RakeHelpers
def self.print_status_with_label(label, current, max)
- return if Rails.env.test? && !ENV['RAILS_ENABLE_TEST_LOG']
- print "\r\033[K%s%9d / %d (%5.1f%%)" % [label, current, max, ((current.to_f / max.to_f) * 100).round(1)]
+ return if Rails.env.test? && !ENV["RAILS_ENABLE_TEST_LOG"]
+ print "\r\033[K%s%9d / %d (%5.1f%%)" %
+ [label, current, max, ((current.to_f / max.to_f) * 100).round(1)]
end
def self.print_status(current, max)
- return if Rails.env.test? && !ENV['RAILS_ENABLE_TEST_LOG']
+ return if Rails.env.test? && !ENV["RAILS_ENABLE_TEST_LOG"]
print "\r\033[K%9d / %d (%5.1f%%)" % [current, max, ((current.to_f / max.to_f) * 100).round(1)]
end
end
diff --git a/lib/rate_limiter.rb b/lib/rate_limiter.rb
index 1ec2d455add..2604d6dcff8 100644
--- a/lib/rate_limiter.rb
+++ b/lib/rate_limiter.rb
@@ -2,7 +2,6 @@
# A redis backed rate limiter.
class RateLimiter
-
attr_reader :max, :secs, :user, :key, :error_code
def self.key_prefix
@@ -30,16 +29,28 @@ class RateLimiter
end
def self.clear_all_global!
- Discourse.redis.without_namespace.keys("GLOBAL::#{key_prefix}*").each do |k|
- Discourse.redis.without_namespace.del k
- end
+ Discourse
+ .redis
+ .without_namespace
+ .keys("GLOBAL::#{key_prefix}*")
+ .each { |k| Discourse.redis.without_namespace.del k }
end
def build_key(type)
"#{RateLimiter.key_prefix}:#{@user && @user.id}:#{type}"
end
- def initialize(user, type, max, secs, global: false, aggressive: false, error_code: nil, apply_limit_to_staff: false, staff_limit: { max: nil, secs: nil })
+ def initialize(
+ user,
+ type,
+ max,
+ secs,
+ global: false,
+ aggressive: false,
+ error_code: nil,
+ apply_limit_to_staff: false,
+ staff_limit: { max: nil, secs: nil }
+ )
@user = user
@type = type
@key = build_key(type)
@@ -71,8 +82,7 @@ class RateLimiter
end
# reloader friendly
- unless defined? PERFORM_LUA
- PERFORM_LUA = DiscourseRedis::EvalHelper.new <<~LUA
+ PERFORM_LUA = DiscourseRedis::EvalHelper.new <<~LUA unless defined?(PERFORM_LUA)
local now = tonumber(ARGV[1])
local secs = tonumber(ARGV[2])
local max = tonumber(ARGV[3])
@@ -91,9 +101,8 @@ class RateLimiter
return 0
end
LUA
- end
- unless defined? PERFORM_LUA_AGGRESSIVE
+ unless defined?(PERFORM_LUA_AGGRESSIVE)
PERFORM_LUA_AGGRESSIVE = DiscourseRedis::EvalHelper.new <<~LUA
local now = tonumber(ARGV[1])
local secs = tonumber(ARGV[2])
@@ -186,11 +195,13 @@ class RateLimiter
# number of events in buffer less than max allowed? OR
(redis.llen(prefixed_key) < @max) ||
- # age bigger than sliding window size?
- (age_of_oldest(now) >= @secs)
+ # age bigger than sliding window size?
+ (age_of_oldest(now) >= @secs)
end
def rate_unlimited?
- !!(RateLimiter.disabled? || (@user&.staff? && !@apply_limit_to_staff && @staff_limit[:max].nil?))
+ !!(
+ RateLimiter.disabled? || (@user&.staff? && !@apply_limit_to_staff && @staff_limit[:max].nil?)
+ )
end
end
diff --git a/lib/rate_limiter/limit_exceeded.rb b/lib/rate_limiter/limit_exceeded.rb
index 0109dbf9e5f..e94ea282332 100644
--- a/lib/rate_limiter/limit_exceeded.rb
+++ b/lib/rate_limiter/limit_exceeded.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class RateLimiter
-
def self.time_left(available_in)
if available_in <= 3
I18n.t("rate_limiter.short_time")
@@ -38,5 +37,4 @@ class RateLimiter
I18n.t("rate_limiter.too_many_requests", time_left: time_left)
end
end
-
end
diff --git a/lib/rate_limiter/on_create_record.rb b/lib/rate_limiter/on_create_record.rb
index 327a1c15fab..f24a85a4b55 100644
--- a/lib/rate_limiter/on_create_record.rb
+++ b/lib/rate_limiter/on_create_record.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class RateLimiter
-
# A mixin we can use on ActiveRecord Models to automatically rate limit them
# based on a SiteSetting.
#
@@ -9,17 +8,17 @@ class RateLimiter
# `model_name` is the class name of your model, underscored.
#
module OnCreateRecord
-
# Over write to define your own rate limiter
def default_rate_limiter
return @rate_limiter if @rate_limiter.present?
limit_key = "create_#{self.class.name.underscore}"
- max_setting = if user && user.new_user? && SiteSetting.has_setting?("rate_limit_new_user_#{limit_key}")
- SiteSetting.get("rate_limit_new_user_#{limit_key}")
- else
- SiteSetting.get("rate_limit_#{limit_key}")
- end
+ max_setting =
+ if user && user.new_user? && SiteSetting.has_setting?("rate_limit_new_user_#{limit_key}")
+ SiteSetting.get("rate_limit_new_user_#{limit_key}")
+ else
+ SiteSetting.get("rate_limit_#{limit_key}")
+ end
@rate_limiter = RateLimiter.new(user, limit_key, 1, max_setting)
end
@@ -34,7 +33,6 @@ class RateLimiter
module ClassMethods
def rate_limit(limiter_method = nil)
-
limiter_method = limiter_method || :default_rate_limiter
self.after_create do |*args|
@@ -63,10 +61,7 @@ class RateLimiter
end
end
end
-
end
end
-
end
-
end
diff --git a/lib/read_only_mixin.rb b/lib/read_only_mixin.rb
index 3fa05604f02..3c393d1b84a 100644
--- a/lib/read_only_mixin.rb
+++ b/lib/read_only_mixin.rb
@@ -33,7 +33,7 @@ module ReadOnlyMixin
end
def add_readonly_header
- response.headers['Discourse-Readonly'] = 'true' if @readonly_mode
+ response.headers["Discourse-Readonly"] = "true" if @readonly_mode
end
def allowed_in_staff_writes_only_mode?
diff --git a/lib/redis_snapshot.rb b/lib/redis_snapshot.rb
index 1ef40792eec..0e8da8491ac 100644
--- a/lib/redis_snapshot.rb
+++ b/lib/redis_snapshot.rb
@@ -13,12 +13,7 @@ class RedisSnapshot
def self.load(redis = Discourse.redis)
keys = redis.keys
- values =
- redis.pipelined do |batch|
- keys.each do |key|
- batch.dump(key)
- end
- end
+ values = redis.pipelined { |batch| keys.each { |key| batch.dump(key) } }
new(keys.zip(values).delete_if { |k, v| v.nil? })
end
@@ -31,9 +26,7 @@ class RedisSnapshot
redis.pipelined do |batch|
batch.flushdb
- @dump.each do |key, value|
- batch.restore(key, 0, value)
- end
+ @dump.each { |key, value| batch.restore(key, 0, value) }
end
nil
diff --git a/lib/require_dependency_backward_compatibility.rb b/lib/require_dependency_backward_compatibility.rb
index efec53ced3d..5b550e45d37 100644
--- a/lib/require_dependency_backward_compatibility.rb
+++ b/lib/require_dependency_backward_compatibility.rb
@@ -13,8 +13,8 @@
module RequireDependencyBackwardCompatibility
def require_dependency(filename)
name = filename.to_s
- return if name == 'jobs/base'
- return super(name.sub(/^lib\//, '')) if name.start_with?('lib/')
+ return if name == "jobs/base"
+ return super(name.sub(%r{^lib/}, "")) if name.start_with?("lib/")
super
end
diff --git a/lib/retrieve_title.rb b/lib/retrieve_title.rb
index df1355ded3c..826792650f4 100644
--- a/lib/retrieve_title.rb
+++ b/lib/retrieve_title.rb
@@ -7,7 +7,7 @@ module RetrieveTitle
fetch_title(
url,
max_redirects: max_redirects,
- initial_https_redirect_ignore_limit: initial_https_redirect_ignore_limit
+ initial_https_redirect_ignore_limit: initial_https_redirect_ignore_limit,
)
rescue Net::ReadTimeout, FinalDestination::SSRFDetector::LookupFailedError
# do nothing for Net::ReadTimeout errors
@@ -15,13 +15,11 @@ module RetrieveTitle
def self.extract_title(html, encoding = nil)
title = nil
- if html =~ /<title>/ && html !~ /<\/title>/
- return nil
- end
+ return nil if html =~ /<title>/ && html !~ %r{</title>}
doc = nil
begin
- doc = Nokogiri::HTML5(html, nil, encoding)
+ doc = Nokogiri.HTML5(html, nil, encoding)
rescue ArgumentError
# invalid HTML (Eg: too many attributes, status tree too deep) - ignore
# Error in nokogumbo is not specialized, uses generic ArgumentError
@@ -29,22 +27,22 @@ module RetrieveTitle
end
if doc
- title = doc.at('title')&.inner_text
+ title = doc.at("title")&.inner_text
# A horrible hack - YouTube uses `document.title` to populate the title
# for some reason. For any other site than YouTube this wouldn't be worth it.
if title == "YouTube" && html =~ /document\.title *= *"(.*)";/
- title = Regexp.last_match[1].sub(/ - YouTube$/, '')
+ title = Regexp.last_match[1].sub(/ - YouTube$/, "")
end
if !title && node = doc.at('meta[property="og:title"]')
- title = node['content']
+ title = node["content"]
end
end
if title.present?
- title.gsub!(/\n/, ' ')
- title.gsub!(/ +/, ' ')
+ title.gsub!(/\n/, " ")
+ title.gsub!(/ +/, " ")
title.strip!
return title
end
@@ -55,7 +53,9 @@ module RetrieveTitle
def self.max_chunk_size(uri)
# Exception for sites that leave the title until very late.
- return 500 if uri.host =~ /(^|\.)amazon\.(com|ca|co\.uk|es|fr|de|it|com\.au|com\.br|cn|in|co\.jp|com\.mx)$/
+ if uri.host =~ /(^|\.)amazon\.(com|ca|co\.uk|es|fr|de|it|com\.au|com\.br|cn|in|co\.jp|com\.mx)$/
+ return 500
+ end
return 300 if uri.host =~ /(^|\.)youtube\.com$/ || uri.host =~ /(^|\.)youtu\.be$/
return 50 if uri.host =~ /(^|\.)github\.com$/
@@ -65,13 +65,14 @@ module RetrieveTitle
# Fetch the beginning of a HTML document at a url
def self.fetch_title(url, max_redirects: nil, initial_https_redirect_ignore_limit: false)
- fd = FinalDestination.new(
- url,
- timeout: CRAWL_TIMEOUT,
- stop_at_blocked_pages: true,
- max_redirects: max_redirects,
- initial_https_redirect_ignore_limit: initial_https_redirect_ignore_limit
- )
+ fd =
+ FinalDestination.new(
+ url,
+ timeout: CRAWL_TIMEOUT,
+ stop_at_blocked_pages: true,
+ max_redirects: max_redirects,
+ initial_https_redirect_ignore_limit: initial_https_redirect_ignore_limit,
+ )
current = nil
title = nil
@@ -87,12 +88,10 @@ module RetrieveTitle
current = chunk
end
- if !encoding && content_type = _response['content-type']&.strip&.downcase
+ if !encoding && content_type = _response["content-type"]&.strip&.downcase
if content_type =~ /charset="?([a-z0-9_-]+)"?/
encoding = Regexp.last_match(1)
- if !Encoding.list.map(&:name).map(&:downcase).include?(encoding)
- encoding = nil
- end
+ encoding = nil if !Encoding.list.map(&:name).map(&:downcase).include?(encoding)
end
end
diff --git a/lib/reviewable/actions.rb b/lib/reviewable/actions.rb
index 3343ac0fb83..abee9387588 100644
--- a/lib/reviewable/actions.rb
+++ b/lib/reviewable/actions.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'reviewable/collection'
+require "reviewable/collection"
class Reviewable < ActiveRecord::Base
class Actions < Reviewable::Collection
@@ -15,9 +15,9 @@ class Reviewable < ActiveRecord::Base
# one off, add it manually.
def self.common_actions
{
- approve: Action.new(:approve, 'thumbs-up', 'reviewables.actions.approve.title'),
- reject: Action.new(:reject, 'thumbs-down', 'reviewables.actions.reject.title'),
- delete: Action.new(:delete, 'trash-alt', 'reviewables.actions.delete_single.title')
+ approve: Action.new(:approve, "thumbs-up", "reviewables.actions.approve.title"),
+ reject: Action.new(:reject, "thumbs-down", "reviewables.actions.reject.title"),
+ delete: Action.new(:delete, "trash-alt", "reviewables.actions.delete_single.title"),
}
end
@@ -33,7 +33,14 @@ class Reviewable < ActiveRecord::Base
end
class Action < Item
- attr_accessor :icon, :button_class, :label, :description, :confirm_message, :client_action, :require_reject_reason, :custom_modal
+ attr_accessor :icon,
+ :button_class,
+ :label,
+ :description,
+ :confirm_message,
+ :client_action,
+ :require_reject_reason,
+ :custom_modal
def initialize(id, icon = nil, button_class = nil, label = nil)
super(id)
@@ -55,6 +62,5 @@ class Reviewable < ActiveRecord::Base
bundle ||= add_bundle(id)
bundle.actions << action
end
-
end
end
diff --git a/lib/reviewable/perform_result.rb b/lib/reviewable/perform_result.rb
index dbaa7fe56cc..623497026d6 100644
--- a/lib/reviewable/perform_result.rb
+++ b/lib/reviewable/perform_result.rb
@@ -11,7 +11,7 @@ class Reviewable < ActiveRecord::Base
:errors,
:recalculate_score,
:update_flag_stats,
- :after_commit
+ :after_commit,
)
def initialize(reviewable, status)
diff --git a/lib/route_format.rb b/lib/route_format.rb
index b502f8c83f8..23fb554701b 100644
--- a/lib/route_format.rb
+++ b/lib/route_format.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module RouteFormat
-
def self.username
/[%\w.\-]+?/
end
@@ -9,5 +8,4 @@ module RouteFormat
def self.backup
/.+\.(sql\.gz|tar\.gz|tgz)/i
end
-
end
diff --git a/lib/route_matcher.rb b/lib/route_matcher.rb
index eeccbf29de9..6512f7942f1 100644
--- a/lib/route_matcher.rb
+++ b/lib/route_matcher.rb
@@ -5,7 +5,14 @@ class RouteMatcher
attr_reader :actions, :params, :methods, :aliases, :formats, :allowed_param_values
- def initialize(actions: nil, params: nil, methods: nil, formats: nil, aliases: nil, allowed_param_values: nil)
+ def initialize(
+ actions: nil,
+ params: nil,
+ methods: nil,
+ formats: nil,
+ aliases: nil,
+ allowed_param_values: nil
+ )
@actions = Array(actions) if actions
@params = Array(params) if params
@methods = Array(methods) if methods
@@ -22,16 +29,14 @@ class RouteMatcher
methods: methods,
formats: formats,
aliases: aliases,
- allowed_param_values: new_allowed_param_values
+ allowed_param_values: new_allowed_param_values,
)
end
def match?(env:)
request = ActionDispatch::Request.new(env)
- action_allowed?(request) &&
- params_allowed?(request) &&
- method_allowed?(request) &&
+ action_allowed?(request) && params_allowed?(request) && method_allowed?(request) &&
format_allowed?(request)
end
@@ -41,7 +46,7 @@ class RouteMatcher
return true if actions.nil? # actions are unrestricted
# message_bus is not a rails route, special handling
- return true if actions.include?("message_bus") && request.fullpath =~ /^\/message-bus\/.*\/poll/
+ return true if actions.include?("message_bus") && request.fullpath =~ %r{^/message-bus/.*/poll}
path_params = path_params_from_request(request)
actions.include? "#{path_params[:controller]}##{path_params[:action]}"
@@ -69,7 +74,7 @@ class RouteMatcher
end
def extract_category_id(category_slug_with_id)
- parts = category_slug_with_id.split('/')
+ parts = category_slug_with_id.split("/")
!parts.empty? && parts.last =~ /\A\d+\Z/ ? parts.pop : nil
end
diff --git a/lib/rtl.rb b/lib/rtl.rb
index abf91ebf5c1..80259f06d17 100644
--- a/lib/rtl.rb
+++ b/lib/rtl.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class Rtl
-
attr_reader :user
def initialize(user)
@@ -21,11 +20,10 @@ class Rtl
end
def rtl_locales
- %w(he ar ur fa_IR)
+ %w[he ar ur fa_IR]
end
def css_class
- enabled? ? 'rtl' : ''
+ enabled? ? "rtl" : ""
end
-
end
diff --git a/lib/s3_cors_rulesets.rb b/lib/s3_cors_rulesets.rb
index 3c4e293dd81..91216de082c 100644
--- a/lib/s3_cors_rulesets.rb
+++ b/lib/s3_cors_rulesets.rb
@@ -5,25 +5,25 @@ require "s3_helper"
class S3CorsRulesets
ASSETS = {
allowed_headers: ["Authorization"],
- allowed_methods: ["GET", "HEAD"],
+ allowed_methods: %w[GET HEAD],
allowed_origins: ["*"],
- max_age_seconds: 3000
+ max_age_seconds: 3000,
}.freeze
BACKUP_DIRECT_UPLOAD = {
allowed_headers: ["*"],
expose_headers: ["ETag"],
- allowed_methods: ["GET", "HEAD", "PUT"],
+ allowed_methods: %w[GET HEAD PUT],
allowed_origins: ["*"],
- max_age_seconds: 3000
+ max_age_seconds: 3000,
}.freeze
DIRECT_UPLOAD = {
- allowed_headers: ["Authorization", "Content-Disposition", "Content-Type"],
+ allowed_headers: %w[Authorization Content-Disposition Content-Type],
expose_headers: ["ETag"],
- allowed_methods: ["GET", "HEAD", "PUT"],
+ allowed_methods: %w[GET HEAD PUT],
allowed_origins: ["*"],
- max_age_seconds: 3000
+ max_age_seconds: 3000,
}.freeze
RULE_STATUS_SKIPPED = "rules_skipped_from_settings"
@@ -46,35 +46,51 @@ class S3CorsRulesets
backup_rules_status = RULE_STATUS_SKIPPED
direct_upload_rules_status = RULE_STATUS_SKIPPED
- s3_helper = S3Helper.build_from_config(
- s3_client: s3_client, use_db_s3_config: use_db_s3_config
- )
+ s3_helper = S3Helper.build_from_config(s3_client: s3_client, use_db_s3_config: use_db_s3_config)
if !Rails.env.test?
puts "Attempting to apply ASSETS S3 CORS ruleset in bucket #{s3_helper.s3_bucket_name}."
end
- assets_rules_status = s3_helper.ensure_cors!([S3CorsRulesets::ASSETS]) ? RULE_STATUS_APPLIED : RULE_STATUS_EXISTED
+ assets_rules_status =
+ s3_helper.ensure_cors!([S3CorsRulesets::ASSETS]) ? RULE_STATUS_APPLIED : RULE_STATUS_EXISTED
if SiteSetting.enable_backups? && SiteSetting.backup_location == BackupLocationSiteSetting::S3
- backup_s3_helper = S3Helper.build_from_config(
- s3_client: s3_client, use_db_s3_config: use_db_s3_config, for_backup: true
- )
+ backup_s3_helper =
+ S3Helper.build_from_config(
+ s3_client: s3_client,
+ use_db_s3_config: use_db_s3_config,
+ for_backup: true,
+ )
if !Rails.env.test?
puts "Attempting to apply BACKUP_DIRECT_UPLOAD S3 CORS ruleset in bucket #{backup_s3_helper.s3_bucket_name}."
end
- backup_rules_status = backup_s3_helper.ensure_cors!([S3CorsRulesets::BACKUP_DIRECT_UPLOAD]) ? RULE_STATUS_APPLIED : RULE_STATUS_EXISTED
+ backup_rules_status =
+ (
+ if backup_s3_helper.ensure_cors!([S3CorsRulesets::BACKUP_DIRECT_UPLOAD])
+ RULE_STATUS_APPLIED
+ else
+ RULE_STATUS_EXISTED
+ end
+ )
end
if SiteSetting.enable_direct_s3_uploads
if !Rails.env.test?
puts "Attempting to apply DIRECT_UPLOAD S3 CORS ruleset in bucket #{s3_helper.s3_bucket_name}."
end
- direct_upload_rules_status = s3_helper.ensure_cors!([S3CorsRulesets::DIRECT_UPLOAD]) ? RULE_STATUS_APPLIED : RULE_STATUS_EXISTED
+ direct_upload_rules_status =
+ (
+ if s3_helper.ensure_cors!([S3CorsRulesets::DIRECT_UPLOAD])
+ RULE_STATUS_APPLIED
+ else
+ RULE_STATUS_EXISTED
+ end
+ )
end
{
assets_rules_status: assets_rules_status,
backup_rules_status: backup_rules_status,
- direct_upload_rules_status: direct_upload_rules_status
+ direct_upload_rules_status: direct_upload_rules_status,
}
end
end
diff --git a/lib/s3_helper.rb b/lib/s3_helper.rb
index d1a08cef371..f8082f04caf 100644
--- a/lib/s3_helper.rb
+++ b/lib/s3_helper.rb
@@ -5,7 +5,8 @@ require "aws-sdk-s3"
class S3Helper
FIFTEEN_MEGABYTES = 15 * 1024 * 1024
- class SettingMissing < StandardError; end
+ class SettingMissing < StandardError
+ end
attr_reader :s3_bucket_name, :s3_bucket_folder_path
@@ -24,14 +25,15 @@ class S3Helper
# * presigned put_object URLs for direct S3 uploads
UPLOAD_URL_EXPIRES_AFTER_SECONDS ||= 10.minutes.to_i
- def initialize(s3_bucket_name, tombstone_prefix = '', options = {})
+ def initialize(s3_bucket_name, tombstone_prefix = "", options = {})
@s3_client = options.delete(:client)
@s3_options = default_s3_options.merge(options)
- @s3_bucket_name, @s3_bucket_folder_path = begin
- raise Discourse::InvalidParameters.new("s3_bucket_name") if s3_bucket_name.blank?
- self.class.get_bucket_and_folder_path(s3_bucket_name)
- end
+ @s3_bucket_name, @s3_bucket_folder_path =
+ begin
+ raise Discourse::InvalidParameters.new("s3_bucket_name") if s3_bucket_name.blank?
+ self.class.get_bucket_and_folder_path(s3_bucket_name)
+ end
@tombstone_prefix =
if @s3_bucket_folder_path
@@ -53,7 +55,7 @@ class S3Helper
use_db_s3_config ? SiteSetting.s3_upload_bucket : GlobalSetting.s3_bucket
end
- S3Helper.new(bucket.downcase, '', options)
+ S3Helper.new(bucket.downcase, "", options)
end
def self.get_bucket_and_folder_path(s3_bucket_name)
@@ -64,19 +66,20 @@ class S3Helper
path = get_path_for_s3_upload(path)
obj = s3_bucket.object(path)
- etag = begin
- if File.size(file.path) >= FIFTEEN_MEGABYTES
- options[:multipart_threshold] = FIFTEEN_MEGABYTES
- obj.upload_file(file, options)
- obj.load
- obj.etag
- else
- options[:body] = file
- obj.put(options).etag
+ etag =
+ begin
+ if File.size(file.path) >= FIFTEEN_MEGABYTES
+ options[:multipart_threshold] = FIFTEEN_MEGABYTES
+ obj.upload_file(file, options)
+ obj.load
+ obj.etag
+ else
+ options[:body] = file
+ obj.put(options).etag
+ end
end
- end
- [path, etag.gsub('"', '')]
+ [path, etag.gsub('"', "")]
end
def path_from_url(url)
@@ -88,10 +91,7 @@ class S3Helper
# copy the file in tombstone
if copy_to_tombstone && @tombstone_prefix.present?
- self.copy(
- get_path_for_s3_upload(s3_filename),
- File.join(@tombstone_prefix, s3_filename)
- )
+ self.copy(get_path_for_s3_upload(s3_filename), File.join(@tombstone_prefix, s3_filename))
end
# delete the file
@@ -106,12 +106,7 @@ class S3Helper
end
def delete_objects(keys)
- s3_bucket.delete_objects({
- delete: {
- objects: keys.map { |k| { key: k } },
- quiet: true,
- },
- })
+ s3_bucket.delete_objects({ delete: { objects: keys.map { |k| { key: k } }, quiet: true } })
end
def copy(source, destination, options: {})
@@ -120,14 +115,16 @@ class S3Helper
end
destination = get_path_for_s3_upload(destination)
- source_object = if !Rails.configuration.multisite || source.include?(multisite_upload_path) || source.include?(@tombstone_prefix)
- s3_bucket.object(source)
- elsif @s3_bucket_folder_path
- folder, filename = source.split("/", 2)
- s3_bucket.object(File.join(folder, multisite_upload_path, filename))
- else
- s3_bucket.object(File.join(multisite_upload_path, source))
- end
+ source_object =
+ if !Rails.configuration.multisite || source.include?(multisite_upload_path) ||
+ source.include?(@tombstone_prefix)
+ s3_bucket.object(source)
+ elsif @s3_bucket_folder_path
+ folder, filename = source.split("/", 2)
+ s3_bucket.object(File.join(folder, multisite_upload_path, filename))
+ else
+ s3_bucket.object(File.join(multisite_upload_path, source))
+ end
if source_object.size > FIFTEEN_MEGABYTES
options[:multipart_copy] = true
@@ -144,15 +141,16 @@ class S3Helper
# with values from the copy call.
response = destination_object.copy_from(source_object, options)
- etag = if response.respond_to?(:copy_object_result)
- # small files, regular copy
- response.copy_object_result.etag
- else
- # larger files, multipart copy
- response.data.etag
- end
+ etag =
+ if response.respond_to?(:copy_object_result)
+ # small files, regular copy
+ response.copy_object_result.etag
+ else
+ # larger files, multipart copy
+ response.data.etag
+ end
- [destination, etag.gsub('"', '')]
+ [destination, etag.gsub('"', "")]
end
# Several places in the application need certain CORS rules to exist
@@ -174,13 +172,16 @@ class S3Helper
s3_resource.client.put_bucket_cors(
bucket: @s3_bucket_name,
cors_configuration: {
- cors_rules: final_rules
- }
+ cors_rules: final_rules,
+ },
)
rescue Aws::S3::Errors::AccessDenied => err
# TODO (martin) Remove this warning log level once we are sure this new
# ensure_cors! rule is functioning correctly.
- Discourse.warn_exception(err, message: "Could not PutBucketCors rules for #{@s3_bucket_name}, rules: #{final_rules}")
+ Discourse.warn_exception(
+ err,
+ message: "Could not PutBucketCors rules for #{@s3_bucket_name}, rules: #{final_rules}",
+ )
return false
end
@@ -197,12 +198,7 @@ class S3Helper
end
# cf. http://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html
- rule = {
- id: id,
- status: "Enabled",
- expiration: { days: days },
- filter: filter
- }
+ rule = { id: id, status: "Enabled", expiration: { days: days }, filter: filter }
rules = []
@@ -214,27 +210,25 @@ class S3Helper
# in the past we has a rule that was called purge-tombstone vs purge_tombstone
# just go ahead and normalize for our bucket
- rules.delete_if do |r|
- r.id.gsub('_', '-') == id.gsub('_', '-')
- end
+ rules.delete_if { |r| r.id.gsub("_", "-") == id.gsub("_", "-") }
rules << rule
# normalize filter in rules, due to AWS library bug
- rules = rules.map do |r|
- r = r.to_h
- prefix = r.delete(:prefix)
- if prefix
- r[:filter] = { prefix: prefix }
+ rules =
+ rules.map do |r|
+ r = r.to_h
+ prefix = r.delete(:prefix)
+ r[:filter] = { prefix: prefix } if prefix
+ r
end
- r
- end
s3_resource.client.put_bucket_lifecycle_configuration(
bucket: @s3_bucket_name,
lifecycle_configuration: {
- rules: rules
- })
+ rules: rules,
+ },
+ )
end
def update_tombstone_lifecycle(grace_period)
@@ -251,16 +245,14 @@ class S3Helper
def tag_file(key, tags)
tag_array = []
- tags.each do |k, v|
- tag_array << { key: k.to_s, value: v.to_s }
- end
+ tags.each { |k, v| tag_array << { key: k.to_s, value: v.to_s } }
s3_resource.client.put_object_tagging(
bucket: @s3_bucket_name,
key: key,
tagging: {
- tag_set: tag_array
- }
+ tag_set: tag_array,
+ },
)
end
@@ -269,9 +261,7 @@ class S3Helper
end
def self.s3_options(obj)
- opts = {
- region: obj.s3_region
- }
+ opts = { region: obj.s3_region }
opts[:endpoint] = SiteSetting.s3_endpoint if SiteSetting.s3_endpoint.present?
opts[:http_continue_timeout] = SiteSetting.s3_http_continue_timeout
@@ -287,33 +277,31 @@ class S3Helper
def download_file(filename, destination_path, failure_message = nil)
object(filename).download_file(destination_path)
rescue => err
- raise failure_message&.to_s || "Failed to download #{filename} because #{err.message.length > 0 ? err.message : err.class.to_s}"
+ raise failure_message&.to_s ||
+ "Failed to download #{filename} because #{err.message.length > 0 ? err.message : err.class.to_s}"
end
def s3_client
@s3_client ||= Aws::S3::Client.new(@s3_options)
end
- def s3_inventory_path(path = 'inventory')
+ def s3_inventory_path(path = "inventory")
get_path_for_s3_upload(path)
end
def abort_multipart(key:, upload_id:)
- s3_client.abort_multipart_upload(
- bucket: s3_bucket_name,
- key: key,
- upload_id: upload_id
- )
+ s3_client.abort_multipart_upload(bucket: s3_bucket_name, key: key, upload_id: upload_id)
end
def create_multipart(key, content_type, metadata: {})
- response = s3_client.create_multipart_upload(
- acl: "private",
- bucket: s3_bucket_name,
- key: key,
- content_type: content_type,
- metadata: metadata
- )
+ response =
+ s3_client.create_multipart_upload(
+ acl: "private",
+ bucket: s3_bucket_name,
+ key: key,
+ content_type: content_type,
+ metadata: metadata,
+ )
{ upload_id: response.upload_id, key: key }
end
@@ -324,8 +312,8 @@ class S3Helper
expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS,
opts: {
part_number: part_number,
- upload_id: upload_id
- }
+ upload_id: upload_id,
+ },
)
end
@@ -343,16 +331,9 @@ class S3Helper
#
# See https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Client.html#list_parts-instance_method
def list_multipart_parts(upload_id:, key:, max_parts: 1000, start_from_part_number: nil)
- options = {
- bucket: s3_bucket_name,
- key: key,
- upload_id: upload_id,
- max_parts: max_parts
- }
+ options = { bucket: s3_bucket_name, key: key, upload_id: upload_id, max_parts: max_parts }
- if start_from_part_number.present?
- options[:part_number_marker] = start_from_part_number
- end
+ options[:part_number_marker] = start_from_part_number if start_from_part_number.present?
s3_client.list_parts(options)
end
@@ -363,24 +344,15 @@ class S3Helper
key: key,
upload_id: upload_id,
multipart_upload: {
- parts: parts
- }
+ parts: parts,
+ },
)
end
- def presigned_url(
- key,
- method:,
- expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS,
- opts: {}
- )
+ def presigned_url(key, method:, expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS, opts: {})
Aws::S3::Presigner.new(client: s3_client).presigned_url(
method,
- {
- bucket: s3_bucket_name,
- key: key,
- expires_in: expires_in,
- }.merge(opts)
+ { bucket: s3_bucket_name, key: key, expires_in: expires_in }.merge(opts),
)
end
@@ -388,9 +360,7 @@ class S3Helper
def fetch_bucket_cors_rules
begin
- s3_resource.client.get_bucket_cors(
- bucket: @s3_bucket_name
- ).cors_rules&.map(&:to_h) || []
+ s3_resource.client.get_bucket_cors(bucket: @s3_bucket_name).cors_rules&.map(&:to_h) || []
rescue Aws::S3::Errors::NoSuchCORSConfiguration
# no rule
[]
@@ -410,9 +380,10 @@ class S3Helper
end
def get_path_for_s3_upload(path)
- if @s3_bucket_folder_path &&
- !path.starts_with?(@s3_bucket_folder_path) &&
- !path.starts_with?(File.join(FileStore::BaseStore::TEMPORARY_UPLOAD_PREFIX, @s3_bucket_folder_path))
+ if @s3_bucket_folder_path && !path.starts_with?(@s3_bucket_folder_path) &&
+ !path.starts_with?(
+ File.join(FileStore::BaseStore::TEMPORARY_UPLOAD_PREFIX, @s3_bucket_folder_path),
+ )
return File.join(@s3_bucket_folder_path, path)
end
@@ -422,7 +393,7 @@ class S3Helper
def multisite_upload_path
path = File.join("uploads", RailsMultisite::ConnectionManagement.current_db, "/")
return path if !Rails.env.test?
- File.join(path, "test_#{ENV['TEST_ENV_NUMBER'].presence || '0'}", "/")
+ File.join(path, "test_#{ENV["TEST_ENV_NUMBER"].presence || "0"}", "/")
end
def s3_resource
@@ -430,11 +401,12 @@ class S3Helper
end
def s3_bucket
- @s3_bucket ||= begin
- bucket = s3_resource.bucket(@s3_bucket_name)
- bucket.create unless bucket.exists?
- bucket
- end
+ @s3_bucket ||=
+ begin
+ bucket = s3_resource.bucket(@s3_bucket_name)
+ bucket.create unless bucket.exists?
+ bucket
+ end
end
def check_missing_site_options
diff --git a/lib/s3_inventory.rb b/lib/s3_inventory.rb
index 615f790b10b..91da944b927 100644
--- a/lib/s3_inventory.rb
+++ b/lib/s3_inventory.rb
@@ -4,7 +4,6 @@ require "aws-sdk-s3"
require "csv"
class S3Inventory
-
attr_reader :type, :model, :inventory_date
CSV_KEY_INDEX ||= 1
@@ -44,7 +43,9 @@ class S3Inventory
multisite_prefix = Discourse.store.upload_path
ActiveRecord::Base.transaction do
begin
- connection.exec("CREATE TEMP TABLE #{table_name}(url text UNIQUE, etag text, PRIMARY KEY(etag, url))")
+ connection.exec(
+ "CREATE TEMP TABLE #{table_name}(url text UNIQUE, etag text, PRIMARY KEY(etag, url))",
+ )
connection.copy_data("COPY #{table_name} FROM STDIN CSV") do
for_each_inventory_row do |row|
key = row[CSV_KEY_INDEX]
@@ -58,22 +59,29 @@ class S3Inventory
end
# backfilling etags
- connection.async_exec("UPDATE #{model.table_name}
+ connection.async_exec(
+ "UPDATE #{model.table_name}
SET etag = #{table_name}.etag
FROM #{table_name}
WHERE #{model.table_name}.etag IS NULL AND
- #{model.table_name}.url = #{table_name}.url")
+ #{model.table_name}.url = #{table_name}.url",
+ )
uploads = model.where("updated_at < ?", inventory_date)
uploads = uploads.by_users if model == Upload
- missing_uploads = uploads
- .joins("LEFT JOIN #{table_name} ON #{table_name}.etag = #{model.table_name}.etag")
- .where("#{table_name}.etag IS NULL")
+ missing_uploads =
+ uploads.joins(
+ "LEFT JOIN #{table_name} ON #{table_name}.etag = #{model.table_name}.etag",
+ ).where("#{table_name}.etag IS NULL")
- exists_with_different_etag = missing_uploads
- .joins("LEFT JOIN #{table_name} inventory2 ON inventory2.url = #{model.table_name}.url")
- .where("inventory2.etag IS NOT NULL").pluck(:id)
+ exists_with_different_etag =
+ missing_uploads
+ .joins(
+ "LEFT JOIN #{table_name} inventory2 ON inventory2.url = #{model.table_name}.url",
+ )
+ .where("inventory2.etag IS NOT NULL")
+ .pluck(:id)
# marking as verified/not verified
if model == Upload
@@ -81,7 +89,7 @@ class S3Inventory
inventory_date: inventory_date,
invalid_etag: Upload.verification_statuses[:invalid_etag],
verified: Upload.verification_statuses[:verified],
- seeded_id_threshold: model::SEEDED_ID_THRESHOLD
+ seeded_id_threshold: model::SEEDED_ID_THRESHOLD,
}
DB.exec(<<~SQL, sql_params)
@@ -115,13 +123,15 @@ class S3Inventory
end
if (missing_count = missing_uploads.count) > 0
- missing_uploads.select(:id, :url).find_each do |upload|
- if exists_with_different_etag.include?(upload.id)
- log "#{upload.url} has different etag"
- else
- log upload.url
+ missing_uploads
+ .select(:id, :url)
+ .find_each do |upload|
+ if exists_with_different_etag.include?(upload.id)
+ log "#{upload.url} has different etag"
+ else
+ log upload.url
+ end
end
- end
log "#{missing_count} of #{uploads.count} #{model.name.underscore.pluralize} are missing"
if exists_with_different_etag.present?
@@ -145,9 +155,7 @@ class S3Inventory
if @preloaded_inventory_file
CSV.foreach(@preloaded_inventory_file) { |row| yield(row) }
else
- files.each do |file|
- CSV.foreach(file[:filename][0...-3]) { |row| yield(row) }
- end
+ files.each { |file| CSV.foreach(file[:filename][0...-3]) { |row| yield(row) } }
end
end
@@ -162,32 +170,40 @@ class S3Inventory
def decompress_inventory_file(file)
log "Decompressing inventory file '#{file[:filename]}', this may take a while..."
- Discourse::Utils.execute_command('gzip', '--decompress', file[:filename], failure_message: "Failed to decompress inventory file '#{file[:filename]}'.", chdir: tmp_directory)
+ Discourse::Utils.execute_command(
+ "gzip",
+ "--decompress",
+ file[:filename],
+ failure_message: "Failed to decompress inventory file '#{file[:filename]}'.",
+ chdir: tmp_directory,
+ )
end
def update_bucket_policy
@s3_helper.s3_client.put_bucket_policy(
bucket: bucket_name,
policy: {
- "Version": "2012-10-17",
- "Statement": [
+ Version: "2012-10-17",
+ Statement: [
{
- "Sid": "InventoryAndAnalyticsPolicy",
- "Effect": "Allow",
- "Principal": { "Service": "s3.amazonaws.com" },
- "Action": ["s3:PutObject"],
- "Resource": ["#{inventory_path_arn}/*"],
- "Condition": {
- "ArnLike": {
- "aws:SourceArn": bucket_arn
+ Sid: "InventoryAndAnalyticsPolicy",
+ Effect: "Allow",
+ Principal: {
+ Service: "s3.amazonaws.com",
+ },
+ Action: ["s3:PutObject"],
+ Resource: ["#{inventory_path_arn}/*"],
+ Condition: {
+ ArnLike: {
+ "aws:SourceArn": bucket_arn,
},
- "StringEquals": {
- "s3:x-amz-acl": "bucket-owner-full-control"
- }
- }
- }
- ]
- }.to_json
+ StringEquals: {
+ "s3:x-amz-acl": "bucket-owner-full-control",
+ },
+ },
+ },
+ ],
+ }.to_json,
)
end
@@ -196,7 +212,7 @@ class S3Inventory
bucket: bucket_name,
id: inventory_id,
inventory_configuration: inventory_configuration,
- use_accelerate_endpoint: false
+ use_accelerate_endpoint: false,
)
end
@@ -204,22 +220,18 @@ class S3Inventory
db_names = RailsMultisite::ConnectionManagement.all_dbs
db_files = {}
- db_names.each do |db|
- db_files[db] = Tempfile.new("#{db}-inventory.csv")
- end
+ db_names.each { |db| db_files[db] = Tempfile.new("#{db}-inventory.csv") }
download_and_decompress_files
for_each_inventory_row do |row|
key = row[CSV_KEY_INDEX]
- row_db = key.match(/uploads\/([^\/]+)\//)&.[](1)
+ row_db = key.match(%r{uploads/([^/]+)/})&.[](1)
if row_db && file = db_files[row_db]
file.write(row.to_csv)
end
end
- db_names.each do |db|
- db_files[db].rewind
- end
+ db_names.each { |db| db_files[db].rewind }
db_files
ensure
@@ -246,21 +258,24 @@ class S3Inventory
def files
return if @preloaded_inventory_file
- @files ||= begin
- symlink_file = unsorted_files.sort_by { |file| -file.last_modified.to_i }.first
- return [] if symlink_file.blank?
-
- @inventory_date = symlink_file.last_modified - INVENTORY_LAG
- log "Downloading symlink file to tmp directory..."
- failure_message = "Failed to download symlink file to tmp directory."
- filename = File.join(tmp_directory, File.basename(symlink_file.key))
-
- @s3_helper.download_file(symlink_file.key, filename, failure_message)
- File.readlines(filename).map do |key|
- key = key.sub("s3://#{bucket_name}/", "").sub("\n", "")
- { key: key, filename: File.join(tmp_directory, File.basename(key)) }
+ @files ||=
+ begin
+ symlink_file = unsorted_files.sort_by { |file| -file.last_modified.to_i }.first
+ return [] if symlink_file.blank?
+
+ @inventory_date = symlink_file.last_modified - INVENTORY_LAG
+ log "Downloading symlink file to tmp directory..."
+ failure_message = "Failed to download symlink file to tmp directory."
+ filename = File.join(tmp_directory, File.basename(symlink_file.key))
+
+ @s3_helper.download_file(symlink_file.key, filename, failure_message)
+ File
+ .readlines(filename)
+ .map do |key|
+ key = key.sub("s3://#{bucket_name}/", "").sub("\n", "")
+ { key: key, filename: File.join(tmp_directory, File.basename(key)) }
+ end
end
- end
end
def download_and_decompress_files
@@ -273,12 +288,13 @@ class S3Inventory
end
def tmp_directory
- @tmp_directory ||= begin
- current_db = RailsMultisite::ConnectionManagement.current_db
- directory = File.join(Rails.root, "tmp", INVENTORY_PREFIX, current_db)
- FileUtils.mkdir_p(directory)
- directory
- end
+ @tmp_directory ||=
+ begin
+ current_db = RailsMultisite::ConnectionManagement.current_db
+ directory = File.join(Rails.root, "tmp", INVENTORY_PREFIX, current_db)
+ FileUtils.mkdir_p(directory)
+ directory
+ end
end
def inventory_configuration
@@ -290,19 +306,19 @@ class S3Inventory
s3_bucket_destination: {
bucket: bucket_arn,
prefix: inventory_path,
- format: "CSV"
- }
+ format: "CSV",
+ },
},
filter: {
- prefix: filter_prefix
+ prefix: filter_prefix,
},
is_enabled: SiteSetting.enable_s3_inventory,
id: inventory_id,
included_object_versions: "Current",
optional_fields: ["ETag"],
schedule: {
- frequency: "Daily"
- }
+ frequency: "Daily",
+ },
}
end
@@ -318,11 +334,7 @@ class S3Inventory
objects = []
hive_path = File.join(inventory_path, bucket_name, inventory_id, "hive")
- @s3_helper.list(hive_path).each do |obj|
- if obj.key.match?(/symlink\.txt$/i)
- objects << obj
- end
- end
+ @s3_helper.list(hive_path).each { |obj| objects << obj if obj.key.match?(/symlink\.txt$/i) }
objects
rescue Aws::Errors::ServiceError => e
@@ -331,10 +343,11 @@ class S3Inventory
end
def inventory_id
- @inventory_id ||= begin
- id = Rails.configuration.multisite ? "original" : type # TODO: rename multisite path to "uploads"
- bucket_folder_path.present? ? "#{bucket_folder_path}-#{id}" : id
- end
+ @inventory_id ||=
+ begin
+ id = Rails.configuration.multisite ? "original" : type # TODO: rename multisite path to "uploads"
+ bucket_folder_path.present? ? "#{bucket_folder_path}-#{id}" : id
+ end
end
def inventory_path_arn
diff --git a/lib/scheduler/defer.rb b/lib/scheduler/defer.rb
index f4a847eef87..0afdcfbaa0b 100644
--- a/lib/scheduler/defer.rb
+++ b/lib/scheduler/defer.rb
@@ -1,10 +1,8 @@
# frozen_string_literal: true
-require 'weakref'
+require "weakref"
module Scheduler
-
module Deferrable
-
DEFAULT_TIMEOUT ||= 90
def initialize
@@ -18,9 +16,7 @@ module Scheduler
end
def timeout=(t)
- @mutex.synchronize do
- @timeout = t
- end
+ @mutex.synchronize { @timeout = t }
end
def length
@@ -63,21 +59,15 @@ module Scheduler
end
def do_all_work
- do_work(_non_block = true)
- end
+ do_work(_non_block = true) while [email protected]?
end
private
def start_thread
@mutex.synchronize do
- if !@reactor
- @reactor = MessageBus::TimerThread.new
- end
- if !@thread&.alive?
- @thread = Thread.new { do_work while true }
- end
+ @reactor = MessageBus::TimerThread.new if !@reactor
+ @thread = Thread.new { do_work while true } if !@thread&.alive?
end
end
@@ -88,9 +78,10 @@ module Scheduler
RailsMultisite::ConnectionManagement.with_connection(db) do
begin
- warning_job = @reactor.queue(@timeout) do
- Rails.logger.error "'#{desc}' is still running after #{@timeout} seconds on db #{db}, this process may need to be restarted!"
- end if !non_block
+ warning_job =
+ @reactor.queue(@timeout) do
+ Rails.logger.error "'#{desc}' is still running after #{@timeout} seconds on db #{db}, this process may need to be restarted!"
+ end if !non_block
job.call
rescue => ex
Discourse.handle_job_exception(ex, message: "Running deferred code '#{desc}'")
diff --git a/lib/score_calculator.rb b/lib/score_calculator.rb
index a4e7bfec775..79658395ec5 100644
--- a/lib/score_calculator.rb
+++ b/lib/score_calculator.rb
@@ -1,15 +1,8 @@
# frozen_string_literal: true
class ScoreCalculator
-
def self.default_score_weights
- {
- reply_count: 5,
- like_score: 15,
- incoming_link_count: 5,
- bookmark_count: 2,
- reads: 0.2
- }
+ { reply_count: 5, like_score: 15, incoming_link_count: 5, bookmark_count: 2, reads: 0.2 }
end
def initialize(weightings = nil)
@@ -26,7 +19,7 @@ class ScoreCalculator
private
def update_posts_score(opts)
- limit = 20000
+ limit = 20_000
components = []
@weightings.each_key { |k| components << "COALESCE(posts.#{k}, 0) * :#{k}" }
@@ -53,7 +46,7 @@ SQL
end
def update_posts_rank(opts)
- limit = 20000
+ limit = 20_000
builder = DB.build <<~SQL
UPDATE posts
@@ -79,7 +72,6 @@ SQL
while builder.exec == limit
end
-
end
def update_topics_rank(opts)
@@ -100,7 +92,7 @@ SQL
defaults = {
likes_required: SiteSetting.summary_likes_required,
posts_required: SiteSetting.summary_posts_required,
- score_required: SiteSetting.summary_score_threshold
+ score_required: SiteSetting.summary_score_threshold,
}
builder.where(<<~SQL, defaults)
@@ -124,15 +116,12 @@ SQL
return builder unless opts
if min_topic_age = opts[:min_topic_age]
- builder.where("topics.bumped_at > :bumped_at ",
- bumped_at: min_topic_age)
+ builder.where("topics.bumped_at > :bumped_at ", bumped_at: min_topic_age)
end
if max_topic_length = opts[:max_topic_length]
- builder.where("topics.posts_count < :max_topic_length",
- max_topic_length: max_topic_length)
+ builder.where("topics.posts_count < :max_topic_length", max_topic_length: max_topic_length)
end
builder
end
-
end
diff --git a/lib/screening_model.rb b/lib/screening_model.rb
index 2e4bfcda115..d5eaa6524c9 100644
--- a/lib/screening_model.rb
+++ b/lib/screening_model.rb
@@ -17,16 +17,16 @@ module ScreeningModel
end
end
- included do
- before_validation :set_default_action
- end
+ included { before_validation :set_default_action }
def set_default_action
self.action_type ||= self.class.actions[self.class.df_action]
end
def action_name=(arg)
- raise ArgumentError.new("Invalid action type #{arg}") if arg.nil? || !self.class.actions.has_key?(arg.to_sym)
+ if arg.nil? || !self.class.actions.has_key?(arg.to_sym)
+ raise ArgumentError.new("Invalid action type #{arg}")
+ end
self.action_type = self.class.actions[arg.to_sym]
end
diff --git a/lib/search.rb b/lib/search.rb
index 4f983b3aa3e..95e1c69fe67 100644
--- a/lib/search.rb
+++ b/lib/search.rb
@@ -2,7 +2,7 @@
class Search
DIACRITICS ||= /([\u0300-\u036f]|[\u1AB0-\u1AFF]|[\u1DC0-\u1DFF]|[\u20D0-\u20FF])/
- HIGHLIGHT_CSS_CLASS = 'search-highlight'
+ HIGHLIGHT_CSS_CLASS = "search-highlight"
cattr_accessor :preloaded_topic_custom_fields
self.preloaded_topic_custom_fields = Set.new
@@ -12,9 +12,7 @@ class Search
end
def self.preload(results, object)
- if @preload
- @preload.each { |preload| preload.call(results, object) }
- end
+ @preload.each { |preload| preload.call(results, object) } if @preload
end
def self.per_facet
@@ -26,7 +24,7 @@ class Search
end
def self.facets
- %w(topic category user private_messages tags all_topics exclude_topics)
+ %w[topic category user private_messages tags all_topics exclude_topics]
end
def self.ts_config(locale = SiteSetting.default_locale)
@@ -38,22 +36,38 @@ class Search
# base docker config
#
case locale.split("_")[0].to_sym
- when :da then 'danish'
- when :nl then 'dutch'
- when :en then 'english'
- when :fi then 'finnish'
- when :fr then 'french'
- when :de then 'german'
- when :hu then 'hungarian'
- when :it then 'italian'
- when :nb then 'norwegian'
- when :pt then 'portuguese'
- when :ro then 'romanian'
- when :ru then 'russian'
- when :es then 'spanish'
- when :sv then 'swedish'
- when :tr then 'turkish'
- else 'simple' # use the 'simple' stemmer for other languages
+ when :da
+ "danish"
+ when :nl
+ "dutch"
+ when :en
+ "english"
+ when :fi
+ "finnish"
+ when :fr
+ "french"
+ when :de
+ "german"
+ when :hu
+ "hungarian"
+ when :it
+ "italian"
+ when :nb
+ "norwegian"
+ when :pt
+ "portuguese"
+ when :ro
+ "romanian"
+ when :ru
+ "russian"
+ when :es
+ "spanish"
+ when :sv
+ "swedish"
+ when :tr
+ "turkish"
+ else
+ "simple" # use the 'simple' stemmer for other languages
end
end
@@ -62,7 +76,7 @@ class Search
end
def self.segment_chinese?
- ['zh_TW', 'zh_CN'].include?(SiteSetting.default_locale) || SiteSetting.search_tokenize_chinese
+ %w[zh_TW zh_CN].include?(SiteSetting.default_locale) || SiteSetting.search_tokenize_chinese
end
def self.segment_japanese?
@@ -71,7 +85,8 @@ class Search
def self.japanese_punctuation_regexp
# Regexp adapted from https://github.com/6/tiny_segmenter/blob/15a5b825993dfd2c662df3766f232051716bef5b/lib/tiny_segmenter.rb#L7
- @japanese_punctuation_regexp ||= Regexp.compile("[-–—―.。・()()[]{}{}【】⟨⟩、、,,،…‥〽「」『』〜~!!::??\"'|__“”‘’;/⁄/«»]")
+ @japanese_punctuation_regexp ||=
+ Regexp.compile("[-–—―.。・()()[]{}{}【】⟨⟩、、,,،…‥〽「」『』〜~!!::??\"'|__“”‘’;/⁄/«»]")
end
def self.prepare_data(search_data, purpose = nil)
@@ -80,7 +95,7 @@ class Search
if purpose != :topic
if segment_chinese?
- require 'cppjieba_rb' unless defined? CppjiebaRb
+ require "cppjieba_rb" unless defined?(CppjiebaRb)
segmented_data = []
@@ -92,30 +107,28 @@ class Search
if match_data[:chinese]
segments = CppjiebaRb.segment(match_data.to_s, mode: :mix)
- if ts_config != 'english'
- segments = CppjiebaRb.filter_stop_word(segments)
- end
+ segments = CppjiebaRb.filter_stop_word(segments) if ts_config != "english"
segments = segments.filter { |s| s.present? }
- segmented_data << segments.join(' ')
+ segmented_data << segments.join(" ")
else
segmented_data << match_data.to_s.squish
end
end
- data = segmented_data.join(' ')
+ data = segmented_data.join(" ")
elsif segment_japanese?
data.gsub!(japanese_punctuation_regexp, " ")
data = TinyJapaneseSegmenter.segment(data)
data = data.filter { |s| s.present? }
- data = data.join(' ')
+ data = data.join(" ")
else
data.squish!
end
end
data.gsub!(/\S+/) do |str|
- if str =~ /^["]?((https?:\/\/)[\S]+)["]?$/
+ if str =~ %r{^["]?((https?://)[\S]+)["]?$}
begin
uri = URI.parse(Regexp.last_match[1])
uri.query = nil
@@ -132,10 +145,7 @@ class Search
end
def self.word_to_date(str)
-
- if str =~ /^[0-9]{1,3}$/
- return Time.zone.now.beginning_of_day.days_ago(str.to_i)
- end
+ return Time.zone.now.beginning_of_day.days_ago(str.to_i) if str =~ /^[0-9]{1,3}$/
if str =~ /^([12][0-9]{3})(-([0-1]?[0-9]))?(-([0-3]?[0-9]))?$/
year = $1.to_i
@@ -144,15 +154,15 @@ class Search
return if day == 0 || month == 0 || day > 31 || month > 12
- return begin
- Time.zone.parse("#{year}-#{month}-#{day}")
- rescue ArgumentError
- end
+ return(
+ begin
+ Time.zone.parse("#{year}-#{month}-#{day}")
+ rescue ArgumentError
+ end
+ )
end
- if str.downcase == "yesterday"
- return Time.zone.now.beginning_of_day.yesterday
- end
+ return Time.zone.now.beginning_of_day.yesterday if str.downcase == "yesterday"
titlecase = str.downcase.titlecase
@@ -160,8 +170,7 @@ class Search
return Time.zone.now.beginning_of_week(str.downcase.to_sym)
end
- if idx = (Date::MONTHNAMES.find_index(titlecase) ||
- Date::ABBR_MONTHNAMES.find_index(titlecase))
+ if idx = (Date::MONTHNAMES.find_index(titlecase) || Date::ABBR_MONTHNAMES.find_index(titlecase))
delta = Time.zone.now.month - idx
delta += 12 if delta < 0
Time.zone.now.beginning_of_month.months_ago(delta)
@@ -171,11 +180,13 @@ class Search
def self.min_post_id_no_cache
return 0 unless SiteSetting.search_prefer_recent_posts?
- offset, has_more = Post.unscoped
- .order('id desc')
- .offset(SiteSetting.search_recent_posts_size - 1)
- .limit(2)
- .pluck(:id)
+ offset, has_more =
+ Post
+ .unscoped
+ .order("id desc")
+ .offset(SiteSetting.search_recent_posts_size - 1)
+ .limit(2)
+ .pluck(:id)
has_more ? offset : 0
end
@@ -184,9 +195,11 @@ class Search
return 0 unless SiteSetting.search_prefer_recent_posts?
# It can be quite slow to count all the posts so let's cache it
- Discourse.cache.fetch("search-min-post-id:#{SiteSetting.search_recent_posts_size}", expires_in: 1.week) do
- min_post_id_no_cache
- end
+ Discourse
+ .cache
+ .fetch("search-min-post-id:#{SiteSetting.search_recent_posts_size}", expires_in: 1.week) do
+ min_post_id_no_cache
+ end
end
attr_accessor :term
@@ -204,7 +217,7 @@ class Search
term = term.to_s.dup
# Removes any zero-width characters from search terms
- term.gsub!(/[\u200B-\u200D\uFEFF]/, '')
+ term.gsub!(/[\u200B-\u200D\uFEFF]/, "")
# Replace curly quotes to regular quotes
term.gsub!(/[\u201c\u201d]/, '"')
@@ -218,7 +231,7 @@ class Search
@original_term = Search.escape_string(@term)
end
- if @search_pms || @search_all_pms || @opts[:type_filter] == 'private_messages'
+ if @search_pms || @search_all_pms || @opts[:type_filter] == "private_messages"
@opts[:type_filter] = "private_messages"
@search_context ||= @guardian.user
@@ -227,18 +240,17 @@ class Search
end
end
- if @search_all_topics && @guardian.user
- @opts[:type_filter] = "all_topics"
- end
+ @opts[:type_filter] = "all_topics" if @search_all_topics && @guardian.user
- @results = GroupedSearchResults.new(
- type_filter: @opts[:type_filter],
- term: clean_term,
- blurb_term: term,
- search_context: @search_context,
- blurb_length: @blurb_length,
- is_header_search: !use_full_page_limit
- )
+ @results =
+ GroupedSearchResults.new(
+ type_filter: @opts[:type_filter],
+ term: clean_term,
+ blurb_term: term,
+ search_context: @search_context,
+ blurb_length: @blurb_length,
+ is_header_search: !use_full_page_limit,
+ )
end
def limit
@@ -272,28 +284,29 @@ class Search
# Query a term
def execute(readonly_mode: Discourse.readonly_mode?)
if log_query?(readonly_mode)
- status, search_log_id = SearchLog.log(
- term: @clean_term,
- search_type: @opts[:search_type],
- ip_address: @opts[:ip_address],
- user_id: @opts[:user_id]
- )
+ status, search_log_id =
+ SearchLog.log(
+ term: @clean_term,
+ search_type: @opts[:search_type],
+ ip_address: @opts[:ip_address],
+ user_id: @opts[:user_id],
+ )
@results.search_log_id = search_log_id unless status == :error
end
unless @filters.present? || @opts[:search_for_id]
min_length = min_search_term_length
- terms = (@term || '').split(/\s(?=(?:[^"]|"[^"]*")*$)/).reject { |t| t.length < min_length }
+ terms = (@term || "").split(/\s(?=(?:[^"]|"[^"]*")*$)/).reject { |t| t.length < min_length }
if terms.blank?
- @term = ''
+ @term = ""
@valid = false
return
end
end
# If the term is a number or url to a topic, just include that topic
- if @opts[:search_for_id] && ['topic', 'private_messages', 'all_topics'].include?(@results.type_filter)
+ if @opts[:search_for_id] && %w[topic private_messages all_topics].include?(@results.type_filter)
if @term =~ /^\d+$/
single_topic(@term.to_i)
else
@@ -344,9 +357,8 @@ class Search
advanced_filter(/^in:personal-direct$/i) do |posts|
if @guardian.user
- posts
- .joins("LEFT JOIN topic_allowed_groups tg ON posts.topic_id = tg.topic_id")
- .where(<<~SQL, user_id: @guardian.user.id)
+ posts.joins("LEFT JOIN topic_allowed_groups tg ON posts.topic_id = tg.topic_id").where(
+ <<~SQL,
tg.id IS NULL
AND posts.topic_id IN (
SELECT tau.topic_id
@@ -359,52 +371,41 @@ class Search
HAVING COUNT(*) = 1
)
SQL
+ user_id: @guardian.user.id,
+ )
end
end
- advanced_filter(/^in:all-pms$/i) do |posts|
- posts.private_posts if @guardian.is_admin?
- end
+ advanced_filter(/^in:all-pms$/i) { |posts| posts.private_posts if @guardian.is_admin? }
advanced_filter(/^in:tagged$/i) do |posts|
- posts
- .where('EXISTS (SELECT 1 FROM topic_tags WHERE topic_tags.topic_id = posts.topic_id)')
+ posts.where("EXISTS (SELECT 1 FROM topic_tags WHERE topic_tags.topic_id = posts.topic_id)")
end
advanced_filter(/^in:untagged$/i) do |posts|
- posts
- .joins("LEFT JOIN topic_tags ON
- topic_tags.topic_id = posts.topic_id")
- .where("topic_tags.id IS NULL")
+ posts.joins(
+ "LEFT JOIN topic_tags ON
+ topic_tags.topic_id = posts.topic_id",
+ ).where("topic_tags.id IS NULL")
end
advanced_filter(/^status:open$/i) do |posts|
- posts.where('NOT topics.closed AND NOT topics.archived')
+ posts.where("NOT topics.closed AND NOT topics.archived")
end
- advanced_filter(/^status:closed$/i) do |posts|
- posts.where('topics.closed')
- end
+ advanced_filter(/^status:closed$/i) { |posts| posts.where("topics.closed") }
advanced_filter(/^status:public$/i) do |posts|
- category_ids = Category
- .where(read_restricted: false)
- .pluck(:id)
+ category_ids = Category.where(read_restricted: false).pluck(:id)
posts.where("topics.category_id in (?)", category_ids)
end
- advanced_filter(/^status:archived$/i) do |posts|
- posts.where('topics.archived')
- end
+ advanced_filter(/^status:archived$/i) { |posts| posts.where("topics.archived") }
- advanced_filter(/^status:noreplies$/i) do |posts|
- posts.where("topics.posts_count = 1")
- end
+ advanced_filter(/^status:noreplies$/i) { |posts| posts.where("topics.posts_count = 1") }
- advanced_filter(/^status:single_user$/i) do |posts|
- posts.where("topics.participant_count = 1")
- end
+ advanced_filter(/^status:single_user$/i) { |posts| posts.where("topics.participant_count = 1") }
advanced_filter(/^posts_count:(\d+)$/i) do |posts, match|
posts.where("topics.posts_count = ?", match.to_i)
@@ -422,40 +423,39 @@ class Search
posts.where("topics.posts_count <= ?", match.to_i)
end
- advanced_filter(/^in:first|^f$/i) do |posts|
- posts.where("posts.post_number = 1")
- end
+ advanced_filter(/^in:first|^f$/i) { |posts| posts.where("posts.post_number = 1") }
- advanced_filter(/^in:pinned$/i) do |posts|
- posts.where("topics.pinned_at IS NOT NULL")
- end
+ advanced_filter(/^in:pinned$/i) { |posts| posts.where("topics.pinned_at IS NOT NULL") }
- advanced_filter(/^in:wiki$/i) do |posts, match|
- posts.where(wiki: true)
- end
+ advanced_filter(/^in:wiki$/i) { |posts, match| posts.where(wiki: true) }
advanced_filter(/^badge:(.*)$/i) do |posts, match|
- badge_id = Badge.where('name ilike ? OR id = ?', match, match.to_i).pluck_first(:id)
+ badge_id = Badge.where("name ilike ? OR id = ?", match, match.to_i).pluck_first(:id)
if badge_id
- posts.where('posts.user_id IN (SELECT ub.user_id FROM user_badges ub WHERE ub.badge_id = ?)', badge_id)
+ posts.where(
+ "posts.user_id IN (SELECT ub.user_id FROM user_badges ub WHERE ub.badge_id = ?)",
+ badge_id,
+ )
else
posts.where("1 = 0")
end
end
def post_action_type_filter(posts, post_action_type)
- posts.where("posts.id IN (
+ posts.where(
+ "posts.id IN (
SELECT pa.post_id FROM post_actions pa
WHERE pa.user_id = ? AND
pa.post_action_type_id = ? AND
deleted_at IS NULL
- )", @guardian.user.id, post_action_type)
+ )",
+ @guardian.user.id,
+ post_action_type,
+ )
end
advanced_filter(/^in:(likes)$/i) do |posts, match|
- if @guardian.user
- post_action_type_filter(posts, PostActionType.types[:like])
- end
+ post_action_type_filter(posts, PostActionType.types[:like]) if @guardian.user
end
# NOTE: With polymorphic bookmarks it may make sense to possibly expand
@@ -463,14 +463,12 @@ class Search
# hand, this may not be necessary, as the user bookmark list has advanced
# search based on a RegisteredBookmarkable's #search_query method.
advanced_filter(/^in:(bookmarks)$/i) do |posts, match|
- if @guardian.user
- posts.where(<<~SQL, @guardian.user.id)
+ posts.where(<<~SQL, @guardian.user.id) if @guardian.user
posts.id IN (
SELECT bookmarkable_id FROM bookmarks
WHERE bookmarks.user_id = ? AND bookmarks.bookmarkable_type = 'Post'
)
SQL
- end
end
advanced_filter(/^in:posted$/i) do |posts|
@@ -489,41 +487,43 @@ class Search
advanced_filter(/^in:(watching|tracking)$/i) do |posts, match|
if @guardian.user
level = TopicUser.notification_levels[match.downcase.to_sym]
- posts.where("posts.topic_id IN (
+ posts.where(
+ "posts.topic_id IN (
SELECT tu.topic_id FROM topic_users tu
WHERE tu.user_id = :user_id AND
tu.notification_level >= :level
- )", user_id: @guardian.user.id, level: level)
-
+ )",
+ user_id: @guardian.user.id,
+ level: level,
+ )
end
end
advanced_filter(/^in:seen$/i) do |posts|
if @guardian.user
- posts
- .joins("INNER JOIN post_timings ON
+ posts.joins(
+ "INNER JOIN post_timings ON
post_timings.topic_id = posts.topic_id
AND post_timings.post_number = posts.post_number
AND post_timings.user_id = #{ActiveRecord::Base.connection.quote(@guardian.user.id)}
- ")
+ ",
+ )
end
end
advanced_filter(/^in:unseen$/i) do |posts|
if @guardian.user
- posts
- .joins("LEFT JOIN post_timings ON
+ posts.joins(
+ "LEFT JOIN post_timings ON
post_timings.topic_id = posts.topic_id
AND post_timings.post_number = posts.post_number
AND post_timings.user_id = #{ActiveRecord::Base.connection.quote(@guardian.user.id)}
- ")
- .where("post_timings.user_id IS NULL")
+ ",
+ ).where("post_timings.user_id IS NULL")
end
end
- advanced_filter(/^with:images$/i) do |posts|
- posts.where("posts.image_upload_id IS NOT NULL")
- end
+ advanced_filter(/^with:images$/i) { |posts| posts.where("posts.image_upload_id IS NOT NULL") }
advanced_filter(/^category:(.+)$/i) do |posts, match|
exact = false
@@ -533,8 +533,8 @@ class Search
match = match[1..-1]
end
- category_ids = Category.where('slug ilike ? OR name ilike ? OR id = ?',
- match, match, match.to_i).pluck(:id)
+ category_ids =
+ Category.where("slug ilike ? OR name ilike ? OR id = ?", match, match, match.to_i).pluck(:id)
if category_ids.present?
category_ids += Category.subcategory_ids(category_ids.first) unless exact
@category_filter_matched ||= true
@@ -555,17 +555,21 @@ class Search
exact = false
end
- category_id = if subcategory_slug
- Category
- .where('lower(slug) = ?', subcategory_slug.downcase)
- .where(parent_category_id: Category.where('lower(slug) = ?', category_slug.downcase).select(:id))
- .pluck_first(:id)
- else
- Category
- .where('lower(slug) = ?', category_slug.downcase)
- .order('case when parent_category_id is null then 0 else 1 end')
- .pluck_first(:id)
- end
+ category_id =
+ if subcategory_slug
+ Category
+ .where("lower(slug) = ?", subcategory_slug.downcase)
+ .where(
+ parent_category_id:
+ Category.where("lower(slug) = ?", category_slug.downcase).select(:id),
+ )
+ .pluck_first(:id)
+ else
+ Category
+ .where("lower(slug) = ?", category_slug.downcase)
+ .order("case when parent_category_id is null then 0 else 1 end")
+ .pluck_first(:id)
+ end
if category_id
category_ids = [category_id]
@@ -598,7 +602,7 @@ class Search
)
SQL
- # a bit yucky but we got to add the term back in
+ # a bit yucky but we got to add the term back in
elsif match.to_s.length >= min_search_term_length
posts.where <<~SQL
posts.id IN (
@@ -611,34 +615,48 @@ class Search
end
advanced_filter(/^group:(.+)$/i) do |posts, match|
- group_id = Group
- .visible_groups(@guardian.user)
- .members_visible_groups(@guardian.user)
- .where('name ilike ? OR (id = ? AND id > 0)', match, match.to_i).pluck_first(:id)
+ group_id =
+ Group
+ .visible_groups(@guardian.user)
+ .members_visible_groups(@guardian.user)
+ .where("name ilike ? OR (id = ? AND id > 0)", match, match.to_i)
+ .pluck_first(:id)
if group_id
- posts.where("posts.user_id IN (select gu.user_id from group_users gu where gu.group_id = ?)", group_id)
+ posts.where(
+ "posts.user_id IN (select gu.user_id from group_users gu where gu.group_id = ?)",
+ group_id,
+ )
else
posts.where("1 = 0")
end
end
advanced_filter(/^group_messages:(.+)$/i) do |posts, match|
- group_id = Group
- .visible_groups(@guardian.user)
- .members_visible_groups(@guardian.user)
- .where(has_messages: true)
- .where('name ilike ? OR (id = ? AND id > 0)', match, match.to_i).pluck_first(:id)
+ group_id =
+ Group
+ .visible_groups(@guardian.user)
+ .members_visible_groups(@guardian.user)
+ .where(has_messages: true)
+ .where("name ilike ? OR (id = ? AND id > 0)", match, match.to_i)
+ .pluck_first(:id)
if group_id
- posts.where('posts.topic_id IN (SELECT topic_id FROM topic_allowed_groups WHERE group_id = ?)', group_id)
+ posts.where(
+ "posts.topic_id IN (SELECT topic_id FROM topic_allowed_groups WHERE group_id = ?)",
+ group_id,
+ )
else
posts.where("1 = 0")
end
end
advanced_filter(/^user:(.+)$/i) do |posts, match|
- user_id = User.where(staged: false).where('username_lower = ? OR id = ?', match.downcase, match.to_i).pluck_first(:id)
+ user_id =
+ User
+ .where(staged: false)
+ .where("username_lower = ? OR id = ?", match.downcase, match.to_i)
+ .pluck_first(:id)
if user_id
posts.where("posts.user_id = ?", user_id)
else
@@ -651,9 +669,7 @@ class Search
user_id = User.not_staged.where(username_lower: username).pluck_first(:id)
- if !user_id && username == "me"
- user_id = @guardian.user&.id
- end
+ user_id = @guardian.user&.id if !user_id && username == "me"
if user_id
posts.where("posts.user_id = ?", user_id)
@@ -688,7 +704,8 @@ class Search
advanced_filter(/^filetypes?:([a-zA-Z0-9,\-_]+)$/i) do |posts, match|
file_extensions = match.split(",").map(&:downcase)
- posts.where("posts.id IN (
+ posts.where(
+ "posts.id IN (
SELECT post_id
FROM topic_links
WHERE extension IN (:file_extensions)
@@ -699,7 +716,9 @@ class Search
FROM uploads
JOIN upload_references ON upload_references.target_type = 'Post' AND upload_references.upload_id = uploads.id
WHERE lower(uploads.extension) IN (:file_extensions)
- )", file_extensions: file_extensions)
+ )",
+ file_extensions: file_extensions,
+ )
end
advanced_filter(/^min_views:(\d+)$/i) do |posts, match|
@@ -717,93 +736,105 @@ class Search
match.downcase!
modifier = positive ? "" : "NOT"
- if match.include?('+')
- tags = match.split('+')
+ if match.include?("+")
+ tags = match.split("+")
- posts.where("topics.id #{modifier} IN (
+ posts.where(
+ "topics.id #{modifier} IN (
SELECT tt.topic_id
FROM topic_tags tt, tags
WHERE tt.tag_id = tags.id
GROUP BY tt.topic_id
- HAVING to_tsvector(#{default_ts_config}, #{Search.wrap_unaccent("array_to_string(array_agg(lower(tags.name)), ' ')")}) @@ to_tsquery(#{default_ts_config}, #{Search.wrap_unaccent('?')})
- )", tags.join('&'))
+ HAVING to_tsvector(#{default_ts_config}, #{Search.wrap_unaccent("array_to_string(array_agg(lower(tags.name)), ' ')")}) @@ to_tsquery(#{default_ts_config}, #{Search.wrap_unaccent("?")})
+ )",
+ tags.join("&"),
+ )
else
tags = match.split(",")
- posts.where("topics.id #{modifier} IN (
+ posts.where(
+ "topics.id #{modifier} IN (
SELECT DISTINCT(tt.topic_id)
FROM topic_tags tt, tags
WHERE tt.tag_id = tags.id AND lower(tags.name) IN (?)
- )", tags)
+ )",
+ tags,
+ )
end
end
def process_advanced_search!(term)
- term.to_s.scan(/(([^" \t\n\x0B\f\r]+)?(("[^"]+")?))/).to_a.map do |(word, _)|
- next if word.blank?
-
- found = false
-
- Search.advanced_filters.each do |matcher, block|
- cleaned = word.gsub(/["']/, "")
- if cleaned =~ matcher
- (@filters ||= []) << [block, $1]
- found = true
+ term
+ .to_s
+ .scan(/(([^" \t\n\x0B\f\r]+)?(("[^"]+")?))/)
+ .to_a
+ .map do |(word, _)|
+ next if word.blank?
+
+ found = false
+
+ Search.advanced_filters.each do |matcher, block|
+ cleaned = word.gsub(/["']/, "")
+ if cleaned =~ matcher
+ (@filters ||= []) << [block, $1]
+ found = true
+ end
end
- end
- if word == 'l'
- @order = :latest
- nil
- elsif word =~ /^order:\w+$/i
- @order = word.downcase.gsub('order:', '').to_sym
- nil
- elsif word =~ /^in:title$/i || word == 't'
- @in_title = true
- nil
- elsif word =~ /^topic:(\d+)$/i
- topic_id = $1.to_i
- if topic_id > 1
- topic = Topic.find_by(id: topic_id)
- if @guardian.can_see?(topic)
- @search_context = topic
+ if word == "l"
+ @order = :latest
+ nil
+ elsif word =~ /^order:\w+$/i
+ @order = word.downcase.gsub("order:", "").to_sym
+ nil
+ elsif word =~ /^in:title$/i || word == "t"
+ @in_title = true
+ nil
+ elsif word =~ /^topic:(\d+)$/i
+ topic_id = $1.to_i
+ if topic_id > 1
+ topic = Topic.find_by(id: topic_id)
+ @search_context = topic if @guardian.can_see?(topic)
end
- end
- nil
- elsif word =~ /^in:all$/i
- @search_all_topics = true
- nil
- elsif word =~ /^in:personal$/i
- @search_pms = true
- nil
- elsif word =~ /^in:messages$/i
- @search_pms = true
- nil
- elsif word =~ /^in:personal-direct$/i
- @search_pms = true
- nil
- elsif word =~ /^in:all-pms$/i
- @search_all_pms = true
- nil
- elsif word =~ /^group_messages:(.+)$/i
- @search_pms = true
- nil
- elsif word =~ /^personal_messages:(.+)$/i
- if user = User.find_by_username($1)
+ nil
+ elsif word =~ /^in:all$/i
+ @search_all_topics = true
+ nil
+ elsif word =~ /^in:personal$/i
@search_pms = true
- @search_context = user
- end
+ nil
+ elsif word =~ /^in:messages$/i
+ @search_pms = true
+ nil
+ elsif word =~ /^in:personal-direct$/i
+ @search_pms = true
+ nil
+ elsif word =~ /^in:all-pms$/i
+ @search_all_pms = true
+ nil
+ elsif word =~ /^group_messages:(.+)$/i
+ @search_pms = true
+ nil
+ elsif word =~ /^personal_messages:(.+)$/i
+ if user = User.find_by_username($1)
+ @search_pms = true
+ @search_context = user
+ end
- nil
- else
- found ? nil : word
+ nil
+ else
+ found ? nil : word
+ end
end
- end.compact.join(' ')
+ .compact
+ .join(" ")
end
def find_grouped_results
if @results.type_filter.present?
- raise Discourse::InvalidAccess.new("invalid type filter") unless Search.facets.include?(@results.type_filter)
+ unless Search.facets.include?(@results.type_filter)
+ raise Discourse::InvalidAccess.new("invalid type filter")
+ end
# calling protected methods
send("#{@results.type_filter}_search")
else
@@ -825,14 +856,20 @@ class Search
# If we're searching for a single topic
def single_topic(id)
if @opts[:restrict_to_archetype].present?
- archetype = @opts[:restrict_to_archetype] == Archetype.default ? Archetype.default : Archetype.private_message
+ archetype =
+ (
+ if @opts[:restrict_to_archetype] == Archetype.default
+ Archetype.default
+ else
+ Archetype.private_message
+ end
+ )
- post = posts_scope
- .joins(:topic)
- .find_by(
+ post =
+ posts_scope.joins(:topic).find_by(
"topics.id = :id AND topics.archetype = :archetype AND posts.post_number = 1",
id: id,
- archetype: archetype
+ archetype: archetype,
)
else
post = posts_scope.find_by(topic_id: id, post_number: 1)
@@ -856,50 +893,49 @@ class Search
# the issue while we figure out what is up in Rails
secure_category_ids
- categories = Category.includes(:category_search_data)
- .where("category_search_data.search_data @@ #{ts_query}")
- .references(:category_search_data)
- .order("topics_month DESC")
- .secured(@guardian)
- .limit(limit)
+ categories =
+ Category
+ .includes(:category_search_data)
+ .where("category_search_data.search_data @@ #{ts_query}")
+ .references(:category_search_data)
+ .order("topics_month DESC")
+ .secured(@guardian)
+ .limit(limit)
- categories.each do |category|
- @results.add(category)
- end
+ categories.each { |category| @results.add(category) }
end
def user_search
return if SiteSetting.hide_user_profiles_from_public && [email protected]
- users = User
- .includes(:user_search_data)
- .references(:user_search_data)
- .where(active: true)
- .where(staged: false)
- .where("user_search_data.search_data @@ #{ts_query("simple")}")
- .order("CASE WHEN username_lower = '#{@original_term.downcase}' THEN 0 ELSE 1 END")
- .order("last_posted_at DESC")
- .limit(limit)
+ users =
+ User
+ .includes(:user_search_data)
+ .references(:user_search_data)
+ .where(active: true)
+ .where(staged: false)
+ .where("user_search_data.search_data @@ #{ts_query("simple")}")
+ .order("CASE WHEN username_lower = '#{@original_term.downcase}' THEN 0 ELSE 1 END")
+ .order("last_posted_at DESC")
+ .limit(limit)
if !SiteSetting.enable_listing_suspended_users_on_search && [email protected]&.admin
users = users.where(suspended_at: nil)
end
- users_custom_data_query = DB.query(<<~SQL, user_ids: users.pluck(:id), term: "%#{@original_term.downcase}%")
+ users_custom_data_query =
+ DB.query(<<~SQL, user_ids: users.pluck(:id), term: "%#{@original_term.downcase}%")
SELECT user_custom_fields.user_id, user_fields.name, user_custom_fields.value FROM user_custom_fields
INNER JOIN user_fields ON user_fields.id = REPLACE(user_custom_fields.name, 'user_field_', '')::INTEGER AND user_fields.searchable IS TRUE
WHERE user_id IN (:user_ids)
AND user_custom_fields.name LIKE 'user_field_%'
AND user_custom_fields.value ILIKE :term
SQL
- users_custom_data = users_custom_data_query.reduce({}) do |acc, row|
- acc[row.user_id] =
- Array.wrap(acc[row.user_id]) << {
- name: row.name,
- value: row.value
- }
- acc
- end
+ users_custom_data =
+ users_custom_data_query.reduce({}) do |acc, row|
+ acc[row.user_id] = Array.wrap(acc[row.user_id]) << { name: row.name, value: row.value }
+ acc
+ end
users.each do |user|
user.custom_data = users_custom_data[user.id] || []
@@ -908,27 +944,28 @@ class Search
end
def groups_search
- groups = Group
- .visible_groups(@guardian.user, "name ASC", include_everyone: false)
- .where("name ILIKE :term OR full_name ILIKE :term", term: "%#{@term}%")
- .limit(limit)
+ groups =
+ Group
+ .visible_groups(@guardian.user, "name ASC", include_everyone: false)
+ .where("name ILIKE :term OR full_name ILIKE :term", term: "%#{@term}%")
+ .limit(limit)
groups.each { |group| @results.add(group) }
end
def tags_search
return unless SiteSetting.tagging_enabled
- tags = Tag.includes(:tag_search_data)
- .where("tag_search_data.search_data @@ #{ts_query}")
- .references(:tag_search_data)
- .order("name asc")
- .limit(limit)
+ tags =
+ Tag
+ .includes(:tag_search_data)
+ .where("tag_search_data.search_data @@ #{ts_query}")
+ .references(:tag_search_data)
+ .order("name asc")
+ .limit(limit)
hidden_tag_names = DiscourseTagging.hidden_tag_names(@guardian)
- tags.each do |tag|
- @results.add(tag) if !hidden_tag_names.include?(tag.name)
- end
+ tags.each { |tag| @results.add(tag) if !hidden_tag_names.include?(tag.name) }
end
def exclude_topics_search
@@ -943,8 +980,11 @@ class Search
PHRASE_MATCH_REGEXP_PATTERN = '"([^"]+)"'
def posts_query(limit, type_filter: nil, aggregate_search: false)
- posts = Post.where(post_type: Topic.visible_post_types(@guardian.user))
- .joins(:post_search_data, :topic)
+ posts =
+ Post.where(post_type: Topic.visible_post_types(@guardian.user)).joins(
+ :post_search_data,
+ :topic,
+ )
if type_filter != "private_messages"
posts = posts.joins("LEFT JOIN categories ON categories.id = topics.category_id")
@@ -954,62 +994,59 @@ class Search
posts = posts.where("topics.visible") unless is_topic_search
if type_filter == "private_messages" || (is_topic_search && @search_context.private_message?)
- posts = posts
- .where(
+ posts =
+ posts.where(
"topics.archetype = ? AND post_search_data.private_message",
- Archetype.private_message
+ Archetype.private_message,
)
- unless @guardian.is_admin?
- posts = posts.private_posts_for_user(@guardian.user)
- end
+ posts = posts.private_posts_for_user(@guardian.user) unless @guardian.is_admin?
elsif type_filter == "all_topics"
- private_posts = posts
- .where(
+ private_posts =
+ posts.where(
"topics.archetype = ? AND post_search_data.private_message",
- Archetype.private_message
- )
- .private_posts_for_user(@guardian.user)
+ Archetype.private_message,
+ ).private_posts_for_user(@guardian.user)
- posts = posts
- .where(
+ posts =
+ posts.where(
"topics.archetype <> ? AND NOT post_search_data.private_message",
- Archetype.private_message
- )
- .or(private_posts)
+ Archetype.private_message,
+ ).or(private_posts)
else
- posts = posts.where(
- "topics.archetype <> ? AND NOT post_search_data.private_message",
- Archetype.private_message
- )
+ posts =
+ posts.where(
+ "topics.archetype <> ? AND NOT post_search_data.private_message",
+ Archetype.private_message,
+ )
end
if @term.present?
if is_topic_search
-
term_without_quote = @term
- if @term =~ /"(.+)"/
- term_without_quote = $1
- end
+ term_without_quote = $1 if @term =~ /"(.+)"/
- if @term =~ /'(.+)'/
- term_without_quote = $1
- end
+ term_without_quote = $1 if @term =~ /'(.+)'/
- posts = posts.joins('JOIN users u ON u.id = posts.user_id')
- posts = posts.where("posts.raw || ' ' || u.username || ' ' || COALESCE(u.name, '') ilike ?", "%#{term_without_quote}%")
+ posts = posts.joins("JOIN users u ON u.id = posts.user_id")
+ posts =
+ posts.where(
+ "posts.raw || ' ' || u.username || ' ' || COALESCE(u.name, '') ilike ?",
+ "%#{term_without_quote}%",
+ )
else
# A is for title
# B is for category
# C is for tags
# D is for cooked
- weights = @in_title ? 'A' : (SiteSetting.tagging_enabled ? 'ABCD' : 'ABD')
+ weights = @in_title ? "A" : (SiteSetting.tagging_enabled ? "ABCD" : "ABD")
posts = posts.where(post_number: 1) if @in_title
posts = posts.where("post_search_data.search_data @@ #{ts_query(weight_filter: weights)}")
exact_terms = @term.scan(Regexp.new(PHRASE_MATCH_REGEXP_PATTERN)).flatten
exact_terms.each do |exact|
- posts = posts.where("posts.raw ilike :exact OR topics.title ilike :exact", exact: "%#{exact}%")
+ posts =
+ posts.where("posts.raw ilike :exact OR topics.title ilike :exact", exact: "%#{exact}%")
end
end
end
@@ -1036,19 +1073,22 @@ class Search
posts.where("posts.user_id = #{@search_context.id}")
end
elsif @search_context.is_a?(Category)
- category_ids = Category
- .where(parent_category_id: @search_context.id)
- .pluck(:id)
- .push(@search_context.id)
+ category_ids =
+ Category
+ .where(parent_category_id: @search_context.id)
+ .pluck(:id)
+ .push(@search_context.id)
posts.where("topics.category_id in (?)", category_ids)
elsif is_topic_search
- posts.where("topics.id = ?", @search_context.id)
- .order("posts.post_number #{@order == :latest ? "DESC" : ""}")
+ posts.where("topics.id = ?", @search_context.id).order(
+ "posts.post_number #{@order == :latest ? "DESC" : ""}",
+ )
elsif @search_context.is_a?(Tag)
- posts = posts
- .joins("LEFT JOIN topic_tags ON topic_tags.topic_id = topics.id")
- .joins("LEFT JOIN tags ON tags.id = topic_tags.tag_id")
+ posts =
+ posts.joins("LEFT JOIN topic_tags ON topic_tags.topic_id = topics.id").joins(
+ "LEFT JOIN tags ON tags.id = topic_tags.tag_id",
+ )
posts.where("tags.id = ?", @search_context.id)
end
else
@@ -1084,7 +1124,7 @@ class Search
rank = <<~SQL
TS_RANK_CD(
post_search_data.search_data,
- #{@term.blank? ? '' : ts_query(weight_filter: weights)},
+ #{@term.blank? ? "" : ts_query(weight_filter: weights)},
#{SiteSetting.search_ranking_normalization}|32
)
SQL
@@ -1139,9 +1179,14 @@ class Search
if type_filter != "private_messages"
posts =
if secure_category_ids.present?
- posts.where("(categories.id IS NULL) OR (NOT categories.read_restricted) OR (categories.id IN (?))", secure_category_ids).references(:categories)
+ posts.where(
+ "(categories.id IS NULL) OR (NOT categories.read_restricted) OR (categories.id IN (?))",
+ secure_category_ids,
+ ).references(:categories)
else
- posts.where("(categories.id IS NULL) OR (NOT categories.read_restricted)").references(:categories)
+ posts.where("(categories.id IS NULL) OR (NOT categories.read_restricted)").references(
+ :categories,
+ )
end
end
@@ -1169,10 +1214,7 @@ class Search
end
def self.ts_query(term:, ts_config: nil, joiner: nil, weight_filter: nil)
- to_tsquery(
- ts_config: ts_config,
- term: set_tsquery_weight_filter(term, weight_filter),
- )
+ to_tsquery(ts_config: ts_config, term: set_tsquery_weight_filter(term, weight_filter))
end
def self.to_tsquery(ts_config: nil, term:, joiner: nil)
@@ -1197,8 +1239,9 @@ class Search
def ts_query(ts_config = nil, weight_filter: nil)
@ts_query_cache ||= {}
- @ts_query_cache["#{ts_config || default_ts_config} #{@term} #{weight_filter}"] ||=
- Search.ts_query(term: @term, ts_config: ts_config, weight_filter: weight_filter)
+ @ts_query_cache[
+ "#{ts_config || default_ts_config} #{@term} #{weight_filter}"
+ ] ||= Search.ts_query(term: @term, ts_config: ts_config, weight_filter: weight_filter)
end
def wrap_rows(query)
@@ -1206,13 +1249,11 @@ class Search
end
def aggregate_post_sql(opts)
- default_opts = {
- type_filter: opts[:type_filter]
- }
+ default_opts = { type_filter: opts[:type_filter] }
min_id =
if SiteSetting.search_recent_regular_posts_offset_post_id > 0
- if %w{all_topics private_message}.include?(opts[:type_filter])
+ if %w[all_topics private_message].include?(opts[:type_filter])
0
else
SiteSetting.search_recent_regular_posts_offset_post_id
@@ -1228,12 +1269,12 @@ class Search
query =
if @order == :likes
# likes are a pain to aggregate so skip
- posts_query(limit, type_filter: opts[:type_filter])
- .select('topics.id', "posts.post_number")
+ posts_query(limit, type_filter: opts[:type_filter]).select("topics.id", "posts.post_number")
else
- posts_query(limit, aggregate_search: true, type_filter: opts[:type_filter])
- .select('topics.id', "#{min_or_max}(posts.post_number) post_number")
- .group('topics.id')
+ posts_query(limit, aggregate_search: true, type_filter: opts[:type_filter]).select(
+ "topics.id",
+ "#{min_or_max}(posts.post_number) post_number",
+ ).group("topics.id")
end
if min_id > 0
@@ -1250,9 +1291,9 @@ class Search
def aggregate_posts(post_sql)
return [] unless post_sql
- posts_scope(posts_eager_loads(Post))
- .joins("JOIN (#{post_sql}) x ON x.id = posts.topic_id AND x.post_number = posts.post_number")
- .order('row_number')
+ posts_scope(posts_eager_loads(Post)).joins(
+ "JOIN (#{post_sql}) x ON x.id = posts.topic_id AND x.post_number = posts.post_number",
+ ).order("row_number")
end
def aggregate_search(opts = {})
@@ -1265,9 +1306,7 @@ class Search
added += 1
end
- if added < limit
- aggregate_posts(post_sql[:remaining]).each { |p| @results.add(p) }
- end
+ aggregate_posts(post_sql[:remaining]).each { |p| @results.add(p) } if added < limit
end
def private_messages_search
@@ -1282,12 +1321,13 @@ class Search
def topic_search
if @search_context.is_a?(Topic)
- posts = posts_scope(posts_eager_loads(posts_query(limit)))
- .where('posts.topic_id = ?', @search_context.id)
+ posts =
+ posts_scope(posts_eager_loads(posts_query(limit))).where(
+ "posts.topic_id = ?",
+ @search_context.id,
+ )
- posts.each do |post|
- @results.add(post)
- end
+ posts.each { |post| @results.add(post) }
else
aggregate_search
end
@@ -1297,12 +1337,12 @@ class Search
query = query.includes(:user, :post_search_data)
topic_eager_loads = [:category]
- if SiteSetting.tagging_enabled
- topic_eager_loads << :tags
- end
+ topic_eager_loads << :tags if SiteSetting.tagging_enabled
Search.custom_topic_eager_loads.each do |custom_loads|
- topic_eager_loads.concat(custom_loads.is_a?(Array) ? custom_loads : custom_loads.call(search_pms: @search_pms).to_a)
+ topic_eager_loads.concat(
+ custom_loads.is_a?(Array) ? custom_loads : custom_loads.call(search_pms: @search_pms).to_a,
+ )
end
query.includes(topic: topic_eager_loads)
@@ -1343,7 +1383,7 @@ class Search
) AS headline",
"LEFT(pd.raw_data, 50) AS leading_raw_data",
"RIGHT(pd.raw_data, 50) AS trailing_raw_data",
- default_scope.arel.projections
+ default_scope.arel.projections,
)
else
default_scope
@@ -1351,21 +1391,19 @@ class Search
end
def log_query?(readonly_mode)
- SiteSetting.log_search_queries? &&
- @opts[:search_type].present? &&
- !readonly_mode &&
- @opts[:type_filter] != "exclude_topics"
+ SiteSetting.log_search_queries? && @opts[:search_type].present? && !readonly_mode &&
+ @opts[:type_filter] != "exclude_topics"
end
def min_search_term_length
return @opts[:min_search_term_length] if @opts[:min_search_term_length]
if SiteSetting.search_tokenize_chinese
- return SiteSetting.defaults.get('min_search_term_length', 'zh_CN')
+ return SiteSetting.defaults.get("min_search_term_length", "zh_CN")
end
if SiteSetting.search_tokenize_japanese
- return SiteSetting.defaults.get('min_search_term_length', 'ja')
+ return SiteSetting.defaults.get("min_search_term_length", "ja")
end
SiteSetting.min_search_term_length
diff --git a/lib/search/grouped_search_results.rb b/lib/search/grouped_search_results.rb
index a1c7cfcbe57..f3470963eb5 100644
--- a/lib/search/grouped_search_results.rb
+++ b/lib/search/grouped_search_results.rb
@@ -1,9 +1,8 @@
# frozen_string_literal: true
-require 'sanitize'
+require "sanitize"
class Search
-
class GroupedSearchResults
include ActiveModel::Serialization
@@ -24,14 +23,21 @@ class Search
:term,
:search_context,
:more_full_page_results,
- :error
+ :error,
)
attr_accessor :search_log_id
BLURB_LENGTH = 200
- def initialize(type_filter:, term:, search_context:, blurb_length: nil, blurb_term: nil, is_header_search: false)
+ def initialize(
+ type_filter:,
+ term:,
+ search_context:,
+ blurb_length: nil,
+ blurb_term: nil,
+ is_header_search: false
+ )
@type_filter = type_filter
@term = term
@blurb_term = blurb_term || term
@@ -58,20 +64,19 @@ class Search
end
end
- OMISSION = '...'
- SCRUB_HEADLINE_REGEXP = /<span(?: \w+="[^"]+")* class="#{Search::HIGHLIGHT_CSS_CLASS}"(?: \w+="[^"]+")*>([^<]*)<\/span>/
+ OMISSION = "..."
+ SCRUB_HEADLINE_REGEXP =
+ %r{<span(?: \w+="[^"]+")* class="#{Search::HIGHLIGHT_CSS_CLASS}"(?: \w+="[^"]+")*>([^<]*)</span>}
def blurb(post)
- opts = {
- term: @blurb_term,
- blurb_length: @blurb_length
- }
+ opts = { term: @blurb_term, blurb_length: @blurb_length }
- if post.post_search_data.version > SearchIndexer::MIN_POST_REINDEX_VERSION && !Search.segment_chinese? && !Search.segment_japanese?
+ if post.post_search_data.version > SearchIndexer::MIN_POST_REINDEX_VERSION &&
+ !Search.segment_chinese? && !Search.segment_japanese?
if SiteSetting.use_pg_headlines_for_excerpt
scrubbed_headline = post.headline.gsub(SCRUB_HEADLINE_REGEXP, '\1')
- prefix_omission = scrubbed_headline.start_with?(post.leading_raw_data) ? '' : OMISSION
- postfix_omission = scrubbed_headline.end_with?(post.trailing_raw_data) ? '' : OMISSION
+ prefix_omission = scrubbed_headline.start_with?(post.leading_raw_data) ? "" : OMISSION
+ postfix_omission = scrubbed_headline.end_with?(post.trailing_raw_data) ? "" : OMISSION
return "#{prefix_omission}#{post.headline}#{postfix_omission}"
else
opts[:cooked] = post.post_search_data.raw_data
@@ -117,18 +122,13 @@ class Search
end
if term
- if term =~ Regexp.new(Search::PHRASE_MATCH_REGEXP_PATTERN)
- term = Regexp.last_match[1]
- end
+ term = Regexp.last_match[1] if term =~ Regexp.new(Search::PHRASE_MATCH_REGEXP_PATTERN)
- blurb = TextHelper.excerpt(cooked, term,
- radius: blurb_length / 2
- )
+ blurb = TextHelper.excerpt(cooked, term, radius: blurb_length / 2)
end
blurb = TextHelper.truncate(cooked, length: blurb_length) if blurb.blank?
Sanitize.clean(blurb)
end
end
-
end
diff --git a/lib/second_factor/actions/discourse_connect_provider.rb b/lib/second_factor/actions/discourse_connect_provider.rb
index b300f928554..bee50463c35 100644
--- a/lib/second_factor/actions/discourse_connect_provider.rb
+++ b/lib/second_factor/actions/discourse_connect_provider.rb
@@ -28,13 +28,16 @@ module SecondFactor::Actions
sso = get_sso(pl)
hostname = URI(sso.return_sso_url).hostname
{
- callback_params: { payload: pl },
+ callback_params: {
+ payload: pl,
+ },
callback_path: session_sso_provider_path,
callback_method: "GET",
- description: I18n.t(
- "second_factor_auth.actions.discourse_connect_provider.description",
- hostname: hostname,
- )
+ description:
+ I18n.t(
+ "second_factor_auth.actions.discourse_connect_provider.description",
+ hostname: hostname,
+ ),
}
end
@@ -63,21 +66,25 @@ module SecondFactor::Actions
sso.groups = current_user.groups.pluck(:name).join(",")
if current_user.uploaded_avatar.present?
- base_url = Discourse.store.external? ? "#{Discourse.store.absolute_base_url}/" : Discourse.base_url
- avatar_url = "#{base_url}#{Discourse.store.get_path_for_upload(current_user.uploaded_avatar)}"
+ base_url =
+ Discourse.store.external? ? "#{Discourse.store.absolute_base_url}/" : Discourse.base_url
+ avatar_url =
+ "#{base_url}#{Discourse.store.get_path_for_upload(current_user.uploaded_avatar)}"
sso.avatar_url = UrlHelper.absolute Discourse.store.cdn_url(avatar_url)
end
if current_user.user_profile.profile_background_upload.present?
- sso.profile_background_url = UrlHelper.absolute(GlobalPath.upload_cdn_path(
- current_user.user_profile.profile_background_upload.url
- ))
+ sso.profile_background_url =
+ UrlHelper.absolute(
+ GlobalPath.upload_cdn_path(current_user.user_profile.profile_background_upload.url),
+ )
end
if current_user.user_profile.card_background_upload.present?
- sso.card_background_url = UrlHelper.absolute(GlobalPath.upload_cdn_path(
- current_user.user_profile.card_background_upload.url
- ))
+ sso.card_background_url =
+ UrlHelper.absolute(
+ GlobalPath.upload_cdn_path(current_user.user_profile.card_background_upload.url),
+ )
end
end
@@ -87,7 +94,9 @@ module SecondFactor::Actions
sso
rescue ::DiscourseConnectProvider::ParseError => e
if SiteSetting.verbose_discourse_connect_logging
- Rails.logger.warn("Verbose SSO log: Signature parse error\n\n#{e.message}\n\n#{sso&.diagnostics}")
+ Rails.logger.warn(
+ "Verbose SSO log: Signature parse error\n\n#{e.message}\n\n#{sso&.diagnostics}",
+ )
end
raise
end
diff --git a/lib/second_factor/actions/grant_admin.rb b/lib/second_factor/actions/grant_admin.rb
index 8b581da934c..5e8dc4b0360 100644
--- a/lib/second_factor/actions/grant_admin.rb
+++ b/lib/second_factor/actions/grant_admin.rb
@@ -10,14 +10,14 @@ module SecondFactor::Actions
def second_factor_auth_required!(params)
user = find_user(params[:user_id])
- description = I18n.t(
- "second_factor_auth.actions.grant_admin.description",
- username: "@#{user.username}"
- )
+ description =
+ I18n.t("second_factor_auth.actions.grant_admin.description", username: "@#{user.username}")
{
- callback_params: { user_id: user.id },
+ callback_params: {
+ user_id: user.id,
+ },
redirect_url: admin_user_show_path(id: user.id, username: user.username),
- description: description
+ description: description,
}
end
diff --git a/lib/second_factor/auth_manager.rb b/lib/second_factor/auth_manager.rb
index 163ae771259..a9ba5eec338 100644
--- a/lib/second_factor/auth_manager.rb
+++ b/lib/second_factor/auth_manager.rb
@@ -124,25 +124,22 @@ class SecondFactor::AuthManager
challenge_json = secure_session["current_second_factor_auth_challenge"]
if challenge_json.blank?
raise SecondFactor::BadChallenge.new(
- "second_factor_auth.challenge_not_found",
- status_code: 404
- )
+ "second_factor_auth.challenge_not_found",
+ status_code: 404,
+ )
end
challenge = JSON.parse(challenge_json).deep_symbolize_keys
if challenge[:nonce] != nonce
raise SecondFactor::BadChallenge.new(
- "second_factor_auth.challenge_not_found",
- status_code: 404
- )
+ "second_factor_auth.challenge_not_found",
+ status_code: 404,
+ )
end
generated_at = challenge[:generated_at]
if generated_at < MAX_CHALLENGE_AGE.ago.to_i
- raise SecondFactor::BadChallenge.new(
- "second_factor_auth.challenge_expired",
- status_code: 401
- )
+ raise SecondFactor::BadChallenge.new("second_factor_auth.challenge_expired", status_code: 401)
end
challenge
end
@@ -151,10 +148,8 @@ class SecondFactor::AuthManager
@guardian = guardian
@current_user = guardian.user
@action = action
- @allowed_methods = Set.new([
- UserSecondFactor.methods[:totp],
- UserSecondFactor.methods[:security_key],
- ]).freeze
+ @allowed_methods =
+ Set.new([UserSecondFactor.methods[:totp], UserSecondFactor.methods[:security_key]]).freeze
end
def allow_backup_codes!
@@ -189,14 +184,10 @@ class SecondFactor::AuthManager
callback_path: config[:callback_path] || request.path,
callback_params: callback_params,
allowed_methods: allowed_methods.to_a,
- generated_at: Time.zone.now.to_i
+ generated_at: Time.zone.now.to_i,
}
- if config[:description]
- challenge[:description] = config[:description]
- end
- if config[:redirect_url].present?
- challenge[:redirect_url] = config[:redirect_url]
- end
+ challenge[:description] = config[:description] if config[:description]
+ challenge[:redirect_url] = config[:redirect_url] if config[:redirect_url].present?
secure_session["current_second_factor_auth_challenge"] = challenge.to_json
nonce
end
@@ -205,9 +196,9 @@ class SecondFactor::AuthManager
challenge = self.class.find_second_factor_challenge(nonce, secure_session)
if !challenge[:successful]
raise SecondFactor::BadChallenge.new(
- "second_factor_auth.challenge_not_completed",
- status_code: 401
- )
+ "second_factor_auth.challenge_not_completed",
+ status_code: 401,
+ )
end
secure_session["current_second_factor_auth_challenge"] = nil
diff --git a/lib/second_factor/auth_manager_result.rb b/lib/second_factor/auth_manager_result.rb
index 2b830b36c79..5d26d8028f6 100644
--- a/lib/second_factor/auth_manager_result.rb
+++ b/lib/second_factor/auth_manager_result.rb
@@ -12,7 +12,9 @@ class SecondFactor::AuthManagerResult
def initialize(status, data)
if !STATUSES.key?(status)
- raise ArgumentError.new("#{status.inspect} is not a valid status. Allowed statuses: #{STATUSES.inspect}")
+ raise ArgumentError.new(
+ "#{status.inspect} is not a valid status. Allowed statuses: #{STATUSES.inspect}",
+ )
end
@status_id = STATUSES[status]
@data = data
diff --git a/lib/seed_data/categories.rb b/lib/seed_data/categories.rb
index 0f7cef8425a..575d84b3955 100644
--- a/lib/seed_data/categories.rb
+++ b/lib/seed_data/categories.rb
@@ -28,16 +28,14 @@ module SeedData
def reseed_options
I18n.with_locale(@locale) do
- categories.map do |params|
- category = find_category(params[:site_setting_name])
- next unless category
-
- {
- id: params[:site_setting_name],
- name: category.name,
- selected: unchanged?(category)
- }
- end.compact
+ categories
+ .map do |params|
+ category = find_category(params[:site_setting_name])
+ next unless category
+
+ { id: params[:site_setting_name], name: category.name, selected: unchanged?(category) }
+ end
+ .compact
end
end
@@ -46,50 +44,58 @@ module SeedData
def categories(site_setting_names = nil)
categories = [
{
- site_setting_name: 'uncategorized_category_id',
- name: I18n.t('uncategorized_category_name'),
+ site_setting_name: "uncategorized_category_id",
+ name: I18n.t("uncategorized_category_name"),
description: nil,
position: 0,
- color: '0088CC',
- text_color: 'FFFFFF',
- permissions: { everyone: :full },
+ color: "0088CC",
+ text_color: "FFFFFF",
+ permissions: {
+ everyone: :full,
+ },
force_permissions: true,
- force_existence: true
+ force_existence: true,
},
{
- site_setting_name: 'meta_category_id',
- name: I18n.t('meta_category_name'),
- description: I18n.t('meta_category_description'),
+ site_setting_name: "meta_category_id",
+ name: I18n.t("meta_category_name"),
+ description: I18n.t("meta_category_description"),
position: 1,
- color: '808281',
- text_color: 'FFFFFF',
- permissions: { everyone: :full },
+ color: "808281",
+ text_color: "FFFFFF",
+ permissions: {
+ everyone: :full,
+ },
force_permissions: true,
- sidebar: true
+ sidebar: true,
},
{
- site_setting_name: 'staff_category_id',
- name: I18n.t('staff_category_name'),
- description: I18n.t('staff_category_description'),
+ site_setting_name: "staff_category_id",
+ name: I18n.t("staff_category_name"),
+ description: I18n.t("staff_category_description"),
position: 2,
- color: 'E45735',
- text_color: 'FFFFFF',
- permissions: { staff: :full },
+ color: "E45735",
+ text_color: "FFFFFF",
+ permissions: {
+ staff: :full,
+ },
force_permissions: true,
- sidebar: true
+ sidebar: true,
},
{
- site_setting_name: 'general_category_id',
- name: I18n.t('general_category_name'),
- description: I18n.t('general_category_description'),
+ site_setting_name: "general_category_id",
+ name: I18n.t("general_category_name"),
+ description: I18n.t("general_category_description"),
position: 3,
- color: '25AAE2',
- text_color: 'FFFFFF',
- permissions: { everyone: :full },
+ color: "25AAE2",
+ text_color: "FFFFFF",
+ permissions: {
+ everyone: :full,
+ },
force_permissions: true,
sidebar: true,
- default_composer_category: true
- }
+ default_composer_category: true,
+ },
]
if site_setting_names
@@ -99,19 +105,31 @@ module SeedData
categories
end
- def create_category(site_setting_name:, name:, description:, position:, color:, text_color:,
- permissions:, force_permissions:, force_existence: false, sidebar: false, default_composer_category: false)
+ def create_category(
+ site_setting_name:,
+ name:,
+ description:,
+ position:,
+ color:,
+ text_color:,
+ permissions:,
+ force_permissions:,
+ force_existence: false,
+ sidebar: false,
+ default_composer_category: false
+ )
category_id = SiteSetting.get(site_setting_name)
if should_create_category?(category_id, force_existence)
- category = Category.new(
- name: unused_category_name(category_id, name),
- description: description,
- user_id: Discourse::SYSTEM_USER_ID,
- position: position,
- color: color,
- text_color: text_color
- )
+ category =
+ Category.new(
+ name: unused_category_name(category_id, name),
+ description: description,
+ user_id: Discourse::SYSTEM_USER_ID,
+ position: position,
+ color: color,
+ text_color: text_color,
+ )
category.skip_category_definition = true if description.blank?
category.set_permissions(permissions)
@@ -120,14 +138,12 @@ module SeedData
SiteSetting.set(site_setting_name, category.id)
if sidebar
- sidebar_categories = SiteSetting.default_sidebar_categories.split('|')
+ sidebar_categories = SiteSetting.default_sidebar_categories.split("|")
sidebar_categories << category.id
- SiteSetting.set('default_sidebar_categories', sidebar_categories.join('|'))
+ SiteSetting.set("default_sidebar_categories", sidebar_categories.join("|"))
end
- if default_composer_category
- SiteSetting.set('default_composer_category', category.id)
- end
+ SiteSetting.set("default_composer_category", category.id) if default_composer_category
elsif category = Category.find_by(id: category_id)
if description.present? && (category.topic_id.blank? || !Topic.exists?(category.topic_id))
category.description = description
@@ -152,11 +168,12 @@ module SeedData
end
def unused_category_name(category_id, name)
- category_exists = Category.where(
- 'id <> :id AND LOWER(name) = :name',
- id: category_id,
- name: name.downcase
- ).exists?
+ category_exists =
+ Category.where(
+ "id <> :id AND LOWER(name) = :name",
+ id: category_id,
+ name: name.downcase,
+ ).exists?
category_exists ? "#{name}#{SecureRandom.hex}" : name
end
@@ -167,7 +184,7 @@ module SeedData
name = unused_category_name(category.id, name)
category.name = name
- category.slug = Slug.for(name, '')
+ category.slug = Slug.for(name, "")
category.save!
if description.present? && description_post = category&.topic&.first_post
diff --git a/lib/seed_data/topics.rb b/lib/seed_data/topics.rb
index 026ff98a18d..d98106579d9 100644
--- a/lib/seed_data/topics.rb
+++ b/lib/seed_data/topics.rb
@@ -12,9 +12,7 @@ module SeedData
def create(site_setting_names: nil, include_welcome_topics: true)
I18n.with_locale(@locale) do
- topics(site_setting_names, include_welcome_topics).each do |params|
- create_topic(**params)
- end
+ topics(site_setting_names, include_welcome_topics).each { |params| create_topic(**params) }
end
end
@@ -30,16 +28,14 @@ module SeedData
def reseed_options
I18n.with_locale(@locale) do
- topics.map do |params|
- post = find_post(params[:site_setting_name])
- next unless post
-
- {
- id: params[:site_setting_name],
- name: post.topic.title,
- selected: unchanged?(post)
- }
- end.compact
+ topics
+ .map do |params|
+ post = find_post(params[:site_setting_name])
+ next unless post
+
+ { id: params[:site_setting_name], name: post.topic.title, selected: unchanged?(post) }
+ end
+ .compact
end
end
@@ -51,58 +47,58 @@ module SeedData
topics = [
# Terms of Service
{
- site_setting_name: 'tos_topic_id',
- title: I18n.t('tos_topic.title'),
- raw: I18n.t('tos_topic.body',
- company_name: setting_value('company_name'),
- base_url: Discourse.base_url,
- contact_email: setting_value('contact_email'),
- governing_law: setting_value('governing_law'),
- city_for_disputes: setting_value('city_for_disputes')
- ),
+ site_setting_name: "tos_topic_id",
+ title: I18n.t("tos_topic.title"),
+ raw:
+ I18n.t(
+ "tos_topic.body",
+ company_name: setting_value("company_name"),
+ base_url: Discourse.base_url,
+ contact_email: setting_value("contact_email"),
+ governing_law: setting_value("governing_law"),
+ city_for_disputes: setting_value("city_for_disputes"),
+ ),
category: staff_category,
- static_first_reply: true
+ static_first_reply: true,
},
-
# FAQ/Guidelines
{
- site_setting_name: 'guidelines_topic_id',
- title: I18n.t('guidelines_topic.title'),
- raw: I18n.t('guidelines_topic.body', base_path: Discourse.base_path),
+ site_setting_name: "guidelines_topic_id",
+ title: I18n.t("guidelines_topic.title"),
+ raw: I18n.t("guidelines_topic.body", base_path: Discourse.base_path),
category: staff_category,
- static_first_reply: true
+ static_first_reply: true,
},
-
# Privacy Policy
{
- site_setting_name: 'privacy_topic_id',
- title: I18n.t('privacy_topic.title'),
- raw: I18n.t('privacy_topic.body'),
+ site_setting_name: "privacy_topic_id",
+ title: I18n.t("privacy_topic.title"),
+ raw: I18n.t("privacy_topic.body"),
category: staff_category,
- static_first_reply: true
- }
+ static_first_reply: true,
+ },
]
if include_welcome_topics
# Welcome Topic
if general_category = Category.find_by(id: SiteSetting.general_category_id)
topics << {
- site_setting_name: 'welcome_topic_id',
- title: I18n.t('discourse_welcome_topic.title'),
- raw: I18n.t('discourse_welcome_topic.body', base_path: Discourse.base_path),
+ site_setting_name: "welcome_topic_id",
+ title: I18n.t("discourse_welcome_topic.title"),
+ raw: I18n.t("discourse_welcome_topic.body", base_path: Discourse.base_path),
category: general_category,
- after_create: proc do |post|
- post.topic.update_pinned(true, true)
- end
+ after_create: proc { |post| post.topic.update_pinned(true, true) },
}
end
# Admin Quick Start Guide
topics << {
- site_setting_name: 'admin_quick_start_topic_id',
- title: DiscoursePluginRegistry.seed_data['admin_quick_start_title'] || I18n.t('admin_quick_start_title'),
+ site_setting_name: "admin_quick_start_topic_id",
+ title:
+ DiscoursePluginRegistry.seed_data["admin_quick_start_title"] ||
+ I18n.t("admin_quick_start_title"),
raw: admin_quick_start_raw,
- category: staff_category
+ category: staff_category,
}
end
@@ -113,18 +109,26 @@ module SeedData
topics
end
- def create_topic(site_setting_name:, title:, raw:, category: nil, static_first_reply: false, after_create: nil)
+ def create_topic(
+ site_setting_name:,
+ title:,
+ raw:,
+ category: nil,
+ static_first_reply: false,
+ after_create: nil
+ )
topic_id = SiteSetting.get(site_setting_name)
return if topic_id > 0 || Topic.find_by(id: topic_id)
- post = PostCreator.create!(
- Discourse.system_user,
- title: title,
- raw: raw,
- skip_jobs: true,
- skip_validations: true,
- category: category&.id
- )
+ post =
+ PostCreator.create!(
+ Discourse.system_user,
+ title: title,
+ raw: raw,
+ skip_jobs: true,
+ skip_validations: true,
+ category: category&.id,
+ )
if static_first_reply
PostCreator.create!(
@@ -132,7 +136,7 @@ module SeedData
raw: first_reply_raw(title),
skip_jobs: true,
skip_validations: true,
- topic_id: post.topic_id
+ topic_id: post.topic_id,
)
end
@@ -174,7 +178,7 @@ module SeedData
end
def first_reply_raw(topic_title)
- I18n.t('static_topic_first_reply', page_name: topic_title)
+ I18n.t("static_topic_first_reply", page_name: topic_title)
end
def admin_quick_start_raw
@@ -182,7 +186,7 @@ module SeedData
if !quick_start_filename || !File.exist?(quick_start_filename)
# TODO Make the quick start guide translatable
- quick_start_filename = File.join(Rails.root, 'docs', 'ADMIN-QUICK-START-GUIDE.md')
+ quick_start_filename = File.join(Rails.root, "docs", "ADMIN-QUICK-START-GUIDE.md")
end
File.read(quick_start_filename)
diff --git a/lib/shrink_uploaded_image.rb b/lib/shrink_uploaded_image.rb
index f6ef2354d47..d1a7f14f012 100644
--- a/lib/shrink_uploaded_image.rb
+++ b/lib/shrink_uploaded_image.rb
@@ -19,7 +19,13 @@ class ShrinkUploadedImage
return false
end
- posts = Post.unscoped.joins(:upload_references).where(upload_references: { upload_id: original_upload.id }).uniq.sort_by(&:created_at)
+ posts =
+ Post
+ .unscoped
+ .joins(:upload_references)
+ .where(upload_references: { upload_id: original_upload.id })
+ .uniq
+ .sort_by(&:created_at)
if posts.empty?
log "Upload not used in any posts"
@@ -53,7 +59,7 @@ class ShrinkUploadedImage
height: h,
thumbnail_width: ww,
thumbnail_height: hh,
- filesize: File.size(path)
+ filesize: File.size(path),
}
if upload.filesize >= upload.filesize_was
@@ -92,7 +98,7 @@ class ShrinkUploadedImage
elsif !post.topic || post.topic.trashed?
log "A deleted topic"
elsif post.cooked.include?(original_upload.sha1)
- if post.raw.include?("#{Discourse.base_url.sub(/^https?:\/\//i, "")}/t/")
+ if post.raw.include?("#{Discourse.base_url.sub(%r{^https?://}i, "")}/t/")
log "Updating a topic onebox"
else
log "Updating an external onebox"
@@ -135,7 +141,7 @@ class ShrinkUploadedImage
if existing_upload
begin
UploadReference
- .where(target_type: 'Post')
+ .where(target_type: "Post")
.where(upload_id: original_upload.id)
.update_all(upload_id: upload.id)
rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation
@@ -154,15 +160,11 @@ class ShrinkUploadedImage
post = current_post
end
- if post.raw_changed?
- post.update_columns(
- raw: post.raw,
- updated_at: Time.zone.now
- )
- end
+ post.update_columns(raw: post.raw, updated_at: Time.zone.now) if post.raw_changed?
if existing_upload
- post.post_hotlinked_media
+ post
+ .post_hotlinked_media
.where(upload_id: original_upload.id)
.update_all(upload_id: upload.id)
end
@@ -183,20 +185,34 @@ class ShrinkUploadedImage
private
def transform_post(post, upload_before, upload_after)
- post.raw.gsub!(/upload:\/\/#{upload_before.base62_sha1}(\.#{upload_before.extension})?/i, upload_after.short_url)
- post.raw.gsub!(Discourse.store.cdn_url(upload_before.url), Discourse.store.cdn_url(upload_after.url))
- post.raw.gsub!("#{Discourse.base_url}#{upload_before.short_path}", "#{Discourse.base_url}#{upload_after.short_path}")
+ post.raw.gsub!(
+ %r{upload://#{upload_before.base62_sha1}(\.#{upload_before.extension})?}i,
+ upload_after.short_url,
+ )
+ post.raw.gsub!(
+ Discourse.store.cdn_url(upload_before.url),
+ Discourse.store.cdn_url(upload_after.url),
+ )
+ post.raw.gsub!(
+ "#{Discourse.base_url}#{upload_before.short_path}",
+ "#{Discourse.base_url}#{upload_after.short_path}",
+ )
if SiteSetting.enable_s3_uploads
post.raw.gsub!(Discourse.store.url_for(upload_before), Discourse.store.url_for(upload_after))
path = SiteSetting.Upload.s3_upload_bucket.split("/", 2)[1]
- post.raw.gsub!(/<img src=\"https:\/\/.+?\/#{path}\/uploads\/default\/optimized\/.+?\/#{upload_before.sha1}_\d_(?<width>\d+)x(?<height>\d+).*?\" alt=\"(?<alt>.*?)\"\/?>/i) do
- "![#{$~[:alt]}|#{$~[:width]}x#{$~[:height]}](#{upload_after.short_url})"
- end
+ post
+ .raw
+ .gsub!(
+ %r{<img src=\"https://.+?/#{path}/uploads/default/optimized/.+?/#{upload_before.sha1}_\d_(?<width>\d+)x(?<height>\d+).*?\" alt=\"(?<alt>.*?)\"/?>}i,
+ ) { "![#{$~[:alt]}|#{$~[:width]}x#{$~[:height]}](#{upload_after.short_url})" }
end
- post.raw.gsub!(/!\[(.*?)\]\(\/uploads\/.+?\/#{upload_before.sha1}(\.#{upload_before.extension})?\)/i, "![\\1](#{upload_after.short_url})")
+ post.raw.gsub!(
+ %r{!\[(.*?)\]\(/uploads/.+?/#{upload_before.sha1}(\.#{upload_before.extension})?\)}i,
+ "![\\1](#{upload_after.short_url})",
+ )
end
def log(*args)
diff --git a/lib/sidekiq/pausable.rb b/lib/sidekiq/pausable.rb
index 4ec09192aa6..cb97d53a272 100644
--- a/lib/sidekiq/pausable.rb
+++ b/lib/sidekiq/pausable.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'thread'
+require "thread"
class SidekiqPauser
TTL = 60
@@ -27,9 +27,7 @@ class SidekiqPauser
stop_extend_lease_thread
end
- RailsMultisite::ConnectionManagement.each_connection do
- unpause! if paused?
- end
+ RailsMultisite::ConnectionManagement.each_connection { unpause! if paused? }
end
def paused_dbs
@@ -62,9 +60,7 @@ class SidekiqPauser
begin
t.wakeup
rescue ThreadError => e
- unless e.message =~ /killed thread/
- raise e
- end
+ raise e unless e.message =~ /killed thread/
end
sleep 0
@@ -76,25 +72,26 @@ class SidekiqPauser
@mutex.synchronize do
@dbs << RailsMultisite::ConnectionManagement.current_db
- @extend_lease_thread ||= Thread.new do
- while true do
- break if !@extend_lease_thread
-
- @mutex.synchronize do
- @dbs.each do |db|
- RailsMultisite::ConnectionManagement.with_connection(db) do
- if !Discourse.redis.expire(PAUSED_KEY, TTL)
- # if it was unpaused in another process we got to remove the
- # bad key
- @dbs.delete(db)
+ @extend_lease_thread ||=
+ Thread.new do
+ while true
+ break if !@extend_lease_thread
+
+ @mutex.synchronize do
+ @dbs.each do |db|
+ RailsMultisite::ConnectionManagement.with_connection(db) do
+ if !Discourse.redis.expire(PAUSED_KEY, TTL)
+ # if it was unpaused in another process we got to remove the
+ # bad key
+ @dbs.delete(db)
+ end
end
end
end
- end
- sleep(Rails.env.test? ? 0.01 : TTL / 2)
+ sleep(Rails.env.test? ? 0.01 : TTL / 2)
+ end
end
- end
end
end
end
@@ -125,14 +122,13 @@ end
# server middleware that will reschedule work whenever Sidekiq is paused
class Sidekiq::Pausable
-
def initialize(delay = 5.seconds)
@delay = delay
end
def call(worker, msg, queue)
if sidekiq_paused?(msg) && !(Jobs::RunHeartbeat === worker)
- worker.class.perform_in(@delay, *msg['args'])
+ worker.class.perform_in(@delay, *msg["args"])
else
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
result = yield
@@ -146,10 +142,7 @@ class Sidekiq::Pausable
def sidekiq_paused?(msg)
if site_id = msg["args"]&.first&.dig("current_site_id")
- RailsMultisite::ConnectionManagement.with_connection(site_id) do
- Sidekiq.paused?
- end
+ RailsMultisite::ConnectionManagement.with_connection(site_id) { Sidekiq.paused? }
end
end
-
end
diff --git a/lib/sidekiq_logster_reporter.rb b/lib/sidekiq_logster_reporter.rb
index 51fe14d21ac..2c37e970729 100644
--- a/lib/sidekiq_logster_reporter.rb
+++ b/lib/sidekiq_logster_reporter.rb
@@ -2,27 +2,24 @@
class SidekiqLogsterReporter
def call(ex, context = {})
-
return if Jobs::HandledExceptionWrapper === ex
Discourse.reset_active_record_cache_if_needed(ex)
# Pass context to Logster
fake_env = {}
- context.each do |key, value|
- Logster.add_to_env(fake_env, key, value)
- end
+ context.each { |key, value| Logster.add_to_env(fake_env, key, value) }
text = "Job exception: #{ex}\n"
- if ex.backtrace
- Logster.add_to_env(fake_env, :backtrace, ex.backtrace)
- end
+ Logster.add_to_env(fake_env, :backtrace, ex.backtrace) if ex.backtrace
Logster.add_to_env(fake_env, :current_hostname, Discourse.current_hostname)
Thread.current[Logster::Logger::LOGSTER_ENV] = fake_env
Logster.logger.error(text)
rescue => e
- Logster.logger.fatal("Failed to log exception #{ex} #{hash}\nReason: #{e.class} #{e}\n#{e.backtrace.join("\n")}")
+ Logster.logger.fatal(
+ "Failed to log exception #{ex} #{hash}\nReason: #{e.class} #{e}\n#{e.backtrace.join("\n")}",
+ )
ensure
Thread.current[Logster::Logger::LOGSTER_ENV] = nil
end
diff --git a/lib/site_icon_manager.rb b/lib/site_icon_manager.rb
index 10f859c6422..198d1c7faaa 100644
--- a/lib/site_icon_manager.rb
+++ b/lib/site_icon_manager.rb
@@ -3,21 +3,63 @@
module SiteIconManager
extend GlobalPath
- @cache = DistributedCache.new('icon_manager')
+ @cache = DistributedCache.new("icon_manager")
SKETCH_LOGO_ID = -6
ICONS = {
- digest_logo: { width: nil, height: nil, settings: [:digest_logo, :logo], fallback_to_sketch: false, resize_required: false },
- mobile_logo: { width: nil, height: nil, settings: [:mobile_logo, :logo], fallback_to_sketch: false, resize_required: false },
- large_icon: { width: nil, height: nil, settings: [:large_icon, :logo_small], fallback_to_sketch: true, resize_required: false },
- manifest_icon: { width: 512, height: 512, settings: [:manifest_icon, :large_icon, :logo_small], fallback_to_sketch: true, resize_required: true },
- favicon: { width: 32, height: 32, settings: [:favicon, :large_icon, :logo_small], fallback_to_sketch: true, resize_required: false },
- apple_touch_icon: { width: 180, height: 180, settings: [:apple_touch_icon, :large_icon, :logo_small], fallback_to_sketch: true, resize_required: false },
- opengraph_image: { width: nil, height: nil, settings: [:opengraph_image, :large_icon, :logo_small, :logo], fallback_to_sketch: true, resize_required: false },
+ digest_logo: {
+ width: nil,
+ height: nil,
+ settings: %i[digest_logo logo],
+ fallback_to_sketch: false,
+ resize_required: false,
+ },
+ mobile_logo: {
+ width: nil,
+ height: nil,
+ settings: %i[mobile_logo logo],
+ fallback_to_sketch: false,
+ resize_required: false,
+ },
+ large_icon: {
+ width: nil,
+ height: nil,
+ settings: %i[large_icon logo_small],
+ fallback_to_sketch: true,
+ resize_required: false,
+ },
+ manifest_icon: {
+ width: 512,
+ height: 512,
+ settings: %i[manifest_icon large_icon logo_small],
+ fallback_to_sketch: true,
+ resize_required: true,
+ },
+ favicon: {
+ width: 32,
+ height: 32,
+ settings: %i[favicon large_icon logo_small],
+ fallback_to_sketch: true,
+ resize_required: false,
+ },
+ apple_touch_icon: {
+ width: 180,
+ height: 180,
+ settings: %i[apple_touch_icon large_icon logo_small],
+ fallback_to_sketch: true,
+ resize_required: false,
+ },
+ opengraph_image: {
+ width: nil,
+ height: nil,
+ settings: %i[opengraph_image large_icon logo_small logo],
+ fallback_to_sketch: true,
+ resize_required: false,
+ },
}
- WATCHED_SETTINGS = ICONS.keys + [:logo, :logo_small]
+ WATCHED_SETTINGS = ICONS.keys + %i[logo logo_small]
def self.ensure_optimized!
unless @disabled
@@ -45,7 +87,7 @@ module SiteIconManager
define_singleton_method("#{name}_url") do
get_set_cache("#{name}_url") do
icon = self.public_send(name)
- icon ? full_cdn_url(icon.url) : ''
+ icon ? full_cdn_url(icon.url) : ""
end
end
end
@@ -73,5 +115,4 @@ module SiteIconManager
return Upload.find(SKETCH_LOGO_ID) if info[:fallback_to_sketch]
nil
end
-
end
diff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rb
index 2925cc0760b..d89408a63db 100644
--- a/lib/site_setting_extension.rb
+++ b/lib/site_setting_extension.rb
@@ -119,57 +119,43 @@ module SiteSettingExtension
name = name_arg.to_sym
if name == :default_locale
- raise Discourse::InvalidParameters.new("Other settings depend on default locale, you can not configure it like this")
+ raise Discourse::InvalidParameters.new(
+ "Other settings depend on default locale, you can not configure it like this",
+ )
end
shadowed_val = nil
mutex.synchronize do
- defaults.load_setting(
- name,
- default,
- opts.delete(:locale_default)
- )
+ defaults.load_setting(name, default, opts.delete(:locale_default))
categories[name] = opts[:category] || :uncategorized
- if opts[:hidden]
- hidden_settings << name
- end
+ hidden_settings << name if opts[:hidden]
if GlobalSetting.respond_to?(name)
val = GlobalSetting.public_send(name)
- unless val.nil? || (val == '')
+ unless val.nil? || (val == "")
shadowed_val = val
hidden_settings << name
shadowed_settings << name
end
end
- if opts[:refresh]
- refresh_settings << name
- end
+ refresh_settings << name if opts[:refresh]
- if opts[:client]
- client_settings << name.to_sym
- end
+ client_settings << name.to_sym if opts[:client]
- if opts[:preview]
- previews[name] = opts[:preview]
- end
+ previews[name] = opts[:preview] if opts[:preview]
- if opts[:secret]
- secret_settings << name
- end
+ secret_settings << name if opts[:secret]
- if opts[:plugin]
- plugins[name] = opts[:plugin]
- end
+ plugins[name] = opts[:plugin] if opts[:plugin]
type_supervisor.load_setting(
name,
- opts.extract!(*SiteSettings::TypeSupervisor::CONSUMED_OPTS)
+ opts.extract!(*SiteSettings::TypeSupervisor::CONSUMED_OPTS),
)
if !shadowed_val.nil?
@@ -184,68 +170,69 @@ module SiteSettingExtension
result = {}
deprecated_settings = Set.new
- SiteSettings::DeprecatedSettings::SETTINGS.each do |s|
- deprecated_settings << s[0]
- end
+ SiteSettings::DeprecatedSettings::SETTINGS.each { |s| deprecated_settings << s[0] }
defaults.all.keys.each do |s|
- result[s] =
- if deprecated_settings.include?(s.to_s)
- public_send(s, warn: false).to_s
- else
- public_send(s).to_s
- end
+ result[s] = if deprecated_settings.include?(s.to_s)
+ public_send(s, warn: false).to_s
+ else
+ public_send(s).to_s
+ end
end
result
end
def client_settings_json
- Discourse.cache.fetch(SiteSettingExtension.client_settings_cache_key, expires_in: 30.minutes) do
- client_settings_json_uncached
- end
+ Discourse
+ .cache
+ .fetch(SiteSettingExtension.client_settings_cache_key, expires_in: 30.minutes) do
+ client_settings_json_uncached
+ end
end
def client_settings_json_uncached
- MultiJson.dump(Hash[*@client_settings.map do |name|
- value = self.public_send(name)
- type = type_supervisor.get_type(name)
- value = value.to_s if type == :upload
- value = value.map(&:to_s).join("|") if type == :uploaded_image_list
-
- [name, value]
- end.flatten])
+ MultiJson.dump(
+ Hash[
+ *@client_settings
+ .map do |name|
+ value = self.public_send(name)
+ type = type_supervisor.get_type(name)
+ value = value.to_s if type == :upload
+ value = value.map(&:to_s).join("|") if type == :uploaded_image_list
+
+ [name, value]
+ end
+ .flatten
+ ],
+ )
end
# Retrieve all settings
def all_settings(include_hidden: false)
-
- locale_setting_hash =
- {
- setting: 'default_locale',
+ locale_setting_hash = {
+ setting: "default_locale",
default: SiteSettings::DefaultsProvider::DEFAULT_LOCALE,
- category: 'required',
- description: description('default_locale'),
+ category: "required",
+ description: description("default_locale"),
type: SiteSetting.types[SiteSetting.types[:enum]],
preview: nil,
value: self.default_locale,
valid_values: LocaleSiteSetting.values,
- translate_names: LocaleSiteSetting.translate_names?
+ translate_names: LocaleSiteSetting.translate_names?,
}
- defaults.all(default_locale)
- .reject do |setting_name, _|
- !include_hidden && hidden_settings.include?(setting_name)
- end.map do |s, v|
+ defaults
+ .all(default_locale)
+ .reject { |setting_name, _| !include_hidden && hidden_settings.include?(setting_name) }
+ .map do |s, v|
type_hash = type_supervisor.type_hash(s)
default = defaults.get(s, default_locale).to_s
value = public_send(s)
value = value.map(&:to_s).join("|") if type_hash[:type].to_s == "uploaded_image_list"
- if type_hash[:type].to_s == "upload" &&
- default.to_i < Upload::SEEDED_ID_THRESHOLD
-
+ if type_hash[:type].to_s == "upload" && default.to_i < Upload::SEEDED_ID_THRESHOLD
default = default_uploads[default.to_i]
end
@@ -257,13 +244,14 @@ module SiteSettingExtension
category: categories[s],
preview: previews[s],
secret: secret_settings.include?(s),
- placeholder: placeholder(s)
+ placeholder: placeholder(s),
}.merge!(type_hash)
opts[:plugin] = plugins[s] if plugins[s]
opts
- end.unshift(locale_setting_hash)
+ end
+ .unshift(locale_setting_hash)
end
def description(setting)
@@ -290,9 +278,18 @@ module SiteSettingExtension
mutex.synchronize do
ensure_listen_for_changes
- new_hash = Hash[*(defaults.db_all.map { |s|
- [s.name.to_sym, type_supervisor.to_rb_value(s.name, s.value, s.data_type)]
- }.to_a.flatten)]
+ new_hash =
+ Hash[
+ *(
+ defaults
+ .db_all
+ .map do |s|
+ [s.name.to_sym, type_supervisor.to_rb_value(s.name, s.value, s.data_type)]
+ end
+ .to_a
+ .flatten
+ )
+ ]
defaults_view = defaults.all(new_hash[:default_locale])
@@ -317,9 +314,7 @@ module SiteSettingExtension
unless @subscribed
MessageBus.subscribe("/site_settings") do |message|
- if message.data["process"] != process_id
- process_message(message)
- end
+ process_message(message) if message.data["process"] != process_id
end
@subscribed = true
@@ -337,9 +332,7 @@ module SiteSettingExtension
end
def diags
- {
- last_message_processed: @last_message_processed
- }
+ { last_message_processed: @last_message_processed }
end
def process_id
@@ -360,7 +353,9 @@ module SiteSettingExtension
clear_uploads_cache(name)
clear_cache!
- DiscourseEvent.trigger(:site_setting_changed, name, old_val, current[name]) if old_val != current[name]
+ if old_val != current[name]
+ DiscourseEvent.trigger(:site_setting_changed, name, old_val, current[name])
+ end
end
def add_override!(name, val)
@@ -378,29 +373,43 @@ module SiteSettingExtension
clear_uploads_cache(name)
notify_clients!(name) if client_settings.include? name
clear_cache!
- DiscourseEvent.trigger(:site_setting_changed, name, old_val, current[name]) if old_val != current[name]
+ if old_val != current[name]
+ DiscourseEvent.trigger(:site_setting_changed, name, old_val, current[name])
+ end
end
def notify_changed!
- MessageBus.publish('/site_settings', process: process_id)
+ MessageBus.publish("/site_settings", process: process_id)
end
def notify_clients!(name)
- MessageBus.publish('/client_settings', name: name, value: self.public_send(name))
+ MessageBus.publish("/client_settings", name: name, value: self.public_send(name))
end
def requires_refresh?(name)
refresh_settings.include?(name.to_sym)
end
- HOSTNAME_SETTINGS ||= %w{
- disabled_image_download_domains blocked_onebox_domains exclude_rel_nofollow_domains
- blocked_email_domains allowed_email_domains allowed_spam_host_domains
- }
+ HOSTNAME_SETTINGS ||= %w[
+ disabled_image_download_domains
+ blocked_onebox_domains
+ exclude_rel_nofollow_domains
+ blocked_email_domains
+ allowed_email_domains
+ allowed_spam_host_domains
+ ]
def filter_value(name, value)
if HOSTNAME_SETTINGS.include?(name)
- value.split("|").map { |url| url.strip!; get_hostname(url) }.compact.uniq.join("|")
+ value
+ .split("|")
+ .map do |url|
+ url.strip!
+ get_hostname(url)
+ end
+ .compact
+ .uniq
+ .join("|")
else
value
end
@@ -416,7 +425,9 @@ module SiteSettingExtension
end
Discourse.request_refresh! if requires_refresh?(name)
else
- raise Discourse::InvalidParameters.new("Either no setting named '#{name}' exists or value provided is invalid")
+ raise Discourse::InvalidParameters.new(
+ "Either no setting named '#{name}' exists or value provided is invalid",
+ )
end
end
@@ -470,9 +481,7 @@ module SiteSettingExtension
changes << [name, value] if !old.has_key?(name) || old[name] != value
end
- old.each do |name, value|
- deletions << [name, value] unless new_hash.has_key?(name)
- end
+ old.each { |name, value| deletions << [name, value] unless new_hash.has_key?(name) }
[changes, deletions]
end
@@ -489,10 +498,13 @@ module SiteSettingExtension
end
define_singleton_method "#{clean_name}=" do |val|
- Rails.logger.warn("An attempt was to change #{clean_name} SiteSetting to #{val} however it is shadowed so this will be ignored!") if value != val
+ if value != val
+ Rails.logger.warn(
+ "An attempt was to change #{clean_name} SiteSetting to #{val} however it is shadowed so this will be ignored!",
+ )
+ end
nil
end
-
end
def setup_methods(name)
@@ -561,18 +573,19 @@ module SiteSettingExtension
end
def get_hostname(url)
+ host =
+ begin
+ URI.parse(url)&.host
+ rescue URI::Error
+ nil
+ end
- host = begin
- URI.parse(url)&.host
- rescue URI::Error
- nil
- end
-
- host ||= begin
- URI.parse("http://#{url}")&.host
- rescue URI::Error
- nil
- end
+ host ||=
+ begin
+ URI.parse("http://#{url}")&.host
+ rescue URI::Error
+ nil
+ end
host.presence || url
end
@@ -593,7 +606,10 @@ module SiteSettingExtension
end
def clear_uploads_cache(name)
- if (type_supervisor.get_type(name) == :upload || type_supervisor.get_type(name) == :uploaded_image_list) && uploads.has_key?(name)
+ if (
+ type_supervisor.get_type(name) == :upload ||
+ type_supervisor.get_type(name) == :uploaded_image_list
+ ) && uploads.has_key?(name)
uploads.delete(name)
end
end
diff --git a/lib/site_settings/db_provider.rb b/lib/site_settings/db_provider.rb
index 6f291995d35..6c4aebaaa97 100644
--- a/lib/site_settings/db_provider.rb
+++ b/lib/site_settings/db_provider.rb
@@ -1,13 +1,11 @@
# frozen_string_literal: true
-module SiteSettings; end
+module SiteSettings
+end
class SiteSettings::DbProvider
-
def initialize(model)
- model.after_commit do
- model.notify_changed!
- end
+ model.after_commit { model.notify_changed! }
@model = model
end
@@ -23,8 +21,7 @@ class SiteSettings::DbProvider
return nil unless table_exists?
# Not leaking out AR records, cause I want all editing to happen via this API
- DB.query("SELECT name, data_type, value FROM #{@model.table_name} WHERE name = ?", name)
- .first
+ DB.query("SELECT name, data_type, value FROM #{@model.table_name} WHERE name = ?", name).first
end
def save(name, value, data_type)
@@ -60,5 +57,4 @@ class SiteSettings::DbProvider
@table_exists ||= {}
@table_exists[current_site] ||= ActiveRecord::Base.connection.table_exists?(@model.table_name)
end
-
end
diff --git a/lib/site_settings/defaults_provider.rb b/lib/site_settings/defaults_provider.rb
index 9ebae9aa512..1c75093aa81 100644
--- a/lib/site_settings/defaults_provider.rb
+++ b/lib/site_settings/defaults_provider.rb
@@ -1,10 +1,11 @@
# frozen_string_literal: true
-module SiteSettings; end
+module SiteSettings
+end
# A cache for providing default value based on site locale
class SiteSettings::DefaultsProvider
- DEFAULT_LOCALE = 'en'
+ DEFAULT_LOCALE = "en"
def initialize(site_setting)
@site_setting = site_setting
@@ -53,7 +54,9 @@ class SiteSettings::DefaultsProvider
@defaults[DEFAULT_LOCALE.to_sym][name] = value
value, type = @site_setting.type_supervisor.to_db_value(name, value)
@defaults[SiteSetting.default_locale.to_sym] ||= {}
- @defaults[SiteSetting.default_locale.to_sym][name] = @site_setting.type_supervisor.to_rb_value(name, value, type)
+ @defaults[SiteSetting.default_locale.to_sym][
+ name
+ ] = @site_setting.type_supervisor.to_rb_value(name, value, type)
else
raise ArgumentError.new("No setting named '#{name}' exists")
end
@@ -72,5 +75,4 @@ class SiteSettings::DefaultsProvider
def current_db
RailsMultisite::ConnectionManagement.current_db
end
-
end
diff --git a/lib/site_settings/deprecated_settings.rb b/lib/site_settings/deprecated_settings.rb
index 898ca2ceaa6..6ac4ca69647 100644
--- a/lib/site_settings/deprecated_settings.rb
+++ b/lib/site_settings/deprecated_settings.rb
@@ -1,24 +1,37 @@
# frozen_string_literal: true
-module SiteSettings; end
+module SiteSettings
+end
module SiteSettings::DeprecatedSettings
SETTINGS = [
# [<old setting>, <new_setting>, <override>, <version to drop>]
- ['search_tokenize_chinese_japanese_korean', 'search_tokenize_chinese', true, '2.9'],
- ['default_categories_regular', 'default_categories_normal', true, '3.0'],
- ['min_trust_to_send_messages', 'personal_message_enabled_groups', false, '3.0'],
- ['enable_personal_messages', 'personal_message_enabled_groups', false, '3.0'],
- ['secure_media', 'secure_uploads', true, '3.0'],
- ['secure_media_allow_embed_images_in_emails', 'secure_uploads_allow_embed_images_in_emails', true, '3.0'],
- ['secure_media_max_email_embed_image_size_kb', 'secure_uploads_max_email_embed_image_size_kb', true, '3.0'],
+ ["search_tokenize_chinese_japanese_korean", "search_tokenize_chinese", true, "2.9"],
+ ["default_categories_regular", "default_categories_normal", true, "3.0"],
+ ["min_trust_to_send_messages", "personal_message_enabled_groups", false, "3.0"],
+ ["enable_personal_messages", "personal_message_enabled_groups", false, "3.0"],
+ ["secure_media", "secure_uploads", true, "3.0"],
+ [
+ "secure_media_allow_embed_images_in_emails",
+ "secure_uploads_allow_embed_images_in_emails",
+ true,
+ "3.0",
+ ],
+ [
+ "secure_media_max_email_embed_image_size_kb",
+ "secure_uploads_max_email_embed_image_size_kb",
+ true,
+ "3.0",
+ ],
]
def setup_deprecated_methods
SETTINGS.each do |old_setting, new_setting, override, version|
unless override
SiteSetting.singleton_class.public_send(
- :alias_method, :"_#{old_setting}", :"#{old_setting}"
+ :alias_method,
+ :"_#{old_setting}",
+ :"#{old_setting}",
)
end
@@ -26,7 +39,7 @@ module SiteSettings::DeprecatedSettings
if warn
Discourse.deprecate(
"`SiteSetting.#{old_setting}` has been deprecated. Please use `SiteSetting.#{new_setting}` instead.",
- drop_from: version
+ drop_from: version,
)
end
@@ -35,7 +48,9 @@ module SiteSettings::DeprecatedSettings
unless override
SiteSetting.singleton_class.public_send(
- :alias_method, :"_#{old_setting}?", :"#{old_setting}?"
+ :alias_method,
+ :"_#{old_setting}?",
+ :"#{old_setting}?",
)
end
@@ -43,7 +58,7 @@ module SiteSettings::DeprecatedSettings
if warn
Discourse.deprecate(
"`SiteSetting.#{old_setting}?` has been deprecated. Please use `SiteSetting.#{new_setting}?` instead.",
- drop_from: version
+ drop_from: version,
)
end
@@ -52,7 +67,9 @@ module SiteSettings::DeprecatedSettings
unless override
SiteSetting.singleton_class.public_send(
- :alias_method, :"_#{old_setting}=", :"#{old_setting}="
+ :alias_method,
+ :"_#{old_setting}=",
+ :"#{old_setting}=",
)
end
@@ -60,7 +77,7 @@ module SiteSettings::DeprecatedSettings
if warn
Discourse.deprecate(
"`SiteSetting.#{old_setting}=` has been deprecated. Please use `SiteSetting.#{new_setting}=` instead.",
- drop_from: version
+ drop_from: version,
)
end
diff --git a/lib/site_settings/local_process_provider.rb b/lib/site_settings/local_process_provider.rb
index 37e5faad56b..5e6f7993f37 100644
--- a/lib/site_settings/local_process_provider.rb
+++ b/lib/site_settings/local_process_provider.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
-module SiteSettings; end
+module SiteSettings
+end
class SiteSettings::LocalProcessProvider
class Setting
diff --git a/lib/site_settings/type_supervisor.rb b/lib/site_settings/type_supervisor.rb
index 80a51e81e92..acff911c84d 100644
--- a/lib/site_settings/type_supervisor.rb
+++ b/lib/site_settings/type_supervisor.rb
@@ -1,44 +1,60 @@
# frozen_string_literal: true
-module SiteSettings; end
+module SiteSettings
+end
class SiteSettings::TypeSupervisor
include SiteSettings::Validations
- CONSUMED_OPTS = %i[enum choices type validator min max regex hidden regex_error allow_any list_type textarea json_schema].freeze
+ CONSUMED_OPTS = %i[
+ enum
+ choices
+ type
+ validator
+ min
+ max
+ regex
+ hidden
+ regex_error
+ allow_any
+ list_type
+ textarea
+ json_schema
+ ].freeze
VALIDATOR_OPTS = %i[min max regex hidden regex_error json_schema].freeze
# For plugins, so they can tell if a feature is supported
SUPPORTED_TYPES = %i[email username list enum].freeze
def self.types
- @types ||= Enum.new(
- string: 1,
- time: 2,
- integer: 3,
- float: 4,
- bool: 5,
- null: 6,
- enum: 7,
- list: 8,
- url_list: 9,
- host_list: 10,
- category_list: 11,
- value_list: 12,
- regex: 13,
- email: 14,
- username: 15,
- category: 16,
- uploaded_image_list: 17,
- upload: 18,
- group: 19,
- group_list: 20,
- tag_list: 21,
- color: 22,
- simple_list: 23,
- emoji_list: 24,
- html_deprecated: 25,
- )
+ @types ||=
+ Enum.new(
+ string: 1,
+ time: 2,
+ integer: 3,
+ float: 4,
+ bool: 5,
+ null: 6,
+ enum: 7,
+ list: 8,
+ url_list: 9,
+ host_list: 10,
+ category_list: 11,
+ value_list: 12,
+ regex: 13,
+ email: 14,
+ username: 15,
+ category: 16,
+ uploaded_image_list: 17,
+ upload: 18,
+ group: 19,
+ group_list: 20,
+ tag_list: 21,
+ color: 22,
+ simple_list: 23,
+ emoji_list: 24,
+ html_deprecated: 25,
+ )
end
def self.parse_value_type(val)
@@ -78,13 +94,9 @@ class SiteSettings::TypeSupervisor
def load_setting(name_arg, opts = {})
name = name_arg.to_sym
- if opts[:textarea]
- @textareas[name] = opts[:textarea]
- end
+ @textareas[name] = opts[:textarea] if opts[:textarea]
- if opts[:json_schema]
- @json_schemas[name] = opts[:json_schema].constantize
- end
+ @json_schemas[name] = opts[:json_schema].constantize if opts[:json_schema]
if (enum = opts[:enum])
@enums[name] = enum.is_a?(String) ? enum.constantize : enum
@@ -130,7 +142,7 @@ class SiteSettings::TypeSupervisor
when self.class.types[:integer]
value.to_i
when self.class.types[:bool]
- value == true || value == 't' || value == 'true'
+ value == true || value == "t" || value == "true"
when self.class.types[:null]
nil
when self.class.types[:enum]
@@ -160,13 +172,14 @@ class SiteSettings::TypeSupervisor
if (klass = enum_class(name))
result.merge!(valid_values: klass.values, translate_names: klass.translate_names?)
else
- result.merge!(valid_values: @choices[name].map { |c| { name: c, value: c } }, translate_names: false)
+ result.merge!(
+ valid_values: @choices[name].map { |c| { name: c, value: c } },
+ translate_names: false,
+ )
end
end
- if type == :list
- result[:allow_any] = @allow_any[name]
- end
+ result[:allow_any] = @allow_any[name] if type == :list
result[:choices] = @choices[name] if @choices.has_key? name
result[:list_type] = @list_type[name] if @list_type.has_key? name
@@ -189,10 +202,10 @@ class SiteSettings::TypeSupervisor
type = @types[name] || self.class.parse_value_type(val)
if type == self.class.types[:bool]
- val = (val == true || val == 't' || val == 'true') ? 't' : 'f'
+ val = (val == true || val == "t" || val == "true") ? "t" : "f"
elsif type == self.class.types[:integer] && !val.is_a?(Integer)
val = val.to_i
- elsif type == self.class.types[:null] && val != ''
+ elsif type == self.class.types[:null] && val != ""
type = get_data_type(name, val)
elsif type == self.class.types[:enum]
val = @defaults_provider[name].is_a?(Integer) ? val.to_i : val.to_s
@@ -208,7 +221,9 @@ class SiteSettings::TypeSupervisor
def validate_value(name, type, val)
if type == self.class.types[:enum]
if enum_class(name)
- raise Discourse::InvalidParameters.new("Invalid value `#{val}` for `#{name}`") unless enum_class(name).valid_value?(val)
+ unless enum_class(name).valid_value?(val)
+ raise Discourse::InvalidParameters.new("Invalid value `#{val}` for `#{name}`")
+ end
else
unless (choice = @choices[name])
raise Discourse::InvalidParameters.new(name)
@@ -223,7 +238,13 @@ class SiteSettings::TypeSupervisor
split = val.to_s.split("|")
diff = (split - @choices[name])
if diff.length > 0
- raise Discourse::InvalidParameters.new(I18n.t('errors.site_settings.invalid_choice', name: diff.join(','), count: diff.length))
+ raise Discourse::InvalidParameters.new(
+ I18n.t(
+ "errors.site_settings.invalid_choice",
+ name: diff.join(","),
+ count: diff.length,
+ ),
+ )
end
end
end
@@ -236,9 +257,7 @@ class SiteSettings::TypeSupervisor
end
validate_method = "validate_#{name}"
- if self.respond_to? validate_method
- public_send(validate_method, val)
- end
+ public_send(validate_method, val) if self.respond_to? validate_method
end
def get_data_type(name, val)
@@ -275,7 +294,8 @@ class SiteSettings::TypeSupervisor
StringSettingValidator
when self.class.types[:host_list]
HostListSettingValidator
- else nil
+ else
+ nil
end
end
end
diff --git a/lib/site_settings/validations.rb b/lib/site_settings/validations.rb
index 43a34d48255..fdc36ff57e4 100644
--- a/lib/site_settings/validations.rb
+++ b/lib/site_settings/validations.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
-module SiteSettings; end
+module SiteSettings
+end
module SiteSettings::Validations
PROHIBITED_USER_AGENT_STRINGS = %w[
@@ -30,13 +31,17 @@ module SiteSettings::Validations
end
def validate_category_ids(category_ids)
- category_ids = category_ids.split('|').map(&:to_i).to_set
- validate_error :invalid_category_id if Category.where(id: category_ids).count != category_ids.size
+ category_ids = category_ids.split("|").map(&:to_i).to_set
+ if Category.where(id: category_ids).count != category_ids.size
+ validate_error :invalid_category_id
+ end
category_ids
end
def validate_default_categories(category_ids, default_categories_selected)
- validate_error :default_categories_already_selected if (category_ids & default_categories_selected).size > 0
+ if (category_ids & default_categories_selected).size > 0
+ validate_error :default_categories_already_selected
+ end
end
def validate_default_categories_watching(new_val)
@@ -46,7 +51,7 @@ module SiteSettings::Validations
SiteSetting.default_categories_tracking.split("|"),
SiteSetting.default_categories_muted.split("|"),
SiteSetting.default_categories_watching_first_post.split("|"),
- SiteSetting.default_categories_normal.split("|")
+ SiteSetting.default_categories_normal.split("|"),
].flatten.map(&:to_i).to_set
validate_default_categories(category_ids, default_categories_selected)
@@ -59,7 +64,7 @@ module SiteSettings::Validations
SiteSetting.default_categories_watching.split("|"),
SiteSetting.default_categories_muted.split("|"),
SiteSetting.default_categories_watching_first_post.split("|"),
- SiteSetting.default_categories_normal.split("|")
+ SiteSetting.default_categories_normal.split("|"),
].flatten.map(&:to_i).to_set
validate_default_categories(category_ids, default_categories_selected)
@@ -72,7 +77,7 @@ module SiteSettings::Validations
SiteSetting.default_categories_watching.split("|"),
SiteSetting.default_categories_tracking.split("|"),
SiteSetting.default_categories_watching_first_post.split("|"),
- SiteSetting.default_categories_normal.split("|")
+ SiteSetting.default_categories_normal.split("|"),
].flatten.map(&:to_i).to_set
validate_default_categories(category_ids, default_categories_selected)
@@ -85,7 +90,7 @@ module SiteSettings::Validations
SiteSetting.default_categories_watching.split("|"),
SiteSetting.default_categories_tracking.split("|"),
SiteSetting.default_categories_muted.split("|"),
- SiteSetting.default_categories_normal.split("|")
+ SiteSetting.default_categories_normal.split("|"),
].flatten.map(&:to_i).to_set
validate_default_categories(category_ids, default_categories_selected)
@@ -98,7 +103,7 @@ module SiteSettings::Validations
SiteSetting.default_categories_watching.split("|"),
SiteSetting.default_categories_tracking.split("|"),
SiteSetting.default_categories_muted.split("|"),
- SiteSetting.default_categories_watching_first_post.split("|")
+ SiteSetting.default_categories_watching_first_post.split("|"),
].flatten.map(&:to_i).to_set
validate_default_categories(category_ids, default_categories_selected)
@@ -109,48 +114,48 @@ module SiteSettings::Validations
end
def validate_default_tags_watching(new_val)
- tag_names = new_val.split('|').to_set
+ tag_names = new_val.split("|").to_set
default_tags_selected = [
SiteSetting.default_tags_tracking.split("|"),
SiteSetting.default_tags_muted.split("|"),
- SiteSetting.default_tags_watching_first_post.split("|")
+ SiteSetting.default_tags_watching_first_post.split("|"),
].flatten.to_set
validate_default_tags(tag_names, default_tags_selected)
end
def validate_default_tags_tracking(new_val)
- tag_names = new_val.split('|').to_set
+ tag_names = new_val.split("|").to_set
default_tags_selected = [
SiteSetting.default_tags_watching.split("|"),
SiteSetting.default_tags_muted.split("|"),
- SiteSetting.default_tags_watching_first_post.split("|")
+ SiteSetting.default_tags_watching_first_post.split("|"),
].flatten.to_set
validate_default_tags(tag_names, default_tags_selected)
end
def validate_default_tags_muted(new_val)
- tag_names = new_val.split('|').to_set
+ tag_names = new_val.split("|").to_set
default_tags_selected = [
SiteSetting.default_tags_watching.split("|"),
SiteSetting.default_tags_tracking.split("|"),
- SiteSetting.default_tags_watching_first_post.split("|")
+ SiteSetting.default_tags_watching_first_post.split("|"),
].flatten.to_set
validate_default_tags(tag_names, default_tags_selected)
end
def validate_default_tags_watching_first_post(new_val)
- tag_names = new_val.split('|').to_set
+ tag_names = new_val.split("|").to_set
default_tags_selected = [
SiteSetting.default_tags_watching.split("|"),
SiteSetting.default_tags_tracking.split("|"),
- SiteSetting.default_tags_muted.split("|")
+ SiteSetting.default_tags_muted.split("|"),
].flatten.to_set
validate_default_tags(tag_names, default_tags_selected)
@@ -163,7 +168,9 @@ module SiteSettings::Validations
end
def validate_secure_uploads(new_val)
- validate_error :secure_uploads_requirements if new_val == "t" && !SiteSetting.Upload.enable_s3_uploads
+ if new_val == "t" && !SiteSetting.Upload.enable_s3_uploads
+ validate_error :secure_uploads_requirements
+ end
end
def validate_enable_page_publishing(new_val)
@@ -171,27 +178,39 @@ module SiteSettings::Validations
end
def validate_share_quote_buttons(new_val)
- validate_error :share_quote_facebook_requirements if new_val.include?("facebook") && SiteSetting.facebook_app_id.blank?
+ if new_val.include?("facebook") && SiteSetting.facebook_app_id.blank?
+ validate_error :share_quote_facebook_requirements
+ end
end
def validate_enable_s3_inventory(new_val)
- validate_error :enable_s3_uploads_is_required if new_val == "t" && !SiteSetting.Upload.enable_s3_uploads
+ if new_val == "t" && !SiteSetting.Upload.enable_s3_uploads
+ validate_error :enable_s3_uploads_is_required
+ end
end
def validate_backup_location(new_val)
return unless new_val == BackupLocationSiteSetting::S3
- validate_error(:s3_backup_requires_s3_settings, setting_name: "s3_backup_bucket") if SiteSetting.s3_backup_bucket.blank?
+ if SiteSetting.s3_backup_bucket.blank?
+ validate_error(:s3_backup_requires_s3_settings, setting_name: "s3_backup_bucket")
+ end
unless SiteSetting.s3_use_iam_profile
- validate_error(:s3_backup_requires_s3_settings, setting_name: "s3_access_key_id") if SiteSetting.s3_access_key_id.blank?
- validate_error(:s3_backup_requires_s3_settings, setting_name: "s3_secret_access_key") if SiteSetting.s3_secret_access_key.blank?
+ if SiteSetting.s3_access_key_id.blank?
+ validate_error(:s3_backup_requires_s3_settings, setting_name: "s3_access_key_id")
+ end
+ if SiteSetting.s3_secret_access_key.blank?
+ validate_error(:s3_backup_requires_s3_settings, setting_name: "s3_secret_access_key")
+ end
end
end
def validate_s3_upload_bucket(new_val)
validate_bucket_setting("s3_upload_bucket", new_val, SiteSetting.s3_backup_bucket)
- validate_error(:s3_upload_bucket_is_required, setting_name: 's3_upload_bucket') if new_val.blank? && SiteSetting.enable_s3_uploads?
+ if new_val.blank? && SiteSetting.enable_s3_uploads?
+ validate_error(:s3_upload_bucket_is_required, setting_name: "s3_upload_bucket")
+ end
end
def validate_s3_backup_bucket(new_val)
@@ -204,7 +223,12 @@ module SiteSettings::Validations
end
if new_val == "all" && Discourse.enabled_auth_providers.count > 0
auth_provider_names = Discourse.enabled_auth_providers.map(&:name).join(", ")
- return validate_error(:second_factor_cannot_enforce_with_socials, auth_provider_names: auth_provider_names)
+ return(
+ validate_error(
+ :second_factor_cannot_enforce_with_socials,
+ auth_provider_names: auth_provider_names,
+ )
+ )
end
return if SiteSetting.enable_local_logins
return if new_val == "no"
@@ -219,24 +243,27 @@ module SiteSettings::Validations
def validate_cors_origins(new_val)
return if new_val.blank?
- return unless new_val.split('|').any?(/\/$/)
+ return unless new_val.split("|").any?(%r{/$})
validate_error :cors_origins_should_not_have_trailing_slash
end
def validate_slow_down_crawler_user_agents(new_val)
return if new_val.blank?
- new_val.downcase.split("|").each do |crawler|
- if crawler.size < 3
- validate_error(:slow_down_crawler_user_agent_must_be_at_least_3_characters)
+ new_val
+ .downcase
+ .split("|")
+ .each do |crawler|
+ if crawler.size < 3
+ validate_error(:slow_down_crawler_user_agent_must_be_at_least_3_characters)
+ end
+ if PROHIBITED_USER_AGENT_STRINGS.any? { |c| c.include?(crawler) }
+ validate_error(
+ :slow_down_crawler_user_agent_cannot_be_popular_browsers,
+ values: PROHIBITED_USER_AGENT_STRINGS.join(I18n.t("word_connector.comma")),
+ )
+ end
end
- if PROHIBITED_USER_AGENT_STRINGS.any? { |c| c.include?(crawler) }
- validate_error(
- :slow_down_crawler_user_agent_cannot_be_popular_browsers,
- values: PROHIBITED_USER_AGENT_STRINGS.join(I18n.t("word_connector.comma"))
- )
- end
- end
end
def validate_strip_image_metadata(new_val)
@@ -261,7 +288,8 @@ module SiteSettings::Validations
return if backup_bucket_name != upload_bucket_name
- if backup_prefix == upload_prefix || backup_prefix.blank? || upload_prefix&.start_with?(backup_prefix)
+ if backup_prefix == upload_prefix || backup_prefix.blank? ||
+ upload_prefix&.start_with?(backup_prefix)
validate_error(:s3_bucket_reused, setting_name: setting_name)
end
end
diff --git a/lib/site_settings/yaml_loader.rb b/lib/site_settings/yaml_loader.rb
index 2ec4c4a412e..cfd44db56a1 100644
--- a/lib/site_settings/yaml_loader.rb
+++ b/lib/site_settings/yaml_loader.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
-module SiteSettings; end
+module SiteSettings
+end
class SiteSettings::YamlLoader
def initialize(file)
@@ -13,14 +14,16 @@ class SiteSettings::YamlLoader
yaml[category].each do |setting_name, hash|
if hash.is_a?(Hash)
# Get default value for the site setting:
- value = hash.delete('default')
+ value = hash.delete("default")
if value.nil?
- raise StandardError, "The site setting `#{setting_name}` in '#{@file}' is missing default value."
+ raise StandardError,
+ "The site setting `#{setting_name}` in '#{@file}' is missing default value."
end
- if hash.values_at('min', 'max').any? && hash['validator'].present?
- raise StandardError, "The site setting `#{setting_name}` in '#{@file}' will have it's min/max validation ignored because there is a validator also specified."
+ if hash.values_at("min", "max").any? && hash["validator"].present?
+ raise StandardError,
+ "The site setting `#{setting_name}` in '#{@file}' will have it's min/max validation ignored because there is a validator also specified."
end
yield category, setting_name, value, hash.deep_symbolize_keys!
@@ -35,7 +38,7 @@ class SiteSettings::YamlLoader
private
def load_yaml(path)
- if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.1.0')
+ if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("3.1.0")
YAML.load_file(path, aliases: true)
else
YAML.load_file(path)
diff --git a/lib/slug.rb b/lib/slug.rb
index ebb177347dd..4d34f06348d 100644
--- a/lib/slug.rb
+++ b/lib/slug.rb
@@ -2,20 +2,22 @@
# frozen_string_literal: true
module Slug
-
CHAR_FILTER_REGEXP = /[:\/\?#\[\]@!\$&'\(\)\*\+,;=_\.~%\\`^\s|\{\}"<>]+/ # :/?#[]@!$&'()*+,;=_.~%\`^|{}"<>
MAX_LENGTH = 255
- def self.for(string, default = 'topic', max_length = MAX_LENGTH, method: nil)
- string = string.gsub(/:([\w\-+]+(?::t\d)?):/, '') if string.present? # strip emoji strings
+ def self.for(string, default = "topic", max_length = MAX_LENGTH, method: nil)
+ string = string.gsub(/:([\w\-+]+(?::t\d)?):/, "") if string.present? # strip emoji strings
method = (method || SiteSetting.slug_generation_method || :ascii).to_sym
max_length = 9999 if method == :encoded # do not truncate encoded slugs
slug =
case method
- when :ascii then self.ascii_generator(string)
- when :encoded then self.encoded_generator(string)
- when :none then self.none_generator(string)
+ when :ascii
+ self.ascii_generator(string)
+ when :encoded
+ self.encoded_generator(string)
+ when :none
+ self.none_generator(string)
end
slug = self.prettify_slug(slug, max_length: max_length)
@@ -30,28 +32,24 @@ module Slug
def self.prettify_slug(slug, max_length:)
# Reject slugs that only contain numbers, because they would be indistinguishable from id's.
- slug = (slug_is_only_numbers?(slug) ? '' : slug)
+ slug = (slug_is_only_numbers?(slug) ? "" : slug)
slug
.tr("_", "-")
- .truncate(max_length, omission: '')
- .squeeze('-') # squeeze continuous dashes to prettify slug
- .gsub(/\A-+|-+\z/, '') # remove possible trailing and preceding dashes
+ .truncate(max_length, omission: "")
+ .squeeze("-") # squeeze continuous dashes to prettify slug
+ .gsub(/\A-+|-+\z/, "") # remove possible trailing and preceding dashes
end
def self.ascii_generator(string)
- I18n.with_locale(SiteSetting.default_locale) do
- string.tr("'", "").parameterize
- end
+ I18n.with_locale(SiteSetting.default_locale) { string.tr("'", "").parameterize }
end
def self.encoded_generator(string, downcase: true)
# This generator will sanitize almost all special characters,
# including reserved characters from RFC3986.
# See also URI::REGEXP::PATTERN.
- string = string.strip
- .gsub(/\s+/, '-')
- .gsub(CHAR_FILTER_REGEXP, '')
+ string = string.strip.gsub(/\s+/, "-").gsub(CHAR_FILTER_REGEXP, "")
string = string.downcase if downcase
@@ -59,6 +57,6 @@ module Slug
end
def self.none_generator(string)
- ''
+ ""
end
end
diff --git a/lib/socket_server.rb b/lib/socket_server.rb
index 2ae36978e0b..4c802d8b0d6 100644
--- a/lib/socket_server.rb
+++ b/lib/socket_server.rb
@@ -1,9 +1,8 @@
# frozen_string_literal: true
-require 'socket'
+require "socket"
class SocketServer
-
def initialize(socket_path)
@socket_path = socket_path
@server = nil
@@ -12,9 +11,7 @@ class SocketServer
def start(&blk)
@server = UNIXServer.new(@socket_path)
@accept_thread = new_accept_thread
- if blk
- @blk = blk
- end
+ @blk = blk if blk
end
def stop
@@ -31,9 +28,7 @@ class SocketServer
Thread.new do
begin
done = false
- while !done
- done = !accept_connection(server)
- end
+ done = !accept_connection(server) while !done
ensure
self.stop
Rails.logger.info("Cleaned up socket server at #{@socket_path}")
@@ -64,9 +59,7 @@ class SocketServer
break if line.include?("\n")
end
- if line.include?("\n")
- socket.write get_response(line.strip)
- end
+ socket.write get_response(line.strip) if line.include?("\n")
true
rescue IOError, Errno::EPIPE
@@ -84,5 +77,4 @@ class SocketServer
raise "Must be implemented by child"
end
end
-
end
diff --git a/lib/spam_handler.rb b/lib/spam_handler.rb
index fc298f87665..6537345ee7c 100644
--- a/lib/spam_handler.rb
+++ b/lib/spam_handler.rb
@@ -1,31 +1,25 @@
# frozen_string_literal: true
class SpamHandler
-
def self.should_prevent_registration_from_ip?(ip_address)
return false if SiteSetting.max_new_accounts_per_registration_ip <= 0
- tl2_plus_accounts_with_same_ip = User.where("trust_level >= ?", TrustLevel[2])
- .where(ip_address: ip_address.to_s)
- .count
+ tl2_plus_accounts_with_same_ip =
+ User.where("trust_level >= ?", TrustLevel[2]).where(ip_address: ip_address.to_s).count
return false if tl2_plus_accounts_with_same_ip > 0
- staff_members_with_same_ip = Group[:staff].users.human_users
- .where(ip_address: ip_address.to_s)
- .count
+ staff_members_with_same_ip =
+ Group[:staff].users.human_users.where(ip_address: ip_address.to_s).count
return false if staff_members_with_same_ip > 0
allowed_ip = ScreenedIpAddress.is_allowed?(ip_address)
return false if allowed_ip
- tl0_accounts_with_same_ip = User.unscoped
- .where(trust_level: TrustLevel[0])
- .where(ip_address: ip_address.to_s)
- .count
+ tl0_accounts_with_same_ip =
+ User.unscoped.where(trust_level: TrustLevel[0]).where(ip_address: ip_address.to_s).count
tl0_accounts_with_same_ip >= SiteSetting.max_new_accounts_per_registration_ip
end
-
end
diff --git a/lib/staff_constraint.rb b/lib/staff_constraint.rb
index 3f5e5a87c4e..e745719732f 100644
--- a/lib/staff_constraint.rb
+++ b/lib/staff_constraint.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class StaffConstraint
-
def matches?(request)
current_user = CurrentUser.lookup_from_env(request.env)
current_user&.staff? && custom_staff_check(request)
@@ -14,5 +13,4 @@ class StaffConstraint
def custom_staff_check(request)
true
end
-
end
diff --git a/lib/stylesheet/compiler.rb b/lib/stylesheet/compiler.rb
index ba4769a2650..356a518d172 100644
--- a/lib/stylesheet/compiler.rb
+++ b/lib/stylesheet/compiler.rb
@@ -1,11 +1,10 @@
# frozen_string_literal: true
-require 'stylesheet/importer'
+require "stylesheet/importer"
module Stylesheet
-
class Compiler
- ASSET_ROOT = "#{Rails.root}/app/assets/stylesheets" unless defined? ASSET_ROOT
+ ASSET_ROOT = "#{Rails.root}/app/assets/stylesheets" unless defined?(ASSET_ROOT)
def self.compile_asset(asset, options = {})
importer = Importer.new(options)
@@ -49,21 +48,24 @@ module Stylesheet
load_paths = [ASSET_ROOT]
load_paths += options[:load_paths] if options[:load_paths]
- engine = SassC::Engine.new(stylesheet,
- filename: filename,
- style: :compressed,
- source_map_file: source_map_file,
- source_map_contents: true,
- theme_id: options[:theme_id],
- theme: options[:theme],
- theme_field: options[:theme_field],
- color_scheme_id: options[:color_scheme_id],
- load_paths: load_paths)
+ engine =
+ SassC::Engine.new(
+ stylesheet,
+ filename: filename,
+ style: :compressed,
+ source_map_file: source_map_file,
+ source_map_contents: true,
+ theme_id: options[:theme_id],
+ theme: options[:theme],
+ theme_field: options[:theme_field],
+ color_scheme_id: options[:color_scheme_id],
+ load_paths: load_paths,
+ )
result = engine.render
if options[:rtl]
- require 'r2'
+ require "r2"
[R2.r2(result), nil]
else
source_map = engine.source_map
diff --git a/lib/stylesheet/importer.rb b/lib/stylesheet/importer.rb
index c53b5cb2d2c..8024e119391 100644
--- a/lib/stylesheet/importer.rb
+++ b/lib/stylesheet/importer.rb
@@ -1,12 +1,12 @@
# frozen_string_literal: true
-require 'global_path'
+require "global_path"
module Stylesheet
class Importer
include GlobalPath
- THEME_TARGETS ||= %w{embedded_theme mobile_theme desktop_theme}
+ THEME_TARGETS ||= %w[embedded_theme mobile_theme desktop_theme]
def self.plugin_assets
@plugin_assets ||= {}
@@ -18,12 +18,20 @@ module Stylesheet
["", "mobile", "desktop"].each do |type|
asset_name = type.present? ? "#{plugin_directory_name}_#{type}" : plugin_directory_name
- stylesheets = type.present? ? DiscoursePluginRegistry.send("#{type}_stylesheets") : DiscoursePluginRegistry.stylesheets
-
- plugin_assets[asset_name] = stylesheets[plugin_directory_name] if plugin_directory_name.present?
+ stylesheets =
+ (
+ if type.present?
+ DiscoursePluginRegistry.send("#{type}_stylesheets")
+ else
+ DiscoursePluginRegistry.stylesheets
+ end
+ )
+
+ plugin_assets[asset_name] = stylesheets[
+ plugin_directory_name
+ ] if plugin_directory_name.present?
end
end
-
end
register_imports!
@@ -33,25 +41,21 @@ module Stylesheet
heading_font = DiscourseFonts.fonts.find { |f| f[:key] == SiteSetting.heading_font }
contents = +""
- if body_font.present?
- contents << <<~CSS
+ contents << <<~CSS if body_font.present?
#{font_css(body_font)}
:root {
--font-family: #{body_font[:stack]};
}
CSS
- end
- if heading_font.present?
- contents << <<~CSS
+ contents << <<~CSS if heading_font.present?
#{font_css(heading_font)}
:root {
--heading-font-family: #{heading_font[:stack]};
}
CSS
- end
contents
end
@@ -64,8 +68,16 @@ module Stylesheet
# Overwrite font definition because the preview canvases in the wizard require explicit @font-face definitions.
# uses same technique as https://github.com/jonathantneal/system-font-css
font[:variants] = [
- { src: 'local(".SFNS-Regular"), local(".SFNSText-Regular"), local(".HelveticaNeueDeskInterface-Regular"), local(".LucidaGrandeUI"), local("Segoe UI"), local("Ubuntu"), local("Roboto-Regular"), local("DroidSans"), local("Tahoma")', weight: 400 },
- { src: 'local(".SFNS-Bold"), local(".SFNSText-Bold"), local(".HelveticaNeueDeskInterface-Bold"), local(".LucidaGrandeUI"), local("Segoe UI Bold"), local("Ubuntu Bold"), local("Roboto-Bold"), local("DroidSans-Bold"), local("Tahoma Bold")', weight: 700 }
+ {
+ src:
+ 'local(".SFNS-Regular"), local(".SFNSText-Regular"), local(".HelveticaNeueDeskInterface-Regular"), local(".LucidaGrandeUI"), local("Segoe UI"), local("Ubuntu"), local("Roboto-Regular"), local("DroidSans"), local("Tahoma")',
+ weight: 400,
+ },
+ {
+ src:
+ 'local(".SFNS-Bold"), local(".SFNSText-Bold"), local(".HelveticaNeueDeskInterface-Bold"), local(".LucidaGrandeUI"), local("Segoe UI Bold"), local("Ubuntu Bold"), local("Roboto-Bold"), local("DroidSans-Bold"), local("Tahoma Bold")',
+ weight: 700,
+ },
]
end
@@ -85,9 +97,9 @@ module Stylesheet
def category_backgrounds
contents = +""
- Category.where('uploaded_background_id IS NOT NULL').each do |c|
- contents << category_css(c) if c.uploaded_background&.url.present?
- end
+ Category
+ .where("uploaded_background_id IS NOT NULL")
+ .each { |c| contents << category_css(c) if c.uploaded_background&.url.present? }
contents
end
@@ -106,16 +118,18 @@ module Stylesheet
if resolved_ids
theme = Theme.find_by_id(theme_id)
contents << theme&.scss_variables.to_s
- Theme.list_baked_fields(resolved_ids, :common, :color_definitions).each do |field|
- contents << "\n\n// Color definitions from #{field.theme.name}\n\n"
-
- if field.theme_id == theme.id
- contents << field.value
- else
- contents << field.compiled_css(prepended_scss)
+ Theme
+ .list_baked_fields(resolved_ids, :common, :color_definitions)
+ .each do |field|
+ contents << "\n\n// Color definitions from #{field.theme.name}\n\n"
+
+ if field.theme_id == theme.id
+ contents << field.value
+ else
+ contents << field.compiled_css(prepended_scss)
+ end
+ contents << "\n\n"
end
- contents << "\n\n"
- end
end
contents
end
@@ -130,24 +144,24 @@ module Stylesheet
def color_variables
contents = +""
if @color_scheme_id
- colors = begin
- ColorScheme.find(@color_scheme_id).resolved_colors
- rescue
- ColorScheme.base_colors
- end
+ colors =
+ begin
+ ColorScheme.find(@color_scheme_id).resolved_colors
+ rescue StandardError
+ ColorScheme.base_colors
+ end
elsif (@theme_id && !theme.component)
colors = theme&.color_scheme&.resolved_colors || ColorScheme.base_colors
else
# this is a slightly ugly backwards compatibility fix,
# we shouldn't be using the default theme color scheme for components
# (most components use CSS custom properties which work fine without this)
- colors = Theme.find_by_id(SiteSetting.default_theme_id)&.color_scheme&.resolved_colors ||
- ColorScheme.base_colors
+ colors =
+ Theme.find_by_id(SiteSetting.default_theme_id)&.color_scheme&.resolved_colors ||
+ ColorScheme.base_colors
end
- colors.each do |n, hex|
- contents << "$#{n}: ##{hex} !default; "
- end
+ colors.each { |n, hex| contents << "$#{n}: ##{hex} !default; " }
contents
end
@@ -192,15 +206,12 @@ module Stylesheet
contents << value
end
-
end
contents
end
def theme
- unless @theme
- @theme = (@theme_id && Theme.find(@theme_id)) || :nil
- end
+ @theme = (@theme_id && Theme.find(@theme_id)) || :nil unless @theme
@theme == :nil ? nil : @theme
end
@@ -215,7 +226,14 @@ module Stylesheet
if font[:variants].present?
fonts_dir = UrlHelper.absolute("#{Discourse.base_path}/fonts")
font[:variants].each do |variant|
- src = variant[:src] ? variant[:src] : "url(\"#{fonts_dir}/#{variant[:filename]}?v=#{DiscourseFonts::VERSION}\") format(\"#{variant[:format]}\")"
+ src =
+ (
+ if variant[:src]
+ variant[:src]
+ else
+ "url(\"#{fonts_dir}/#{variant[:filename]}?v=#{DiscourseFonts::VERSION}\") format(\"#{variant[:format]}\")"
+ end
+ )
contents << <<~CSS
@font-face {
font-family: #{font[:name]};
@@ -228,6 +246,5 @@ module Stylesheet
contents
end
-
end
end
diff --git a/lib/stylesheet/manager.rb b/lib/stylesheet/manager.rb
index 97ac5d076c1..217bed7737e 100644
--- a/lib/stylesheet/manager.rb
+++ b/lib/stylesheet/manager.rb
@@ -1,14 +1,15 @@
# frozen_string_literal: true
-require 'distributed_cache'
-require 'stylesheet/compiler'
+require "distributed_cache"
+require "stylesheet/compiler"
-module Stylesheet; end
+module Stylesheet
+end
class Stylesheet::Manager
BASE_COMPILER_VERSION = 1
- CACHE_PATH ||= 'tmp/stylesheet-cache'
+ CACHE_PATH ||= "tmp/stylesheet-cache"
MANIFEST_DIR ||= "#{Rails.root}/tmp/cache/assets/#{Rails.env}"
THEME_REGEX ||= /_theme$/
COLOR_SCHEME_STYLESHEET ||= "color_definitions"
@@ -28,7 +29,7 @@ class Stylesheet::Manager
end
def self.clear_core_cache!(targets)
- cache.hash.keys.select { |k| k =~ /#{targets.join('|')}/ }.each { |k| cache.delete(k) }
+ cache.hash.keys.select { |k| k =~ /#{targets.join("|")}/ }.each { |k| cache.delete(k) }
end
def self.clear_plugin_cache!(plugin)
@@ -42,8 +43,13 @@ class Stylesheet::Manager
end
def self.precompile_css
- targets = [:desktop, :mobile, :desktop_rtl, :mobile_rtl, :admin, :wizard]
- targets += Discourse.find_plugin_css_assets(include_disabled: true, mobile_view: true, desktop_view: true)
+ targets = %i[desktop mobile desktop_rtl mobile_rtl admin wizard]
+ targets +=
+ Discourse.find_plugin_css_assets(
+ include_disabled: true,
+ mobile_view: true,
+ desktop_view: true,
+ )
targets.each do |target|
$stderr.puts "precompile target: #{target}"
@@ -53,14 +59,18 @@ class Stylesheet::Manager
end
def self.precompile_theme_css
- themes = Theme.where('user_selectable OR id = ?', SiteSetting.default_theme_id).pluck(:id, :color_scheme_id)
+ themes =
+ Theme.where("user_selectable OR id = ?", SiteSetting.default_theme_id).pluck(
+ :id,
+ :color_scheme_id,
+ )
color_schemes = ColorScheme.where(user_selectable: true).to_a
color_schemes << ColorScheme.find_by(id: SiteSetting.default_dark_mode_color_scheme_id)
color_schemes << ColorScheme.base
color_schemes = color_schemes.compact.uniq
- targets = [:desktop_theme, :mobile_theme]
+ targets = %i[desktop_theme mobile_theme]
compiled = Set.new
themes.each do |theme_id, color_scheme_id|
@@ -71,18 +81,19 @@ class Stylesheet::Manager
scss_checker = ScssChecker.new(target, manager.theme_ids)
- manager.load_themes(manager.theme_ids).each do |theme|
- next if compiled.include?("#{target}_#{theme.id}")
+ manager
+ .load_themes(manager.theme_ids)
+ .each do |theme|
+ next if compiled.include?("#{target}_#{theme.id}")
- builder = Stylesheet::Manager::Builder.new(
- target: target, theme: theme, manager: manager
- )
+ builder =
+ Stylesheet::Manager::Builder.new(target: target, theme: theme, manager: manager)
- next if theme.component && !scss_checker.has_scss(theme.id)
- $stderr.puts "precompile target: #{target} #{theme.name}"
- builder.compile(force: true)
- compiled << "#{target}_#{theme.id}"
- end
+ next if theme.component && !scss_checker.has_scss(theme.id)
+ $stderr.puts "precompile target: #{target} #{theme.name}"
+ builder.compile(force: true)
+ compiled << "#{target}_#{theme.id}"
+ end
end
theme_color_scheme = ColorScheme.find_by_id(color_scheme_id)
@@ -95,7 +106,7 @@ class Stylesheet::Manager
target: COLOR_SCHEME_STYLESHEET,
theme: theme,
color_scheme: scheme,
- manager: manager
+ manager: manager,
).compile(force: true)
end
@@ -107,14 +118,15 @@ class Stylesheet::Manager
def self.fs_asset_cachebuster
if use_file_hash_for_cachebuster?
- @cachebuster ||= if File.exist?(manifest_full_path)
- File.readlines(manifest_full_path, 'r')[0]
- else
- cachebuster = "#{BASE_COMPILER_VERSION}:#{fs_assets_hash}"
- FileUtils.mkdir_p(MANIFEST_DIR)
- File.open(manifest_full_path, "w") { |f| f.print(cachebuster) }
- cachebuster
- end
+ @cachebuster ||=
+ if File.exist?(manifest_full_path)
+ File.readlines(manifest_full_path, "r")[0]
+ else
+ cachebuster = "#{BASE_COMPILER_VERSION}:#{fs_assets_hash}"
+ FileUtils.mkdir_p(MANIFEST_DIR)
+ File.open(manifest_full_path, "w") { |f| f.print(cachebuster) }
+ cachebuster
+ end
else
"#{BASE_COMPILER_VERSION}:#{max_file_mtime}"
end
@@ -129,7 +141,7 @@ class Stylesheet::Manager
def self.manifest_full_path
path = "#{MANIFEST_DIR}/stylesheet-manifest"
return path if !Rails.env.test?
- "#{path}-test_#{ENV['TEST_ENV_NUMBER'].presence || '0'}"
+ "#{path}-test_#{ENV["TEST_ENV_NUMBER"].presence || "0"}"
end
private_class_method :manifest_full_path
@@ -141,7 +153,7 @@ class Stylesheet::Manager
def self.list_files
globs = [
"#{Rails.root}/app/assets/stylesheets/**/*.*css",
- "#{Rails.root}/app/assets/images/**/*.*"
+ "#{Rails.root}/app/assets/images/**/*.*",
]
Discourse.plugins.each do |plugin|
@@ -168,7 +180,7 @@ class Stylesheet::Manager
def self.cache_fullpath
path = "#{Rails.root}/#{CACHE_PATH}"
return path if !Rails.env.test?
- File.join(path, "test_#{ENV['TEST_ENV_NUMBER'].presence || '0'}")
+ File.join(path, "test_#{ENV["TEST_ENV_NUMBER"].presence || "0"}")
end
attr_reader :theme_ids
@@ -207,10 +219,9 @@ class Stylesheet::Manager
.where(id: to_load_theme_ids)
.includes(:yaml_theme_fields, :theme_settings, :upload_fields, :builder_theme_fields)
.each do |theme|
-
- @themes_cache[theme.id] = theme
- themes << theme
- end
+ @themes_cache[theme.id] = theme
+ themes << theme
+ end
themes
end
@@ -219,35 +230,46 @@ class Stylesheet::Manager
stylesheet_details(target, "all")
end
- def stylesheet_preload_tag(target = :desktop, media = 'all')
+ def stylesheet_preload_tag(target = :desktop, media = "all")
stylesheets = stylesheet_details(target, media)
- stylesheets.map do |stylesheet|
- href = stylesheet[:new_href]
- %[<link href="#{href}" rel="preload" as="style"/>]
- end.join("\n").html_safe
+ stylesheets
+ .map do |stylesheet|
+ href = stylesheet[:new_href]
+ %[<link href="#{href}" rel="preload" as="style"/>]
+ end
+ .join("\n")
+ .html_safe
end
- def stylesheet_link_tag(target = :desktop, media = 'all', preload_callback = nil)
+ def stylesheet_link_tag(target = :desktop, media = "all", preload_callback = nil)
stylesheets = stylesheet_details(target, media)
- stylesheets.map do |stylesheet|
- href = stylesheet[:new_href]
- preload_callback.call(href, 'style') if preload_callback
- theme_id = stylesheet[:theme_id]
- data_theme_id = theme_id ? "data-theme-id=\"#{theme_id}\"" : ""
- theme_name = stylesheet[:theme_name]
- data_theme_name = theme_name ? "data-theme-name=\"#{CGI.escapeHTML(theme_name)}\"" : ""
- %[<link href="#{href}" media="#{media}" rel="stylesheet" data-target="#{target}" #{data_theme_id} #{data_theme_name}/>]
- end.join("\n").html_safe
+ stylesheets
+ .map do |stylesheet|
+ href = stylesheet[:new_href]
+ preload_callback.call(href, "style") if preload_callback
+ theme_id = stylesheet[:theme_id]
+ data_theme_id = theme_id ? "data-theme-id=\"#{theme_id}\"" : ""
+ theme_name = stylesheet[:theme_name]
+ data_theme_name = theme_name ? "data-theme-name=\"#{CGI.escapeHTML(theme_name)}\"" : ""
+ %[<link href="#{href}" media="#{media}" rel="stylesheet" data-target="#{target}" #{data_theme_id} #{data_theme_name}/>]
+ end
+ .join("\n")
+ .html_safe
end
- def stylesheet_details(target = :desktop, media = 'all')
+ def stylesheet_details(target = :desktop, media = "all")
target = target.to_sym
current_hostname = Discourse.current_hostname
is_theme_target = !!(target.to_s =~ THEME_REGEX)
- array_cache_key = is_theme_target ?
- "array_themes_#{@theme_ids.join(",")}_#{target}_#{current_hostname}" :
- "array_#{target}_#{current_hostname}"
+ array_cache_key =
+ (
+ if is_theme_target
+ "array_themes_#{@theme_ids.join(",")}_#{target}_#{current_hostname}"
+ else
+ "array_#{target}_#{current_hostname}"
+ end
+ )
stylesheets = cache[array_cache_key]
return stylesheets if stylesheets.present?
@@ -260,7 +282,12 @@ class Stylesheet::Manager
themes = load_themes(@theme_ids)
themes.each do |theme|
theme_id = theme&.id
- data = { target: target, theme_id: theme_id, theme_name: theme&.name.downcase, remote: theme.remote_theme_id? }
+ data = {
+ target: target,
+ theme_id: theme_id,
+ theme_name: theme&.name.downcase,
+ remote: theme.remote_theme_id?,
+ }
builder = Builder.new(target: target, theme: theme, manager: self)
next if builder.theme&.component && !scss_checker.has_scss(theme_id)
@@ -272,13 +299,10 @@ class Stylesheet::Manager
end
if stylesheets.size > 1
- stylesheets = stylesheets.sort_by do |s|
- [
- s[:remote] ? 0 : 1,
- s[:theme_id] == @theme_id ? 1 : 0,
- s[:theme_name]
- ]
- end
+ stylesheets =
+ stylesheets.sort_by do |s|
+ [s[:remote] ? 0 : 1, s[:theme_id] == @theme_id ? 1 : 0, s[:theme_name]]
+ end
end
else
builder = Builder.new(target: target, manager: self)
@@ -297,14 +321,15 @@ class Stylesheet::Manager
def color_scheme_stylesheet_details(color_scheme_id = nil, media)
theme_id = @theme_id || SiteSetting.default_theme_id
- color_scheme = begin
- ColorScheme.find(color_scheme_id)
- rescue
- # don't load fallback when requesting dark color scheme
- return false if media != "all"
+ color_scheme =
+ begin
+ ColorScheme.find(color_scheme_id)
+ rescue StandardError
+ # don't load fallback when requesting dark color scheme
+ return false if media != "all"
- get_theme(theme_id)&.color_scheme || ColorScheme.base
- end
+ get_theme(theme_id)&.color_scheme || ColorScheme.base
+ end
return false if !color_scheme
@@ -318,12 +343,13 @@ class Stylesheet::Manager
theme = get_theme(theme_id)
- builder = Builder.new(
- target: target,
- theme: get_theme(theme_id),
- color_scheme: color_scheme,
- manager: self
- )
+ builder =
+ Builder.new(
+ target: target,
+ theme: get_theme(theme_id),
+ color_scheme: color_scheme,
+ manager: self,
+ )
builder.compile unless File.exist?(builder.stylesheet_fullpath)
@@ -333,25 +359,25 @@ class Stylesheet::Manager
stylesheet
end
- def color_scheme_stylesheet_preload_tag(color_scheme_id = nil, media = 'all')
+ def color_scheme_stylesheet_preload_tag(color_scheme_id = nil, media = "all")
stylesheet = color_scheme_stylesheet_details(color_scheme_id, media)
- return '' if !stylesheet
+ return "" if !stylesheet
href = stylesheet[:new_href]
%[<link href="#{href}" rel="preload" as="style"/>].html_safe
end
- def color_scheme_stylesheet_link_tag(color_scheme_id = nil, media = 'all', preload_callback = nil)
+ def color_scheme_stylesheet_link_tag(color_scheme_id = nil, media = "all", preload_callback = nil)
stylesheet = color_scheme_stylesheet_details(color_scheme_id, media)
- return '' if !stylesheet
+ return "" if !stylesheet
href = stylesheet[:new_href]
- preload_callback.call(href, 'style') if preload_callback
+ preload_callback.call(href, "style") if preload_callback
- css_class = media == 'all' ? "light-scheme" : "dark-scheme"
+ css_class = media == "all" ? "light-scheme" : "dark-scheme"
%[<link href="#{href}" media="#{media}" rel="stylesheet" class="#{css_class}"/>].html_safe
end
diff --git a/lib/stylesheet/manager/builder.rb b/lib/stylesheet/manager/builder.rb
index 25b1e078a82..47dbae0650c 100644
--- a/lib/stylesheet/manager/builder.rb
+++ b/lib/stylesheet/manager/builder.rb
@@ -15,12 +15,18 @@ class Stylesheet::Manager::Builder
if File.exist?(stylesheet_fullpath)
if !StylesheetCache.where(target: qualified_target, digest: digest).exists?
begin
- source_map = begin
- File.read(source_map_fullpath)
- rescue Errno::ENOENT
- end
-
- StylesheetCache.add(qualified_target, digest, File.read(stylesheet_fullpath), source_map)
+ source_map =
+ begin
+ File.read(source_map_fullpath)
+ rescue Errno::ENOENT
+ end
+
+ StylesheetCache.add(
+ qualified_target,
+ digest,
+ File.read(stylesheet_fullpath),
+ source_map,
+ )
rescue => e
Rails.logger.warn "Completely unexpected error adding contents of '#{stylesheet_fullpath}' to cache #{e}"
end
@@ -30,40 +36,35 @@ class Stylesheet::Manager::Builder
end
rtl = @target.to_s =~ /_rtl$/
- css, source_map = with_load_paths do |load_paths|
- Stylesheet::Compiler.compile_asset(
- @target,
- rtl: rtl,
- theme_id: theme&.id,
- theme_variables: theme&.scss_variables.to_s,
- source_map_file: source_map_url_relative_from_stylesheet,
- color_scheme_id: @color_scheme&.id,
- load_paths: load_paths
- )
- rescue SassC::SyntaxError => e
- if Stylesheet::Importer::THEME_TARGETS.include?(@target.to_s)
- # no special errors for theme, handled in theme editor
- ["", nil]
- elsif @target.to_s == Stylesheet::Manager::COLOR_SCHEME_STYLESHEET
- # log error but do not crash for errors in color definitions SCSS
- Rails.logger.error "SCSS compilation error: #{e.message}"
- ["", nil]
- else
- raise Discourse::ScssError, e.message
+ css, source_map =
+ with_load_paths do |load_paths|
+ Stylesheet::Compiler.compile_asset(
+ @target,
+ rtl: rtl,
+ theme_id: theme&.id,
+ theme_variables: theme&.scss_variables.to_s,
+ source_map_file: source_map_url_relative_from_stylesheet,
+ color_scheme_id: @color_scheme&.id,
+ load_paths: load_paths,
+ )
+ rescue SassC::SyntaxError => e
+ if Stylesheet::Importer::THEME_TARGETS.include?(@target.to_s)
+ # no special errors for theme, handled in theme editor
+ ["", nil]
+ elsif @target.to_s == Stylesheet::Manager::COLOR_SCHEME_STYLESHEET
+ # log error but do not crash for errors in color definitions SCSS
+ Rails.logger.error "SCSS compilation error: #{e.message}"
+ ["", nil]
+ else
+ raise Discourse::ScssError, e.message
+ end
end
- end
FileUtils.mkdir_p(cache_fullpath)
- File.open(stylesheet_fullpath, "w") do |f|
- f.puts css
- end
+ File.open(stylesheet_fullpath, "w") { |f| f.puts css }
- if source_map.present?
- File.open(source_map_fullpath, "w") do |f|
- f.puts source_map
- end
- end
+ File.open(source_map_fullpath, "w") { |f| f.puts source_map } if source_map.present?
begin
StylesheetCache.add(qualified_target, digest, css, source_map)
@@ -146,20 +147,21 @@ class Stylesheet::Manager::Builder
end
def scheme_slug
- Slug.for(ActiveSupport::Inflector.transliterate(@color_scheme.name), 'scheme')
+ Slug.for(ActiveSupport::Inflector.transliterate(@color_scheme.name), "scheme")
end
# digest encodes the things that trigger a recompile
def digest
- @digest ||= begin
- if is_theme?
- theme_digest
- elsif is_color_scheme?
- color_scheme_digest
- else
- default_digest
+ @digest ||=
+ begin
+ if is_theme?
+ theme_digest
+ elsif is_color_scheme?
+ color_scheme_digest
+ else
+ default_digest
+ end
end
- end
end
def with_load_paths
@@ -171,7 +173,7 @@ class Stylesheet::Manager::Builder
end
def scss_digest
- if [:mobile_theme, :desktop_theme].include?(@target)
+ if %i[mobile_theme desktop_theme].include?(@target)
resolve_baked_field(@target.to_s.sub("_theme", ""), :scss)
elsif @target == :embedded_theme
resolve_baked_field(:common, :embedded_scss)
@@ -181,7 +183,10 @@ class Stylesheet::Manager::Builder
end
def theme_digest
- Digest::SHA1.hexdigest(scss_digest.to_s + color_scheme_digest.to_s + settings_digest + uploads_digest + current_hostname)
+ Digest::SHA1.hexdigest(
+ scss_digest.to_s + color_scheme_digest.to_s + settings_digest + uploads_digest +
+ current_hostname,
+ )
end
# this protects us from situations where new versions of a plugin removed a file
@@ -205,13 +210,15 @@ class Stylesheet::Manager::Builder
[@manager.get_theme(theme.id)]
end
- fields = themes.each_with_object([]) do |theme, array|
- array.concat(theme.yaml_theme_fields.map(&:updated_at))
- end
+ fields =
+ themes.each_with_object([]) do |theme, array|
+ array.concat(theme.yaml_theme_fields.map(&:updated_at))
+ end
- settings = themes.each_with_object([]) do |theme, array|
- array.concat(theme.theme_settings.map(&:updated_at))
- end
+ settings =
+ themes.each_with_object([]) do |theme, array|
+ array.concat(theme.theme_settings.map(&:updated_at))
+ end
timestamps = fields.concat(settings).map!(&:to_f).sort!.join(",")
@@ -221,9 +228,7 @@ class Stylesheet::Manager::Builder
def uploads_digest
sha1s = []
- (theme&.upload_fields || []).map do |upload_field|
- sha1s << upload_field.upload&.sha1
- end
+ (theme&.upload_fields || []).map { |upload_field| sha1s << upload_field.upload&.sha1 }
Digest::SHA1.hexdigest(sha1s.compact.sort!.join("\n"))
end
@@ -235,20 +240,20 @@ class Stylesheet::Manager::Builder
def color_scheme_digest
cs = @color_scheme || theme&.color_scheme
- categories_updated = Stylesheet::Manager.cache.defer_get_set("categories_updated") do
- Category
- .where("uploaded_background_id IS NOT NULL")
- .pluck(:updated_at)
- .map(&:to_i)
- .sum
- end
+ categories_updated =
+ Stylesheet::Manager
+ .cache
+ .defer_get_set("categories_updated") do
+ Category.where("uploaded_background_id IS NOT NULL").pluck(:updated_at).map(&:to_i).sum
+ end
fonts = "#{SiteSetting.base_font}-#{SiteSetting.heading_font}"
digest_string = "#{current_hostname}-"
if cs || categories_updated > 0
theme_color_defs = resolve_baked_field(:common, :color_definitions)
- digest_string += "#{RailsMultisite::ConnectionManagement.current_db}-#{cs&.id}-#{cs&.version}-#{theme_color_defs}-#{Stylesheet::Manager.fs_asset_cachebuster}-#{categories_updated}-#{fonts}"
+ digest_string +=
+ "#{RailsMultisite::ConnectionManagement.current_db}-#{cs&.id}-#{cs&.version}-#{theme_color_defs}-#{Stylesheet::Manager.fs_asset_cachebuster}-#{categories_updated}-#{fonts}"
else
digest_string += "defaults-#{Stylesheet::Manager.fs_asset_cachebuster}-#{fonts}"
@@ -274,17 +279,21 @@ class Stylesheet::Manager::Builder
baked_fields = []
targets = [Theme.targets[target.to_sym], Theme.targets[:common]]
- @manager.load_themes(theme_ids).each do |theme|
- theme.builder_theme_fields.each do |theme_field|
- if theme_field.name == name.to_s && targets.include?(theme_field.target_id)
- baked_fields << theme_field
+ @manager
+ .load_themes(theme_ids)
+ .each do |theme|
+ theme.builder_theme_fields.each do |theme_field|
+ if theme_field.name == name.to_s && targets.include?(theme_field.target_id)
+ baked_fields << theme_field
+ end
end
end
- end
- baked_fields.map do |f|
- f.ensure_baked!
- f.value_baked || f.value
- end.join("\n")
+ baked_fields
+ .map do |f|
+ f.ensure_baked!
+ f.value_baked || f.value
+ end
+ .join("\n")
end
end
diff --git a/lib/stylesheet/manager/scss_checker.rb b/lib/stylesheet/manager/scss_checker.rb
index 117b4ccfe1e..6f19bc10f3e 100644
--- a/lib/stylesheet/manager/scss_checker.rb
+++ b/lib/stylesheet/manager/scss_checker.rb
@@ -13,23 +13,27 @@ class Stylesheet::Manager::ScssChecker
private
def get_themes_with_scss
- @themes_with_scss ||= begin
- theme_target = @target.to_sym
- theme_target = :mobile if theme_target == :mobile_theme
- theme_target = :desktop if theme_target == :desktop_theme
- name = @target == :embedded_theme ? :embedded_scss : :scss
+ @themes_with_scss ||=
+ begin
+ theme_target = @target.to_sym
+ theme_target = :mobile if theme_target == :mobile_theme
+ theme_target = :desktop if theme_target == :desktop_theme
+ name = @target == :embedded_theme ? :embedded_scss : :scss
- results = Theme
- .where(id: @theme_ids)
- .left_joins(:theme_fields)
- .where(theme_fields: {
- target_id: [Theme.targets[theme_target], Theme.targets[:common]],
- name: name
- })
- .group(:id)
- .size
+ results =
+ Theme
+ .where(id: @theme_ids)
+ .left_joins(:theme_fields)
+ .where(
+ theme_fields: {
+ target_id: [Theme.targets[theme_target], Theme.targets[:common]],
+ name: name,
+ },
+ )
+ .group(:id)
+ .size
- results
- end
+ results
+ end
end
end
diff --git a/lib/stylesheet/watcher.rb b/lib/stylesheet/watcher.rb
index cd7d11caf0d..a2c8189e83b 100644
--- a/lib/stylesheet/watcher.rb
+++ b/lib/stylesheet/watcher.rb
@@ -1,10 +1,9 @@
# frozen_string_literal: true
-require 'listen'
+require "listen"
module Stylesheet
class Watcher
-
def self.watch(paths = nil)
watcher = new(paths)
watcher.start
@@ -22,7 +21,7 @@ module Stylesheet
@default_paths = ["app/assets/stylesheets"]
Discourse.plugins.each do |plugin|
if plugin.path.to_s.include?(Rails.root.to_s)
- @default_paths << File.dirname(plugin.path).sub(Rails.root.to_s, '').sub(/^\//, '')
+ @default_paths << File.dirname(plugin.path).sub(Rails.root.to_s, "").sub(%r{^/}, "")
else
# if plugin doesn’t seem to be in our app, consider it as outside of the app
# and ignore it
@@ -35,9 +34,7 @@ module Stylesheet
def start
Thread.new do
begin
- while true
- worker_loop
- end
+ worker_loop while true
rescue => e
STDERR.puts "CSS change notifier crashed \n#{e}"
start
@@ -45,45 +42,45 @@ module Stylesheet
end
listener_opts = { ignore: /xxxx/, only: /\.(css|scss)$/ }
- listener_opts[:force_polling] = true if ENV['FORCE_POLLING']
+ listener_opts[:force_polling] = true if ENV["FORCE_POLLING"]
Thread.new do
begin
- plugins_paths = Dir.glob("#{Rails.root}/plugins/*").map do |file|
- if File.symlink?(file)
- File.expand_path(File.readlink(file), "#{Rails.root}/plugins")
- else
- file
- end
- end.compact
-
- listener = Listen.to(*@paths, listener_opts) do |modified, added, _|
- paths = [modified, added].flatten
- paths.compact!
- paths.map! do |long|
- plugin_name = nil
- plugins_paths.each do |plugin_path|
- if long.include?("#{plugin_path}/")
- plugin_name = File.basename(plugin_path)
- break
+ plugins_paths =
+ Dir
+ .glob("#{Rails.root}/plugins/*")
+ .map do |file|
+ if File.symlink?(file)
+ File.expand_path(File.readlink(file), "#{Rails.root}/plugins")
+ else
+ file
end
end
+ .compact
+
+ listener =
+ Listen.to(*@paths, listener_opts) do |modified, added, _|
+ paths = [modified, added].flatten
+ paths.compact!
+ paths.map! do |long|
+ plugin_name = nil
+ plugins_paths.each do |plugin_path|
+ if long.include?("#{plugin_path}/")
+ plugin_name = File.basename(plugin_path)
+ break
+ end
+ end
- target = nil
- target_match = long.match(/admin|desktop|mobile|publish|wizard|wcag|color_definitions/)
- if target_match&.length
- target = target_match[0]
+ target = nil
+ target_match =
+ long.match(/admin|desktop|mobile|publish|wizard|wcag|color_definitions/)
+ target = target_match[0] if target_match&.length
+
+ { basename: File.basename(long), target: target, plugin_name: plugin_name }
end
- {
- basename: File.basename(long),
- target: target,
- plugin_name: plugin_name
- }
+ process_change(paths)
end
-
- process_change(paths)
- end
rescue => e
STDERR.puts "Failed to listen for CSS changes: \n#{e}"
end
@@ -98,34 +95,32 @@ module Stylesheet
return
end
- targets = target ? [target] : ["desktop", "mobile", "admin"]
+ targets = target ? [target] : %w[desktop mobile admin]
Stylesheet::Manager.clear_core_cache!(targets)
- message = targets.map! do |name|
- Stylesheet::Manager.new.stylesheet_data(name.to_sym)
- end.flatten!
- MessageBus.publish '/file-change', message
+ message =
+ targets.map! { |name| Stylesheet::Manager.new.stylesheet_data(name.to_sym) }.flatten!
+ MessageBus.publish "/file-change", message
end
def plugin_assets_refresh(plugin_name, target)
Stylesheet::Manager.clear_plugin_cache!(plugin_name)
targets = []
if target.present?
- targets.push("#{plugin_name}_#{target.to_s}") if DiscoursePluginRegistry.stylesheets_exists?(plugin_name, target.to_sym)
+ if DiscoursePluginRegistry.stylesheets_exists?(plugin_name, target.to_sym)
+ targets.push("#{plugin_name}_#{target.to_s}")
+ end
else
targets.push(plugin_name)
end
- message = targets.map! do |name|
- Stylesheet::Manager.new.stylesheet_data(name.to_sym)
- end.flatten!
- MessageBus.publish '/file-change', message
+ message =
+ targets.map! { |name| Stylesheet::Manager.new.stylesheet_data(name.to_sym) }.flatten!
+ MessageBus.publish "/file-change", message
end
def worker_loop
path = @queue.pop
- while @queue.length > 0
- @queue.pop
- end
+ @queue.pop while @queue.length > 0
if path[:plugin_name]
plugin_assets_refresh(path[:plugin_name], path[:target])
@@ -135,10 +130,7 @@ module Stylesheet
end
def process_change(paths)
- paths.each do |path|
- @queue.push path
- end
+ paths.each { |path| @queue.push path }
end
-
end
end
diff --git a/lib/suggested_topics_builder.rb b/lib/suggested_topics_builder.rb
index 273289671af..76599a32738 100644
--- a/lib/suggested_topics_builder.rb
+++ b/lib/suggested_topics_builder.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class SuggestedTopicsBuilder
-
attr_reader :excluded_topic_ids
def initialize(topic)
@@ -12,14 +11,11 @@ class SuggestedTopicsBuilder
end
def add_results(results, priority = :low)
-
# WARNING .blank? will execute an Active Record query
return unless results
# Only add results if we don't have those topic ids already
- results = results
- .where('topics.id NOT IN (?)', @excluded_topic_ids)
- .where(visible: true)
+ results = results.where("topics.id NOT IN (?)", @excluded_topic_ids).where(visible: true)
# If limit suggested to category is enabled, restrict to that category
if @category_id && SiteSetting.limit_suggested_to_category?
@@ -30,7 +26,6 @@ class SuggestedTopicsBuilder
results.reject! { |topic| @category_topic_ids.include?(topic.id) }
unless results.empty?
-
# protect against dupes
temp = results
results = []
@@ -48,11 +43,11 @@ class SuggestedTopicsBuilder
def splice_results(results, priority)
if priority == :ultra_high
@results.insert 0, *results
-
- elsif @category_id && priority == :high
+ elsif @category_id && priority == :high
# Topics from category @category_id need to be first in the list, all others after.
other_category_index = @results.index { |r| r.category_id != @category_id }
- category_results, other_category_results = results.partition { |r| r.category_id == @category_id }
+ category_results, other_category_results =
+ results.partition { |r| r.category_id == @category_id }
if other_category_index
@results.insert other_category_index, *category_results
@@ -84,5 +79,4 @@ class SuggestedTopicsBuilder
def size
@results.size
end
-
end
diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rb
index b82e5451080..afb62d54574 100644
--- a/lib/svg_sprite.rb
+++ b/lib/svg_sprite.rb
@@ -1,229 +1,232 @@
# frozen_string_literal: true
module SvgSprite
- SVG_ICONS ||= Set.new([
- "adjust",
- "address-book",
- "ambulance",
- "anchor",
- "angle-double-down",
- "angle-double-up",
- "angle-double-right",
- "angle-double-left",
- "angle-down",
- "angle-right",
- "angle-up",
- "archive",
- "arrow-down",
- "arrow-left",
- "arrow-up",
- "arrows-alt-h",
- "arrows-alt-v",
- "at",
- "asterisk",
- "backward",
- "ban",
- "bars",
- "bed",
- "bell",
- "bell-slash",
- "bold",
- "book",
- "book-reader",
- "bookmark",
- "briefcase",
- "calendar-alt",
- "caret-down",
- "caret-left",
- "caret-right",
- "caret-up",
- "certificate",
- "chart-bar",
- "chart-pie",
- "check",
- "check-circle",
- "check-square",
- "chevron-down",
- "chevron-left",
- "chevron-right",
- "chevron-up",
- "circle",
- "code",
- "cog",
- "columns",
- "comment",
- "compress",
- "copy",
- "crosshairs",
- "cube",
- "desktop",
- "discourse-amazon",
- "discourse-bell-exclamation",
- "discourse-bell-one",
- "discourse-bell-slash",
- "discourse-bookmark-clock",
- "discourse-compress",
- "discourse-emojis",
- "discourse-expand",
- "discourse-other-tab",
- "download",
- "ellipsis-h",
- "ellipsis-v",
- "envelope",
- "envelope-square",
- "exchange-alt",
- "exclamation-circle",
- "exclamation-triangle",
- "external-link-alt",
- "fab-android",
- "fab-apple",
- "fab-chrome",
- "fab-discord",
- "fab-discourse",
- "fab-facebook-square",
- "fab-facebook",
- "fab-github",
- "fab-instagram",
- "fab-linux",
- "fab-twitter",
- "fab-twitter-square",
- "fab-wikipedia-w",
- "fab-windows",
- "far-bell",
- "far-bell-slash",
- "far-calendar-plus",
- "far-chart-bar",
- "far-check-square",
- "far-circle",
- "far-clipboard",
- "far-clock",
- "far-comment",
- "far-comments",
- "far-copyright",
- "far-dot-circle",
- "far-edit",
- "far-envelope",
- "far-eye",
- "far-eye-slash",
- "far-file-alt",
- "far-frown",
- "far-heart",
- "far-image",
- "far-list-alt",
- "far-meh",
- "far-moon",
- "far-smile",
- "far-square",
- "far-star",
- "far-sun",
- "far-thumbs-down",
- "far-thumbs-up",
- "far-trash-alt",
- "fast-backward",
- "fast-forward",
- "file",
- "file-alt",
- "filter",
- "flag",
- "folder",
- "folder-open",
- "forward",
- "gavel",
- "gift",
- "globe",
- "globe-americas",
- "hand-point-right",
- "hands-helping",
- "heart",
- "history",
- "home",
- "hourglass-start",
- "id-card",
- "image",
- "inbox",
- "info-circle",
- "italic",
- "key",
- "keyboard",
- "layer-group",
- "link",
- "list",
- "list-ol",
- "list-ul",
- "lock",
- "magic",
- "map-marker-alt",
- "microphone-slash",
- "minus",
- "minus-circle",
- "mobile-alt",
- "moon",
- "paint-brush",
- "paper-plane",
- "pause",
- "pencil-alt",
- "play",
- "plug",
- "plus",
- "plus-circle",
- "plus-square",
- "power-off",
- "puzzle-piece",
- "question",
- "question-circle",
- "quote-left",
- "quote-right",
- "random",
- "redo",
- "reply",
- "rocket",
- "search",
- "share",
- "shield-alt",
- "sign-in-alt",
- "sign-out-alt",
- "signal",
- "sliders-h",
- "square-full",
- "star",
- "step-backward",
- "step-forward",
- "stream",
- "sync-alt",
- "sync",
- "table",
- "tag",
- "tags",
- "tasks",
- "thermometer-three-quarters",
- "thumbs-down",
- "thumbs-up",
- "thumbtack",
- "times",
- "times-circle",
- "toggle-off",
- "toggle-on",
- "trash-alt",
- "undo",
- "unlink",
- "unlock",
- "unlock-alt",
- "upload",
- "user",
- "user-cog",
- "user-edit",
- "user-friends",
- "user-plus",
- "user-secret",
- "user-shield",
- "user-times",
- "users",
- "wrench",
- "spinner",
- "tippy-rounded-arrow"
- ])
-
- FA_ICON_MAP = { 'far fa-' => 'far-', 'fab fa-' => 'fab-', 'fas fa-' => '', 'fa-' => '' }
+ SVG_ICONS ||=
+ Set.new(
+ %w[
+ adjust
+ address-book
+ ambulance
+ anchor
+ angle-double-down
+ angle-double-up
+ angle-double-right
+ angle-double-left
+ angle-down
+ angle-right
+ angle-up
+ archive
+ arrow-down
+ arrow-left
+ arrow-up
+ arrows-alt-h
+ arrows-alt-v
+ at
+ asterisk
+ backward
+ ban
+ bars
+ bed
+ bell
+ bell-slash
+ bold
+ book
+ book-reader
+ bookmark
+ briefcase
+ calendar-alt
+ caret-down
+ caret-left
+ caret-right
+ caret-up
+ certificate
+ chart-bar
+ chart-pie
+ check
+ check-circle
+ check-square
+ chevron-down
+ chevron-left
+ chevron-right
+ chevron-up
+ circle
+ code
+ cog
+ columns
+ comment
+ compress
+ copy
+ crosshairs
+ cube
+ desktop
+ discourse-amazon
+ discourse-bell-exclamation
+ discourse-bell-one
+ discourse-bell-slash
+ discourse-bookmark-clock
+ discourse-compress
+ discourse-emojis
+ discourse-expand
+ discourse-other-tab
+ download
+ ellipsis-h
+ ellipsis-v
+ envelope
+ envelope-square
+ exchange-alt
+ exclamation-circle
+ exclamation-triangle
+ external-link-alt
+ fab-android
+ fab-apple
+ fab-chrome
+ fab-discord
+ fab-discourse
+ fab-facebook-square
+ fab-facebook
+ fab-github
+ fab-instagram
+ fab-linux
+ fab-twitter
+ fab-twitter-square
+ fab-wikipedia-w
+ fab-windows
+ far-bell
+ far-bell-slash
+ far-calendar-plus
+ far-chart-bar
+ far-check-square
+ far-circle
+ far-clipboard
+ far-clock
+ far-comment
+ far-comments
+ far-copyright
+ far-dot-circle
+ far-edit
+ far-envelope
+ far-eye
+ far-eye-slash
+ far-file-alt
+ far-frown
+ far-heart
+ far-image
+ far-list-alt
+ far-meh
+ far-moon
+ far-smile
+ far-square
+ far-star
+ far-sun
+ far-thumbs-down
+ far-thumbs-up
+ far-trash-alt
+ fast-backward
+ fast-forward
+ file
+ file-alt
+ filter
+ flag
+ folder
+ folder-open
+ forward
+ gavel
+ gift
+ globe
+ globe-americas
+ hand-point-right
+ hands-helping
+ heart
+ history
+ home
+ hourglass-start
+ id-card
+ image
+ inbox
+ info-circle
+ italic
+ key
+ keyboard
+ layer-group
+ link
+ list
+ list-ol
+ list-ul
+ lock
+ magic
+ map-marker-alt
+ microphone-slash
+ minus
+ minus-circle
+ mobile-alt
+ moon
+ paint-brush
+ paper-plane
+ pause
+ pencil-alt
+ play
+ plug
+ plus
+ plus-circle
+ plus-square
+ power-off
+ puzzle-piece
+ question
+ question-circle
+ quote-left
+ quote-right
+ random
+ redo
+ reply
+ rocket
+ search
+ share
+ shield-alt
+ sign-in-alt
+ sign-out-alt
+ signal
+ sliders-h
+ square-full
+ star
+ step-backward
+ step-forward
+ stream
+ sync-alt
+ sync
+ table
+ tag
+ tags
+ tasks
+ thermometer-three-quarters
+ thumbs-down
+ thumbs-up
+ thumbtack
+ times
+ times-circle
+ toggle-off
+ toggle-on
+ trash-alt
+ undo
+ unlink
+ unlock
+ unlock-alt
+ upload
+ user
+ user-cog
+ user-edit
+ user-friends
+ user-plus
+ user-secret
+ user-shield
+ user-times
+ users
+ wrench
+ spinner
+ tippy-rounded-arrow
+ ],
+ )
+
+ FA_ICON_MAP = { "far fa-" => "far-", "fab fa-" => "fab-", "fas fa-" => "", "fa-" => "" }
CORE_SVG_SPRITES = Dir.glob("#{Rails.root}/vendor/assets/svg-icons/**/*.svg")
@@ -236,47 +239,56 @@ module SvgSprite
end
def self.custom_svg_sprites(theme_id)
- get_set_cache("custom_svg_sprites_#{Theme.transform_ids(theme_id).join(',')}") do
+ get_set_cache("custom_svg_sprites_#{Theme.transform_ids(theme_id).join(",")}") do
plugin_paths = []
- Discourse.plugins.map { |plugin| File.dirname(plugin.path) }.each do |path|
- plugin_paths << "#{path}/svg-icons/*.svg"
- end
+ Discourse
+ .plugins
+ .map { |plugin| File.dirname(plugin.path) }
+ .each { |path| plugin_paths << "#{path}/svg-icons/*.svg" }
custom_sprite_paths = Dir.glob(plugin_paths)
- custom_sprites = custom_sprite_paths.map do |path|
- if File.exist?(path)
- {
- filename: "#{File.basename(path, ".svg")}",
- sprite: File.read(path)
- }
+ custom_sprites =
+ custom_sprite_paths.map do |path|
+ if File.exist?(path)
+ { filename: "#{File.basename(path, ".svg")}", sprite: File.read(path) }
+ end
end
- end
if theme_id.present?
- ThemeField.where(type_id: ThemeField.types[:theme_upload_var], name: THEME_SPRITE_VAR_NAME, theme_id: Theme.transform_ids(theme_id))
- .pluck(:upload_id, :theme_id).each do |upload_id, child_theme_id|
-
- begin
- upload = Upload.find(upload_id)
- custom_sprites << {
- filename: "theme_#{theme_id}_#{upload_id}.svg",
- sprite: upload.content
- }
- rescue => e
- name = Theme.find(child_theme_id).name rescue nil
- Discourse.warn_exception(e, message: "#{name} theme contains a corrupt svg upload")
+ ThemeField
+ .where(
+ type_id: ThemeField.types[:theme_upload_var],
+ name: THEME_SPRITE_VAR_NAME,
+ theme_id: Theme.transform_ids(theme_id),
+ )
+ .pluck(:upload_id, :theme_id)
+ .each do |upload_id, child_theme_id|
+ begin
+ upload = Upload.find(upload_id)
+ custom_sprites << {
+ filename: "theme_#{theme_id}_#{upload_id}.svg",
+ sprite: upload.content,
+ }
+ rescue => e
+ name =
+ begin
+ Theme.find(child_theme_id).name
+ rescue StandardError
+ nil
+ end
+ Discourse.warn_exception(e, message: "#{name} theme contains a corrupt svg upload")
+ end
end
-
- end
end
custom_sprites
end
end
def self.all_icons(theme_id = nil)
- get_set_cache("icons_#{Theme.transform_ids(theme_id).join(',')}") do
- Set.new()
+ get_set_cache("icons_#{Theme.transform_ids(theme_id).join(",")}") do
+ Set
+ .new()
.merge(settings_icons)
.merge(plugin_icons)
.merge(badge_icons)
@@ -291,7 +303,7 @@ module SvgSprite
end
def self.version(theme_id = nil)
- get_set_cache("version_#{Theme.transform_ids(theme_id).join(',')}") do
+ get_set_cache("version_#{Theme.transform_ids(theme_id).join(",")}") do
Digest::SHA1.hexdigest(bundle(theme_id))
end
end
@@ -309,96 +321,101 @@ module SvgSprite
CORE_SVG_SPRITES.each do |path|
if File.exist?(path)
- sprites << {
- filename: "#{File.basename(path, ".svg")}",
- sprite: File.read(path)
- }
+ sprites << { filename: "#{File.basename(path, ".svg")}", sprite: File.read(path) }
end
end
- if theme_id.present?
- sprites = sprites + custom_svg_sprites(theme_id)
- end
+ sprites = sprites + custom_svg_sprites(theme_id) if theme_id.present?
sprites
end
def self.core_svgs
- @core_svgs ||= begin
- symbols = {}
-
- CORE_SVG_SPRITES.each do |filename|
- svg_filename = "#{File.basename(filename, ".svg")}"
-
- Nokogiri::XML(File.open(filename)) do |config|
- config.options = Nokogiri::XML::ParseOptions::NOBLANKS
- end.css('symbol').each do |sym|
- icon_id = prepare_symbol(sym, svg_filename)
- sym.attributes['id'].value = icon_id
- symbols[icon_id] = sym.to_xml
+ @core_svgs ||=
+ begin
+ symbols = {}
+
+ CORE_SVG_SPRITES.each do |filename|
+ svg_filename = "#{File.basename(filename, ".svg")}"
+
+ Nokogiri
+ .XML(File.open(filename)) do |config|
+ config.options = Nokogiri::XML::ParseOptions::NOBLANKS
+ end
+ .css("symbol")
+ .each do |sym|
+ icon_id = prepare_symbol(sym, svg_filename)
+ sym.attributes["id"].value = icon_id
+ symbols[icon_id] = sym.to_xml
+ end
end
- end
- symbols
- end
+ symbols
+ end
end
def self.bundle(theme_id = nil)
icons = all_icons(theme_id)
- svg_subset = """<!--
+ svg_subset =
+ "" \
+ "<!--
Discourse SVG subset of Font Awesome Free by @fontawesome - https://fontawesome.com
License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
-->
<svg xmlns='http://www.w3.org/2000/svg' style='display: none;'>
-""".dup
+" \
+ "".dup
- core_svgs.each do |icon_id, sym|
- if icons.include?(icon_id)
- svg_subset << sym
- end
- end
+ core_svgs.each { |icon_id, sym| svg_subset << sym if icons.include?(icon_id) }
custom_svg_sprites(theme_id).each do |item|
begin
- svg_file = Nokogiri::XML(item[:sprite]) do |config|
- config.options = Nokogiri::XML::ParseOptions::NOBLANKS
- end
+ svg_file =
+ Nokogiri.XML(item[:sprite]) do |config|
+ config.options = Nokogiri::XML::ParseOptions::NOBLANKS
+ end
rescue => e
- Rails.logger.warn("Bad XML in custom sprite in theme with ID=#{theme_id}. Error info: #{e.inspect}")
+ Rails.logger.warn(
+ "Bad XML in custom sprite in theme with ID=#{theme_id}. Error info: #{e.inspect}",
+ )
end
next if !svg_file
- svg_file.css("symbol").each do |sym|
- icon_id = prepare_symbol(sym, item[:filename])
+ svg_file
+ .css("symbol")
+ .each do |sym|
+ icon_id = prepare_symbol(sym, item[:filename])
- if icons.include? icon_id
- sym.attributes['id'].value = icon_id
- sym.css('title').each(&:remove)
- svg_subset << sym.to_xml
+ if icons.include? icon_id
+ sym.attributes["id"].value = icon_id
+ sym.css("title").each(&:remove)
+ svg_subset << sym.to_xml
+ end
end
- end
end
- svg_subset << '</svg>'
+ svg_subset << "</svg>"
end
def self.search(searched_icon)
searched_icon = process(searched_icon.dup)
sprite_sources(SiteSetting.default_theme_id).each do |item|
- svg_file = Nokogiri::XML(item[:sprite])
+ svg_file = Nokogiri.XML(item[:sprite])
- svg_file.css('symbol').each do |sym|
- icon_id = prepare_symbol(sym, item[:filename])
+ svg_file
+ .css("symbol")
+ .each do |sym|
+ icon_id = prepare_symbol(sym, item[:filename])
- if searched_icon == icon_id
- sym.attributes['id'].value = icon_id
- sym.css('title').each(&:remove)
- return sym.to_xml
+ if searched_icon == icon_id
+ sym.attributes["id"].value = icon_id
+ sym.css("title").each(&:remove)
+ return sym.to_xml
+ end
end
- end
end
false
@@ -408,16 +425,18 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
results = Set.new
sprite_sources(SiteSetting.default_theme_id).each do |item|
- svg_file = Nokogiri::XML(item[:sprite])
-
- svg_file.css('symbol').each do |sym|
- icon_id = prepare_symbol(sym, item[:filename])
- if keyword.empty? || icon_id.include?(keyword)
- sym.attributes['id'].value = icon_id
- sym.css('title').each(&:remove)
- results.add(id: icon_id, symbol: sym.to_xml)
+ svg_file = Nokogiri.XML(item[:sprite])
+
+ svg_file
+ .css("symbol")
+ .each do |sym|
+ icon_id = prepare_symbol(sym, item[:filename])
+ if keyword.empty? || icon_id.include?(keyword)
+ sym.attributes["id"].value = icon_id
+ sym.css("title").each(&:remove)
+ results.add(id: icon_id, symbol: sym.to_xml)
+ end
end
- end
end
results.sort_by { |icon| icon[:id] }
@@ -428,7 +447,7 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
get_set_cache("raw_svg_#{name}") do
symbol = search(name)
break "" unless symbol
- symbol = Nokogiri::XML(symbol).children.first
+ symbol = Nokogiri.XML(symbol).children.first
symbol.name = "svg"
<<~HTML
<svg class="fa d-icon svg-icon svg-node" aria-hidden="true">#{symbol}</svg>
@@ -441,13 +460,13 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
end
def self.prepare_symbol(symbol, svg_filename = nil)
- icon_id = symbol.attr('id')
+ icon_id = symbol.attr("id")
case svg_filename
when "regular"
- icon_id = icon_id.prepend('far-')
+ icon_id = icon_id.prepend("far-")
when "brands"
- icon_id = icon_id.prepend('fab-')
+ icon_id = icon_id.prepend("fab-")
end
icon_id
@@ -459,9 +478,7 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
site_setting_icons = []
SiteSetting.settings_hash.select do |key, value|
- if key.to_s.include?("_icon") && String === value
- site_setting_icons |= value.split('|')
- end
+ site_setting_icons |= value.split("|") if key.to_s.include?("_icon") && String === value
end
site_setting_icons
@@ -473,15 +490,11 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
end
def self.badge_icons
- get_set_cache("badge_icons") do
- Badge.pluck(:icon).uniq
- end
+ get_set_cache("badge_icons") { Badge.pluck(:icon).uniq }
end
def self.group_icons
- get_set_cache("group_icons") do
- Group.pluck(:flair_icon).uniq
- end
+ get_set_cache("group_icons") { Group.pluck(:flair_icon).uniq }
end
def self.theme_icons(theme_id)
@@ -491,13 +504,16 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
theme_ids = Theme.transform_ids(theme_id)
# Need to load full records for default values
- Theme.where(id: theme_ids).each do |theme|
- _settings = theme.cached_settings.each do |key, value|
- if key.to_s.include?("_icon") && String === value
- theme_icon_settings |= value.split('|')
- end
+ Theme
+ .where(id: theme_ids)
+ .each do |theme|
+ _settings =
+ theme.cached_settings.each do |key, value|
+ if key.to_s.include?("_icon") && String === value
+ theme_icon_settings |= value.split("|")
+ end
+ end
end
- end
theme_icon_settings |= ThemeModifierHelper.new(theme_ids: theme_ids).svg_icons
@@ -508,10 +524,10 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
# Automatically register icons in sprites added via themes or plugins
icons = []
custom_svg_sprites(theme_id).each do |item|
- svg_file = Nokogiri::XML(item[:sprite])
- svg_file.css('symbol').each do |sym|
- icons << sym.attributes['id'].value if sym.attributes['id'].present?
- end
+ svg_file = Nokogiri.XML(item[:sprite])
+ svg_file
+ .css("symbol")
+ .each { |sym| icons << sym.attributes["id"].value if sym.attributes["id"].present? }
end
icons
end
@@ -527,6 +543,6 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL
end
def self.cache
- @cache ||= DistributedCache.new('svg_sprite')
+ @cache ||= DistributedCache.new("svg_sprite")
end
end
diff --git a/lib/system_message.rb b/lib/system_message.rb
index 48626244ad4..53ce825c800 100644
--- a/lib/system_message.rb
+++ b/lib/system_message.rb
@@ -3,7 +3,6 @@
# Handle sending a message to a user from the system.
class SystemMessage
-
def self.create(recipient, type, params = {})
self.new(recipient).create(type, params)
end
@@ -25,14 +24,29 @@ class SystemMessage
params = defaults.merge(params)
- title = params[:message_title] || I18n.with_locale(@recipient.effective_locale) { I18n.t("system_messages.#{type}.subject_template", params) }
- raw = params[:message_raw] || I18n.with_locale(@recipient.effective_locale) { I18n.t("system_messages.#{type}.text_body_template", params) }
+ title =
+ params[:message_title] ||
+ I18n.with_locale(@recipient.effective_locale) do
+ I18n.t("system_messages.#{type}.subject_template", params)
+ end
+ raw =
+ params[:message_raw] ||
+ I18n.with_locale(@recipient.effective_locale) do
+ I18n.t("system_messages.#{type}.text_body_template", params)
+ end
if from_system
user = Discourse.system_user
else
user = Discourse.site_contact_user
- target_group_names = Group.exists?(name: SiteSetting.site_contact_group_name) ? SiteSetting.site_contact_group_name : nil
+ target_group_names =
+ (
+ if Group.exists?(name: SiteSetting.site_contact_group_name)
+ SiteSetting.site_contact_group_name
+ else
+ nil
+ end
+ )
end
post_creator_args = [
@@ -44,10 +58,16 @@ class SystemMessage
target_group_names: target_group_names,
subtype: TopicSubtype.system_message,
skip_validations: true,
- post_alert_options: params[:post_alert_options]
+ post_alert_options: params[:post_alert_options],
]
- DiscourseEvent.trigger(:before_system_message_sent, message_type: type, recipient: @recipient, post_creator_args: post_creator_args, params: method_params)
+ DiscourseEvent.trigger(
+ :before_system_message_sent,
+ message_type: type,
+ recipient: @recipient,
+ post_creator_args: post_creator_args,
+ params: method_params,
+ )
creator = PostCreator.new(*post_creator_args)
@@ -55,9 +75,7 @@ class SystemMessage
DiscourseEvent.trigger(:system_message_sent, post: post, message_type: type)
- if creator.errors.present?
- raise StandardError, creator.errors.full_messages.join(" ")
- end
+ raise StandardError, creator.errors.full_messages.join(" ") if creator.errors.present?
unless from_system
UserArchivedMessage.create!(user: Discourse.site_contact_user, topic: post.topic)
@@ -71,10 +89,12 @@ class SystemMessage
site_name: SiteSetting.title,
username: @recipient.username,
user_preferences_url: "#{@recipient.full_url}/preferences",
- new_user_tips: I18n.with_locale(@recipient.effective_locale) { I18n.t('system_messages.usage_tips.text_body_template', base_url: Discourse.base_url) },
+ new_user_tips:
+ I18n.with_locale(@recipient.effective_locale) do
+ I18n.t("system_messages.usage_tips.text_body_template", base_url: Discourse.base_url)
+ end,
site_password: "",
base_url: Discourse.base_url,
}
end
-
end
diff --git a/lib/tasks/add_topic_to_quotes.rake b/lib/tasks/add_topic_to_quotes.rake
index 12dfbe498f4..4a463082a99 100644
--- a/lib/tasks/add_topic_to_quotes.rake
+++ b/lib/tasks/add_topic_to_quotes.rake
@@ -2,9 +2,11 @@
desc "Add the topic to quotes"
task "add_topic_to_quotes" => :environment do
- Post.where("raw like '%topic:%'").each do |p|
- new_raw = p.raw.gsub(/topic:(\d+)\]/, "topic:#{p.topic_id}\"]")
- new_cooked = p.cook(new_raw, topic_id: p.topic_id)
- Post.update_all ["raw = ?, cooked = ?", new_raw, new_cooked], ["id = ?", p.id]
- end
+ Post
+ .where("raw like '%topic:%'")
+ .each do |p|
+ new_raw = p.raw.gsub(/topic:(\d+)\]/, "topic:#{p.topic_id}\"]")
+ new_cooked = p.cook(new_raw, topic_id: p.topic_id)
+ Post.update_all ["raw = ?, cooked = ?", new_raw, new_cooked], ["id = ?", p.id]
+ end
end
diff --git a/lib/tasks/admin.rake b/lib/tasks/admin.rake
index 37ef651f2b0..35e6cc1b9db 100644
--- a/lib/tasks/admin.rake
+++ b/lib/tasks/admin.rake
@@ -20,20 +20,24 @@ task "admin:invite", [:email] => [:environment] do |_, args|
puts "Granting admin!"
user.grant_admin!
- if user.trust_level < 1
- user.change_trust_level!(1)
- end
+ user.change_trust_level!(1) if user.trust_level < 1
user.email_tokens.update_all confirmed: true
puts "Sending email!"
- email_token = user.email_tokens.create!(email: user.email, scope: EmailToken.scopes[:password_reset])
- Jobs.enqueue(:user_email, type: "account_created", user_id: user.id, email_token: email_token.token)
+ email_token =
+ user.email_tokens.create!(email: user.email, scope: EmailToken.scopes[:password_reset])
+ Jobs.enqueue(
+ :user_email,
+ type: "account_created",
+ user_id: user.id,
+ email_token: email_token.token,
+ )
end
desc "Creates a forum administrator"
task "admin:create" => :environment do
- require 'highline/import'
+ require "highline/import"
begin
email = ask("Email: ")
@@ -43,8 +47,11 @@ task "admin:create" => :environment do
if existing_user
# user already exists, ask for password reset
admin = existing_user
- reset_password = ask("User with this email already exists! Do you want to reset the password for this email? (Y/n) ")
- if (reset_password == "" || reset_password.downcase == 'y')
+ reset_password =
+ ask(
+ "User with this email already exists! Do you want to reset the password for this email? (Y/n) ",
+ )
+ if (reset_password == "" || reset_password.downcase == "y")
begin
password = ask("Password: ") { |q| q.echo = false }
password_confirmation = ask("Repeat password: ") { |q| q.echo = false }
@@ -74,9 +81,7 @@ task "admin:create" => :environment do
admin.password = password
end
- if SiteSetting.full_name_required && admin.name.blank?
- admin.name = ask("Full name: ")
- end
+ admin.name = ask("Full name: ") if SiteSetting.full_name_required && admin.name.blank?
# save/update user account
saved = admin.save
@@ -95,15 +100,12 @@ task "admin:create" => :environment do
# grant admin privileges
grant_admin = ask("Do you want to grant Admin privileges to this account? (Y/n) ")
- if (grant_admin == "" || grant_admin.downcase == 'y')
+ if (grant_admin == "" || grant_admin.downcase == "y")
admin.grant_admin!
- if admin.trust_level < 1
- admin.change_trust_level!(1)
- end
+ admin.change_trust_level!(1) if admin.trust_level < 1
admin.email_tokens.update_all confirmed: true
admin.activate
say("\nYour account now has Admin privileges!")
end
-
end
diff --git a/lib/tasks/annotate.rake b/lib/tasks/annotate.rake
index b7ceb0f1b9b..677c7d6d1f4 100644
--- a/lib/tasks/annotate.rake
+++ b/lib/tasks/annotate.rake
@@ -5,9 +5,8 @@ task "annotate" => :environment do |task, args|
raise if !system "bin/annotate --models"
STDERR.puts "Annotate executed successfully"
- non_core_plugins = Dir["plugins/*"].filter do |plugin_path|
- `git check-ignore #{plugin_path}`.present?
- end
+ non_core_plugins =
+ Dir["plugins/*"].filter { |plugin_path| `git check-ignore #{plugin_path}`.present? }
if non_core_plugins.length > 0
STDERR.puts "Warning: you have non-core plugins installed which may affect the annotations"
STDERR.puts "For core annotations, consider running `bin/rake annotate:clean`"
diff --git a/lib/tasks/assets.rake b/lib/tasks/assets.rake
index 34a3e45ac78..f00ab3068e9 100644
--- a/lib/tasks/assets.rake
+++ b/lib/tasks/assets.rake
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-task 'assets:precompile:before' do
- require 'uglifier'
- require 'open3'
+task "assets:precompile:before" do
+ require "uglifier"
+ require "open3"
- unless %w{profile production}.include? Rails.env
+ unless %w[profile production].include? Rails.env
raise "rake assets:precompile should only be run in RAILS_ENV=production, you are risking unminified assets"
end
@@ -35,9 +35,9 @@ task 'assets:precompile:before' do
# is recompiled
Emoji.clear_cache
- $node_compress = `which terser`.present? && !ENV['SKIP_NODE_UGLIFY']
+ $node_compress = `which terser`.present? && !ENV["SKIP_NODE_UGLIFY"]
- unless ENV['USE_SPROCKETS_UGLIFY']
+ unless ENV["USE_SPROCKETS_UGLIFY"]
$bypass_sprockets_uglify = true
Rails.configuration.assets.js_compressor = nil
Rails.configuration.assets.gzip = false
@@ -49,16 +49,16 @@ task 'assets:precompile:before' do
# leaving very complicated build issues
# https://github.com/rails/sprockets-rails/issues/49
- require 'sprockets'
- require 'digest/sha1'
+ require "sprockets"
+ require "digest/sha1"
# Add ember cli chunks
Rails.configuration.assets.precompile.push(
- *EmberCli.script_chunks.values.flatten.flat_map { |name| ["#{name}.js", "#{name}.map"] }
+ *EmberCli.script_chunks.values.flatten.flat_map { |name| ["#{name}.js", "#{name}.map"] },
)
end
-task 'assets:precompile:css' => 'environment' do
+task "assets:precompile:css" => "environment" do
if ENV["DONT_PRECOMPILE_CSS"] == "1"
STDERR.puts "Skipping CSS precompilation, ensure CSS lives in a shared directory across hosts"
else
@@ -84,7 +84,7 @@ task 'assets:precompile:css' => 'environment' do
end
end
-task 'assets:flush_sw' => 'environment' do
+task "assets:flush_sw" => "environment" do
begin
hostname = Discourse.current_hostname
default_port = SiteSetting.force_https? ? 443 : 80
@@ -92,13 +92,14 @@ task 'assets:flush_sw' => 'environment' do
STDERR.puts "Flushing service worker script"
`curl -s -m 1 --resolve '#{hostname}:#{port}:127.0.0.1' #{Discourse.base_url}/service-worker.js > /dev/null`
STDERR.puts "done"
- rescue
+ rescue StandardError
STDERR.puts "Warning: unable to flush service worker script"
end
end
def check_node_heap_size_limit
- output, status = Open3.capture2("node", "-e", "console.log(v8.getHeapStatistics().heap_size_limit/1024/1024)")
+ output, status =
+ Open3.capture2("node", "-e", "console.log(v8.getHeapStatistics().heap_size_limit/1024/1024)")
raise "Failed to fetch node memory limit" if status != 0
output.to_f
end
@@ -108,9 +109,7 @@ def assets_path
end
def global_path_klass
- @global_path_klass ||= Class.new do
- extend GlobalPath
- end
+ @global_path_klass ||= Class.new { extend GlobalPath }
end
def cdn_path(p)
@@ -146,13 +145,14 @@ end
def compress_ruby(from, to)
data = File.read("#{assets_path}/#{from}")
- uglified, map = Uglifier.new(comments: :none,
- source_map: {
- filename: File.basename(from),
- output_filename: File.basename(to)
- }
- )
- .compile_with_map(data)
+ uglified, map =
+ Uglifier.new(
+ comments: :none,
+ source_map: {
+ filename: File.basename(from),
+ output_filename: File.basename(to),
+ },
+ ).compile_with_map(data)
dest = "#{assets_path}/#{to}"
File.write(dest, uglified << "\n//# sourceMappingURL=#{cdn_path "/assets/#{to}.map"}")
@@ -204,7 +204,11 @@ def concurrent?
if ENV["SPROCKETS_CONCURRENT"] == "1"
concurrent_compressors = []
executor = Concurrent::FixedThreadPool.new(Concurrent.processor_count)
- yield(Proc.new { |&block| concurrent_compressors << Concurrent::Future.execute(executor: executor) { block.call } })
+ yield(
+ Proc.new do |&block|
+ concurrent_compressors << Concurrent::Future.execute(executor: executor) { block.call }
+ end
+ )
concurrent_compressors.each(&:wait!)
else
yield(Proc.new { |&block| block.call })
@@ -223,10 +227,7 @@ def log_task_duration(task_description, &task)
end
def geolite_dbs
- @geolite_dbs ||= %w{
- GeoLite2-City
- GeoLite2-ASN
- }
+ @geolite_dbs ||= %w[GeoLite2-City GeoLite2-ASN]
end
def get_mmdb_time(root_path)
@@ -255,11 +256,10 @@ def copy_maxmind(from_path, to_path)
end
end
-task 'assets:precompile' => 'assets:precompile:before' do
+task "assets:precompile" => "assets:precompile:before" do
refresh_days = GlobalSetting.refresh_maxmind_db_during_precompile_days
if refresh_days.to_i > 0
-
mmdb_time = get_mmdb_time(DiscourseIpInfo.path)
backup_mmdb_time =
@@ -275,23 +275,21 @@ task 'assets:precompile' => 'assets:precompile:before' do
if !mmdb_time || mmdb_time < refresh_days.days.ago
puts "Downloading MaxMindDB..."
- mmdb_thread = Thread.new do
- begin
- geolite_dbs.each do |db|
- DiscourseIpInfo.mmdb_download(db)
- end
+ mmdb_thread =
+ Thread.new do
+ begin
+ geolite_dbs.each { |db| DiscourseIpInfo.mmdb_download(db) }
- if GlobalSetting.maxmind_backup_path.present?
- copy_maxmind(DiscourseIpInfo.path, GlobalSetting.maxmind_backup_path)
+ if GlobalSetting.maxmind_backup_path.present?
+ copy_maxmind(DiscourseIpInfo.path, GlobalSetting.maxmind_backup_path)
+ end
+ rescue OpenURI::HTTPError => e
+ STDERR.puts("*" * 100)
+ STDERR.puts("MaxMindDB (#{name}) could not be downloaded: #{e}")
+ STDERR.puts("*" * 100)
+ Rails.logger.warn("MaxMindDB (#{name}) could not be downloaded: #{e}")
end
-
- rescue OpenURI::HTTPError => e
- STDERR.puts("*" * 100)
- STDERR.puts("MaxMindDB (#{name}) could not be downloaded: #{e}")
- STDERR.puts("*" * 100)
- Rails.logger.warn("MaxMindDB (#{name}) could not be downloaded: #{e}")
end
- end
end
end
@@ -305,13 +303,13 @@ task 'assets:precompile' => 'assets:precompile:before' do
locales.add(SiteSetting.default_locale)
end
- log_task_duration('Done compressing all JS files') {
+ log_task_duration("Done compressing all JS files") do
concurrent? do |proc|
- manifest.files
+ manifest
+ .files
.select { |k, v| k =~ /\.js$/ }
.each do |file, info|
-
- path = "#{assets_path}/#{file}"
+ path = "#{assets_path}/#{file}"
_file = (d = File.dirname(file)) == "." ? "_#{file}" : "#{d}/_#{File.basename(file)}"
_path = "#{assets_path}/#{_file}"
max_compress = max_compress?(info["logical_path"], locales)
@@ -321,7 +319,7 @@ task 'assets:precompile' => 'assets:precompile:before' do
STDERR.puts "Skipping: #{file}"
else
proc.call do
- log_task_duration(file) {
+ log_task_duration(file) do
STDERR.puts "Compressing: #{file}"
if max_compress
@@ -333,12 +331,12 @@ task 'assets:precompile' => 'assets:precompile:before' do
info["mtime"] = File.mtime(path).iso8601
gzip(path)
brotli(path, max_compress)
- }
+ end
end
end
- end
+ end
end
- }
+ end
# protected
manifest.send :save
diff --git a/lib/tasks/auto_annotate_models.rake b/lib/tasks/auto_annotate_models.rake
index c73a0d91d4d..cbc1840ad2a 100644
--- a/lib/tasks/auto_annotate_models.rake
+++ b/lib/tasks/auto_annotate_models.rake
@@ -8,32 +8,31 @@ if (Rails.env.development? || Rails.env.test?)
# You can override any of these by setting an environment variable of the
# same name.
Annotate.set_defaults(
- 'position_in_routes' => "before",
- 'position_in_class' => "after",
- 'position_in_test' => "before",
- 'position_in_fixture' => "before",
- 'position_in_factory' => "before",
- 'show_indexes' => "true",
- 'simple_indexes' => "false",
- 'model_dir' => ["app/models"] + Dir.glob("plugins/*/app/models"),
- 'include_version' => "false",
- 'require' => "",
- 'exclude_tests' => "true",
- 'exclude_fixtures' => "true",
- 'exclude_helpers' => "true",
- 'exclude_factories' => "true",
- 'exclude_serializers' => "true",
- 'exclude_controllers' => "true",
- 'ignore_model_sub_dir' => "false",
- 'skip_on_db_migrate' => "true",
- 'format_bare' => "true",
- 'format_rdoc' => "false",
- 'format_markdown' => "false",
- 'sort' => "false",
- 'force' => "false",
- 'trace' => "false",
- 'show_foreign_keys' => "true"
+ "position_in_routes" => "before",
+ "position_in_class" => "after",
+ "position_in_test" => "before",
+ "position_in_fixture" => "before",
+ "position_in_factory" => "before",
+ "show_indexes" => "true",
+ "simple_indexes" => "false",
+ "model_dir" => ["app/models"] + Dir.glob("plugins/*/app/models"),
+ "include_version" => "false",
+ "require" => "",
+ "exclude_tests" => "true",
+ "exclude_fixtures" => "true",
+ "exclude_helpers" => "true",
+ "exclude_factories" => "true",
+ "exclude_serializers" => "true",
+ "exclude_controllers" => "true",
+ "ignore_model_sub_dir" => "false",
+ "skip_on_db_migrate" => "true",
+ "format_bare" => "true",
+ "format_rdoc" => "false",
+ "format_markdown" => "false",
+ "sort" => "false",
+ "force" => "false",
+ "trace" => "false",
+ "show_foreign_keys" => "true",
)
end
-
end
diff --git a/lib/tasks/autospec.rake b/lib/tasks/autospec.rake
index 971eadc0601..a972be9a5fe 100644
--- a/lib/tasks/autospec.rake
+++ b/lib/tasks/autospec.rake
@@ -6,9 +6,9 @@
desc "Run all specs automatically as needed"
task "autospec" => :environment do
- require 'autospec/manager'
+ require "autospec/manager"
- debug = ARGV.any? { |a| a == "d" || a == "debug" } || ENV["DEBUG"]
+ debug = ARGV.any? { |a| a == "d" || a == "debug" } || ENV["DEBUG"]
force_polling = ARGV.any? { |a| a == "p" || a == "polling" }
latency = ((ARGV.find { |a| a =~ /l=|latency=/ } || "").split("=")[1] || 3).to_i
@@ -25,18 +25,19 @@ end
desc "Regenerate swagger docs on API spec change"
task "autospec:swagger" => :environment do
- require 'listen'
- require 'open3'
+ require "listen"
+ require "open3"
puts "Listening to changes in spec/requests/api to regenerate Swagger docs."
- listener = Listen.to("spec/requests/api") do |modified, added, removed|
- puts "API doc file changed."
- Open3.popen3("spec/regenerate_swagger_docs") do |stdin, stdout, stderr, wait_thr|
- while line = stdout.gets
- puts line
+ listener =
+ Listen.to("spec/requests/api") do |modified, added, removed|
+ puts "API doc file changed."
+ Open3.popen3("spec/regenerate_swagger_docs") do |stdin, stdout, stderr, wait_thr|
+ while line = stdout.gets
+ puts line
+ end
end
end
- end
listener.start
sleep
end
diff --git a/lib/tasks/avatars.rake b/lib/tasks/avatars.rake
index 7ccb1fe2f01..78e53a1541f 100644
--- a/lib/tasks/avatars.rake
+++ b/lib/tasks/avatars.rake
@@ -27,9 +27,12 @@ task "avatars:clean" => :environment do
puts "Cleaning up avatar thumbnails"
puts
- optimized_image_ids = OptimizedImage.where("upload_id IN (SELECT custom_upload_id FROM user_avatars) OR
+ optimized_image_ids =
+ OptimizedImage.where(
+ "upload_id IN (SELECT custom_upload_id FROM user_avatars) OR
upload_id IN (SELECT gravatar_upload_id FROM user_avatars) OR
- upload_id IN (SELECT uploaded_avatar_id FROM users)").pluck(:id)
+ upload_id IN (SELECT uploaded_avatar_id FROM users)",
+ ).pluck(:id)
optimized_image_ids.each do |id|
begin
diff --git a/lib/tasks/categories.rake b/lib/tasks/categories.rake
index 88430a79513..1e33a62166b 100644
--- a/lib/tasks/categories.rake
+++ b/lib/tasks/categories.rake
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-task "categories:move_topics", [:from_category, :to_category] => [:environment] do |_, args|
+task "categories:move_topics", %i[from_category to_category] => [:environment] do |_, args|
from_category_id = args[:from_category]
to_category_id = args[:to_category]
@@ -49,8 +49,10 @@ task "categories:list" => :environment do
puts "-- -----------------"
categories.each do |c|
puts "#{c[0]} #{c[1]}"
- Category.where(parent_category_id: c[0]).order(:slug).pluck(:id, :slug).each do |s|
- puts " #{s[0]} #{s[1]}"
- end
+ Category
+ .where(parent_category_id: c[0])
+ .order(:slug)
+ .pluck(:id, :slug)
+ .each { |s| puts " #{s[0]} #{s[1]}" }
end
end
diff --git a/lib/tasks/cdn.rake b/lib/tasks/cdn.rake
index b9c6c27501e..ee2b0c14ee0 100644
--- a/lib/tasks/cdn.rake
+++ b/lib/tasks/cdn.rake
@@ -2,25 +2,24 @@
# cdn related tasks
#
-desc 'pre-stage assets on cdn'
-task 'assets:prestage' => :environment do |t|
+desc "pre-stage assets on cdn"
+task "assets:prestage" => :environment do |t|
require "net/https"
require "uri"
def get_assets(path)
- Dir.glob("#{Rails.root}/public/assets/#{path}*").map do |f|
- if f =~ /[a-f0-9]{16}\.(css|js)$/
- "/assets/#{path}#{f.split('/')[-1]}"
- end
- end.compact
+ Dir
+ .glob("#{Rails.root}/public/assets/#{path}*")
+ .map { |f| "/assets/#{path}#{f.split("/")[-1]}" if f =~ /[a-f0-9]{16}\.(css|js)$/ }
+ .compact
end
# pre-stage css/js only for now
assets = get_assets("locales/") + get_assets("")
- puts "pre staging: #{assets.join(' ')}"
+ puts "pre staging: #{assets.join(" ")}"
# makes testing simpler leaving this here
- config = YAML::safe_load(File.open("#{Rails.root}/config/cdn.yml"))
+ config = YAML.safe_load(File.open("#{Rails.root}/config/cdn.yml"))
start = Time.now
@@ -36,14 +35,12 @@ task 'assets:prestage' => :environment do |t|
"id" => config["id"],
"login" => config["login"],
"passwd" => config["password"],
- "json" => { "prefetch_paths" => asset }.to_json
+ "json" => { "prefetch_paths" => asset }.to_json,
)
response = http.request(request)
json = JSON.parse(response.body)
- if json["status"] != "ok"
- failed_assets.push(asset)
- end
+ failed_assets.push(asset) if json["status"] != "ok"
end
if failed_assets.length > 0
diff --git a/lib/tasks/db.rake b/lib/tasks/db.rake
index c14b5666c5b..403fd6749cb 100644
--- a/lib/tasks/db.rake
+++ b/lib/tasks/db.rake
@@ -1,9 +1,14 @@
# frozen_string_literal: true
# we should set the locale before the migration
-task 'set_locale' do
+task "set_locale" do
begin
- I18n.locale = (SiteSetting.default_locale || :en) rescue :en
+ I18n.locale =
+ begin
+ (SiteSetting.default_locale || :en)
+ rescue StandardError
+ :en
+ end
rescue I18n::InvalidLocale
I18n.locale = :en
end
@@ -19,21 +24,20 @@ module MultisiteTestHelpers
end
end
-task 'db:environment:set' => [:load_config] do |_, args|
+task "db:environment:set" => [:load_config] do |_, args|
if MultisiteTestHelpers.load_multisite?
system("RAILS_ENV=test RAILS_DB=discourse_test_multisite rake db:environment:set")
end
end
-task 'db:force_skip_persist' do
+task "db:force_skip_persist" do
GlobalSetting.skip_db = true
GlobalSetting.skip_redis = true
end
-task 'db:create' => [:load_config] do |_, args|
+task "db:create" => [:load_config] do |_, args|
if MultisiteTestHelpers.create_multisite?
unless system("RAILS_ENV=test RAILS_DB=discourse_test_multisite rake db:create")
-
STDERR.puts "-" * 80
STDERR.puts "ERROR: Could not create multisite DB. A common cause of this is a plugin"
STDERR.puts "checking the column structure when initializing, which raises an error."
@@ -44,12 +48,12 @@ task 'db:create' => [:load_config] do |_, args|
end
begin
- reqs = Rake::Task['db:create'].prerequisites.map(&:to_sym)
- Rake::Task['db:create'].clear_prerequisites
- Rake::Task['db:create'].enhance(["db:force_skip_persist"] + reqs)
+ reqs = Rake::Task["db:create"].prerequisites.map(&:to_sym)
+ Rake::Task["db:create"].clear_prerequisites
+ Rake::Task["db:create"].enhance(["db:force_skip_persist"] + reqs)
end
-task 'db:drop' => [:load_config] do |_, args|
+task "db:drop" => [:load_config] do |_, args|
if MultisiteTestHelpers.create_multisite?
system("RAILS_DB=discourse_test_multisite RAILS_ENV=test rake db:drop")
end
@@ -60,15 +64,15 @@ begin
Rake::Task["db:rollback"].clear
end
-task 'db:rollback' => ['environment', 'set_locale'] do |_, args|
+task "db:rollback" => %w[environment set_locale] do |_, args|
step = ENV["STEP"] ? ENV["STEP"].to_i : 1
ActiveRecord::Base.connection.migration_context.rollback(step)
- Rake::Task['db:_dump'].invoke
+ Rake::Task["db:_dump"].invoke
end
# our optimized version of multisite migrate, we have many sites and we have seeds
# this ensures we can run migrations concurrently to save huge amounts of time
-Rake::Task['multisite:migrate'].clear
+Rake::Task["multisite:migrate"].clear
class StdOutDemux
def initialize(stdout)
@@ -104,17 +108,22 @@ class SeedHelper
def self.filter
# Allows a plugin to exclude any specified seed data files from running
- DiscoursePluginRegistry.seedfu_filter.any? ?
- /^(?!.*(#{DiscoursePluginRegistry.seedfu_filter.to_a.join("|")})).*$/ : nil
+ if DiscoursePluginRegistry.seedfu_filter.any?
+ /^(?!.*(#{DiscoursePluginRegistry.seedfu_filter.to_a.join("|")})).*$/
+ else
+ nil
+ end
end
end
-task 'multisite:migrate' => ['db:load_config', 'environment', 'set_locale'] do |_, args|
- if ENV["RAILS_ENV"] != "production"
- raise "Multisite migrate is only supported in production"
- end
+task "multisite:migrate" => %w[db:load_config environment set_locale] do |_, args|
+ raise "Multisite migrate is only supported in production" if ENV["RAILS_ENV"] != "production"
- DistributedMutex.synchronize('db_migration', redis: Discourse.redis.without_namespace, validity: 1200) do
+ DistributedMutex.synchronize(
+ "db_migration",
+ redis: Discourse.redis.without_namespace,
+ validity: 1200,
+ ) do
# TODO: Switch to processes for concurrent migrations because Rails migration
# is not thread safe by default.
concurrency = 1
@@ -134,35 +143,35 @@ task 'multisite:migrate' => ['db:load_config', 'environment', 'set_locale'] do |
def execute_concurrently(concurrency, exceptions)
queue = Queue.new
- RailsMultisite::ConnectionManagement.each_connection do |db|
- queue << db
- end
+ RailsMultisite::ConnectionManagement.each_connection { |db| queue << db }
concurrency.times { queue << :done }
- (1..concurrency).map do
- Thread.new {
- while true
- db = queue.pop
- break if db == :done
+ (1..concurrency)
+ .map do
+ Thread.new do
+ while true
+ db = queue.pop
+ break if db == :done
- RailsMultisite::ConnectionManagement.with_connection(db) do
- begin
- yield(db) if block_given?
- rescue => e
- exceptions << [db, e]
- ensure
+ RailsMultisite::ConnectionManagement.with_connection(db) do
begin
- $stdout.finish_chunk if concurrency > 1
- rescue => ex
- STDERR.puts ex.inspect
- STDERR.puts ex.backtrace
+ yield(db) if block_given?
+ rescue => e
+ exceptions << [db, e]
+ ensure
+ begin
+ $stdout.finish_chunk if concurrency > 1
+ rescue => ex
+ STDERR.puts ex.inspect
+ STDERR.puts ex.backtrace
+ end
end
end
end
end
- }
- end.each(&:join)
+ end
+ .each(&:join)
end
def check_exceptions(exceptions)
@@ -195,29 +204,35 @@ task 'multisite:migrate' => ['db:load_config', 'environment', 'set_locale'] do |
puts "Seeding #{db}"
SeedFu.seed(SeedHelper.paths, SeedHelper.filter)
- if !Discourse.skip_post_deployment_migrations? && ENV['SKIP_OPTIMIZE_ICONS'] != '1'
+ if !Discourse.skip_post_deployment_migrations? && ENV["SKIP_OPTIMIZE_ICONS"] != "1"
SiteIconManager.ensure_optimized!
end
end
- if concurrency > 1
- $stdout = old_stdout
- end
+ $stdout = old_stdout if concurrency > 1
check_exceptions(exceptions)
- Rake::Task['db:_dump'].invoke
+ Rake::Task["db:_dump"].invoke
end
end
# we need to run seed_fu every time we run rake db:migrate
-task 'db:migrate' => ['load_config', 'environment', 'set_locale'] do |_, args|
- DistributedMutex.synchronize('db_migration', redis: Discourse.redis.without_namespace, validity: 300) do
+task "db:migrate" => %w[load_config environment set_locale] do |_, args|
+ DistributedMutex.synchronize(
+ "db_migration",
+ redis: Discourse.redis.without_namespace,
+ validity: 300,
+ ) do
migrations = ActiveRecord::Base.connection.migration_context.migrations
- now_timestamp = Time.now.utc.strftime('%Y%m%d%H%M%S').to_i
- epoch_timestamp = Time.at(0).utc.strftime('%Y%m%d%H%M%S').to_i
+ now_timestamp = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
+ epoch_timestamp = Time.at(0).utc.strftime("%Y%m%d%H%M%S").to_i
- raise "Migration #{migrations.last.version} is timestamped in the future" if migrations.last.version > now_timestamp
- raise "Migration #{migrations.first.version} is timestamped before the epoch" if migrations.first.version < epoch_timestamp
+ if migrations.last.version > now_timestamp
+ raise "Migration #{migrations.last.version} is timestamped in the future"
+ end
+ if migrations.first.version < epoch_timestamp
+ raise "Migration #{migrations.first.version} is timestamped before the epoch"
+ end
%i[pg_trgm unaccent].each do |extension|
begin
@@ -233,11 +248,9 @@ task 'db:migrate' => ['load_config', 'environment', 'set_locale'] do |_, args|
SeedFu.quiet = true
SeedFu.seed(SeedHelper.paths, SeedHelper.filter)
- if Rails.env.development? && !ENV["RAILS_DB"]
- Rake::Task['db:schema:cache:dump'].invoke
- end
+ Rake::Task["db:schema:cache:dump"].invoke if Rails.env.development? && !ENV["RAILS_DB"]
- if !Discourse.skip_post_deployment_migrations? && ENV['SKIP_OPTIMIZE_ICONS'] != '1'
+ if !Discourse.skip_post_deployment_migrations? && ENV["SKIP_OPTIMIZE_ICONS"] != "1"
SiteIconManager.ensure_optimized!
end
end
@@ -247,14 +260,19 @@ task 'db:migrate' => ['load_config', 'environment', 'set_locale'] do |_, args|
end
end
-task 'test:prepare' => 'environment' do
- I18n.locale = SiteSetting.default_locale rescue :en
+task "test:prepare" => "environment" do
+ I18n.locale =
+ begin
+ SiteSetting.default_locale
+ rescue StandardError
+ :en
+ end
SeedFu.seed(DiscoursePluginRegistry.seed_paths)
end
-task 'db:api_test_seed' => 'environment' do
+task "db:api_test_seed" => "environment" do
puts "Loading test data for discourse_api"
- load Rails.root + 'db/api_test_seeds.rb'
+ load Rails.root + "db/api_test_seeds.rb"
end
def print_table(array)
@@ -262,17 +280,15 @@ def print_table(array)
cols = array[0].keys.length
array.each do |row|
- row.each_with_index do |(_, val), i|
- width[i] = [width[i].to_i, val.to_s.length].max
- end
+ row.each_with_index { |(_, val), i| width[i] = [width[i].to_i, val.to_s.length].max }
end
array[0].keys.each_with_index do |col, i|
- print col.to_s.ljust(width[i], ' ')
+ print col.to_s.ljust(width[i], " ")
if i == cols - 1
puts
else
- print ' | '
+ print " | "
end
end
@@ -280,19 +296,18 @@ def print_table(array)
array.each do |row|
row.each_with_index do |(_, val), i|
- print val.to_s.ljust(width[i], ' ')
+ print val.to_s.ljust(width[i], " ")
if i == cols - 1
puts
else
- print ' | '
+ print " | "
end
end
end
end
-desc 'Statistics about database'
-task 'db:stats' => 'environment' do
-
+desc "Statistics about database"
+task "db:stats" => "environment" do
sql = <<~SQL
select table_name,
(
@@ -312,8 +327,8 @@ task 'db:stats' => 'environment' do
print_table(DB.query_hash(sql))
end
-task 'db:ensure_post_migrations' do
- if ['1', 'true'].include?(ENV['SKIP_POST_DEPLOYMENT_MIGRATIONS'])
+task "db:ensure_post_migrations" do
+ if %w[1 true].include?(ENV["SKIP_POST_DEPLOYMENT_MIGRATIONS"])
cmd = `cat /proc/#{Process.pid}/cmdline | xargs -0 echo`
ENV["SKIP_POST_DEPLOYMENT_MIGRATIONS"] = "0"
exec cmd
@@ -336,23 +351,20 @@ class NormalizedIndex
end
def normalize_index_names(names)
- names.map do |name|
- NormalizedIndex.new(name)
- end.reject { |i| i.name.include?("ccnew") }
+ names.map { |name| NormalizedIndex.new(name) }.reject { |i| i.name.include?("ccnew") }
end
-desc 'Validate indexes'
-task 'db:validate_indexes', [:arg] => ['db:ensure_post_migrations', 'environment'] do |_, args|
-
+desc "Validate indexes"
+task "db:validate_indexes", [:arg] => %w[db:ensure_post_migrations environment] do |_, args|
db = TemporaryDb.new
db.start
db.migrate
ActiveRecord::Base.establish_connection(
- adapter: 'postgresql',
- database: 'discourse',
+ adapter: "postgresql",
+ database: "discourse",
port: db.pg_port,
- host: 'localhost'
+ host: "localhost",
)
expected = DB.query_single <<~SQL
@@ -377,7 +389,6 @@ task 'db:validate_indexes', [:arg] => ['db:ensure_post_migrations', 'environment
inconsistency_found = false
RailsMultisite::ConnectionManagement.each_connection do |db_name|
-
puts "Testing indexes on the #{db_name} database", ""
current = DB.query_single <<~SQL
@@ -403,9 +414,7 @@ task 'db:validate_indexes', [:arg] => ['db:ensure_post_migrations', 'environment
end
end
- if db_name != "default" && renames.length == 0 && missing.length == 0 && extra.length == 0
- next
- end
+ next if db_name != "default" && renames.length == 0 && missing.length == 0 && extra.length == 0
if renames.length > 0
inconsistency_found = true
@@ -431,9 +440,7 @@ task 'db:validate_indexes', [:arg] => ['db:ensure_post_migrations', 'environment
inconsistency_found = true
puts "Missing Indexes", ""
- missing.each do |m|
- puts m
- end
+ missing.each { |m| puts m }
if fix_indexes
puts "Adding missing indexes..."
missing.each do |m|
@@ -452,9 +459,7 @@ task 'db:validate_indexes', [:arg] => ['db:ensure_post_migrations', 'environment
inconsistency_found = true
puts "", "Extra Indexes", ""
- extra.each do |e|
- puts e
- end
+ extra.each { |e| puts e }
if fix_indexes
puts "Removing extra indexes"
@@ -481,21 +486,22 @@ task 'db:validate_indexes', [:arg] => ['db:ensure_post_migrations', 'environment
end
end
- if inconsistency_found && !fix_indexes
- exit 1
- end
+ exit 1 if inconsistency_found && !fix_indexes
end
-desc 'Rebuild indexes'
-task 'db:rebuild_indexes' => 'environment' do
- if Import::backup_tables_count > 0
+desc "Rebuild indexes"
+task "db:rebuild_indexes" => "environment" do
+ if Import.backup_tables_count > 0
raise "Backup from a previous import exists. Drop them before running this job with rake import:remove_backup, or move them to another schema."
end
Discourse.enable_readonly_mode
backup_schema = Jobs::Importer::BACKUP_SCHEMA
- table_names = DB.query_single("select table_name from information_schema.tables where table_schema = 'public'")
+ table_names =
+ DB.query_single(
+ "select table_name from information_schema.tables where table_schema = 'public'",
+ )
begin
# Move all tables to the backup schema:
@@ -511,13 +517,13 @@ task 'db:rebuild_indexes' => 'environment' do
# Fetch index definitions from the new db
index_definitions = {}
table_names.each do |table_name|
- index_definitions[table_name] = DB.query_single("SELECT indexdef FROM pg_indexes WHERE tablename = '#{table_name}' and schemaname = 'public';")
+ index_definitions[table_name] = DB.query_single(
+ "SELECT indexdef FROM pg_indexes WHERE tablename = '#{table_name}' and schemaname = 'public';",
+ )
end
# Drop the new tables
- table_names.each do |table_name|
- DB.exec("DROP TABLE public.#{table_name}")
- end
+ table_names.each { |table_name| DB.exec("DROP TABLE public.#{table_name}") }
# Move the old tables back to the public schema
table_names.each do |table_name|
@@ -525,7 +531,10 @@ task 'db:rebuild_indexes' => 'environment' do
end
# Drop their indexes
- index_names = DB.query_single("SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND tablename IN ('#{table_names.join("', '")}')")
+ index_names =
+ DB.query_single(
+ "SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND tablename IN ('#{table_names.join("', '")}')",
+ )
index_names.each do |index_name|
begin
puts index_name
@@ -547,7 +556,7 @@ task 'db:rebuild_indexes' => 'environment' do
end
end
end
- rescue
+ rescue StandardError
# Can we roll this back?
raise
ensure
@@ -555,14 +564,14 @@ task 'db:rebuild_indexes' => 'environment' do
end
end
-desc 'Check that the DB can be accessed'
-task 'db:status:json' do
+desc "Check that the DB can be accessed"
+task "db:status:json" do
begin
- Rake::Task['environment'].invoke
- DB.query('SELECT 1')
- rescue
- puts({ status: 'error' }.to_json)
+ Rake::Task["environment"].invoke
+ DB.query("SELECT 1")
+ rescue StandardError
+ puts({ status: "error" }.to_json)
else
- puts({ status: 'ok' }.to_json)
+ puts({ status: "ok" }.to_json)
end
end
diff --git a/lib/tasks/destroy.rake b/lib/tasks/destroy.rake
index d65a2039c38..1708c701eee 100644
--- a/lib/tasks/destroy.rake
+++ b/lib/tasks/destroy.rake
@@ -3,7 +3,7 @@
## These tasks are destructive and are for clearing out all the
# content and users from your site.
desc "Remove all topics in a category"
-task "destroy:topics", [:category, :parent_category] => :environment do |t, args|
+task "destroy:topics", %i[category parent_category] => :environment do |t, args|
category = args[:category]
parent_category = args[:parent_category]
descriptive_slug = parent_category ? "#{parent_category}/#{category}" : category
@@ -48,7 +48,5 @@ task "destroy:categories" => :environment do |t, args|
destroy_task = DestroyTask.new
categories = args.extras
puts "Going to delete these categories: #{categories}"
- categories.each do |id|
- destroy_task.destroy_category(id, true)
- end
+ categories.each { |id| destroy_task.destroy_category(id, true) }
end
diff --git a/lib/tasks/dev.rake b/lib/tasks/dev.rake
index fa6e2f86984..91c6df22fca 100644
--- a/lib/tasks/dev.rake
+++ b/lib/tasks/dev.rake
@@ -1,46 +1,47 @@
# frozen_string_literal: true
def check_environment!
- if !Rails.env.development?
- raise "Database commands are only supported in development environment"
- end
+ raise "Database commands are only supported in development environment" if !Rails.env.development?
- ENV['SKIP_TEST_DATABASE'] = "1"
- ENV['SKIP_MULTISITE'] = "1"
+ ENV["SKIP_TEST_DATABASE"] = "1"
+ ENV["SKIP_MULTISITE"] = "1"
end
-desc 'Run db:migrate:reset task and populate sample content for development environment'
-task 'dev:reset' => ['db:load_config'] do |_, args|
+desc "Run db:migrate:reset task and populate sample content for development environment"
+task "dev:reset" => ["db:load_config"] do |_, args|
check_environment!
- Rake::Task['db:migrate:reset'].invoke
- Rake::Task['dev:config'].invoke
- Rake::Task['dev:populate'].invoke
+ Rake::Task["db:migrate:reset"].invoke
+ Rake::Task["dev:config"].invoke
+ Rake::Task["dev:populate"].invoke
end
-desc 'Initialize development environment'
-task 'dev:config' => ['db:load_config'] do |_, args|
+desc "Initialize development environment"
+task "dev:config" => ["db:load_config"] do |_, args|
DiscourseDev.config.update!
end
-desc 'Populate sample content for development environment'
-task 'dev:populate' => ['db:load_config'] do |_, args|
+desc "Populate sample content for development environment"
+task "dev:populate" => ["db:load_config"] do |_, args|
system("redis-cli flushall")
- Rake::Task['groups:populate'].invoke
- Rake::Task['users:populate'].invoke
- Rake::Task['categories:populate'].invoke
- Rake::Task['tags:populate'].invoke
- Rake::Task['topics:populate'].invoke
+ Rake::Task["groups:populate"].invoke
+ Rake::Task["users:populate"].invoke
+ Rake::Task["categories:populate"].invoke
+ Rake::Task["tags:populate"].invoke
+ Rake::Task["topics:populate"].invoke
end
-desc 'Repopulate sample datas in development environment'
-task 'dev:repopulate' => ['db:load_config'] do |_, args|
- require 'highline/import'
+desc "Repopulate sample datas in development environment"
+task "dev:repopulate" => ["db:load_config"] do |_, args|
+ require "highline/import"
- answer = ask("Do you want to repopulate the database with fresh data? It will recreate DBs and run migration from scratch before generating all the samples. (Y/n) ")
+ answer =
+ ask(
+ "Do you want to repopulate the database with fresh data? It will recreate DBs and run migration from scratch before generating all the samples. (Y/n) ",
+ )
- if (answer == "" || answer.downcase == 'y')
- Rake::Task['dev:reset'].invoke
+ if (answer == "" || answer.downcase == "y")
+ Rake::Task["dev:reset"].invoke
else
puts "You can run `bin/rails dev:reset` to repopulate anytime."
end
diff --git a/lib/tasks/docker.rake b/lib/tasks/docker.rake
index 3f9de71ede5..0e3c40e0de8 100644
--- a/lib/tasks/docker.rake
+++ b/lib/tasks/docker.rake
@@ -43,7 +43,7 @@ end
def run_or_fail_prettier(*patterns)
if patterns.any? { |p| Dir[p].any? }
- patterns = patterns.map { |p| "'#{p}'" }.join(' ')
+ patterns = patterns.map { |p| "'#{p}'" }.join(" ")
run_or_fail("yarn pprettier --list-different #{patterns}")
else
puts "Skipping prettier. Pattern not found."
@@ -55,53 +55,78 @@ def log(message)
puts "[#{Time.now.strftime("%Y-%m-%d %H:%M:%S")}] #{message}"
end
-desc 'Run all tests (JS and code in a standalone environment)'
-task 'docker:test' do
+desc "Run all tests (JS and code in a standalone environment)"
+task "docker:test" do
begin
@good = true
@good &&= run_or_fail("yarn install")
- unless ENV['SKIP_LINT']
+ unless ENV["SKIP_LINT"]
puts "Running linters/prettyfiers"
puts "eslint #{`yarn eslint -v`}"
puts "prettier #{`yarn prettier -v`}"
if ENV["SINGLE_PLUGIN"]
@good &&= run_or_fail("bundle exec rubocop --parallel plugins/#{ENV["SINGLE_PLUGIN"]}")
- @good &&= run_or_fail("bundle exec ruby script/i18n_lint.rb plugins/#{ENV["SINGLE_PLUGIN"]}/config/locales/{client,server}.en.yml")
- @good &&= run_or_fail("yarn eslint --ext .js,.js.es6 --no-error-on-unmatched-pattern plugins/#{ENV['SINGLE_PLUGIN']}")
-
- puts "Listing prettier offenses in #{ENV['SINGLE_PLUGIN']}:"
- @good &&= run_or_fail_prettier("plugins/#{ENV['SINGLE_PLUGIN']}/**/*.scss", "plugins/#{ENV['SINGLE_PLUGIN']}/**/*.{js,es6}")
+ @good &&=
+ run_or_fail(
+ "bundle exec ruby script/i18n_lint.rb plugins/#{ENV["SINGLE_PLUGIN"]}/config/locales/{client,server}.en.yml",
+ )
+ @good &&=
+ run_or_fail(
+ "yarn eslint --ext .js,.js.es6 --no-error-on-unmatched-pattern plugins/#{ENV["SINGLE_PLUGIN"]}",
+ )
+
+ puts "Listing prettier offenses in #{ENV["SINGLE_PLUGIN"]}:"
+ @good &&=
+ run_or_fail_prettier(
+ "plugins/#{ENV["SINGLE_PLUGIN"]}/**/*.scss",
+ "plugins/#{ENV["SINGLE_PLUGIN"]}/**/*.{js,es6}",
+ )
else
@good &&= run_or_fail("bundle exec rake plugin:update_all") unless ENV["SKIP_PLUGINS"]
@good &&= run_or_fail("bundle exec rubocop --parallel") unless ENV["SKIP_CORE"]
@good &&= run_or_fail("yarn eslint app/assets/javascripts") unless ENV["SKIP_CORE"]
- @good &&= run_or_fail("yarn eslint --ext .js,.js.es6 --no-error-on-unmatched-pattern plugins") unless ENV["SKIP_PLUGINS"]
-
- @good &&= run_or_fail('bundle exec ruby script/i18n_lint.rb "config/locales/{client,server}.en.yml"') unless ENV["SKIP_CORE"]
- @good &&= run_or_fail('bundle exec ruby script/i18n_lint.rb "plugins/**/locales/{client,server}.en.yml"') unless ENV["SKIP_PLUGINS"]
+ @good &&=
+ run_or_fail(
+ "yarn eslint --ext .js,.js.es6 --no-error-on-unmatched-pattern plugins",
+ ) unless ENV["SKIP_PLUGINS"]
+
+ @good &&=
+ run_or_fail(
+ 'bundle exec ruby script/i18n_lint.rb "config/locales/{client,server}.en.yml"',
+ ) unless ENV["SKIP_CORE"]
+ @good &&=
+ run_or_fail(
+ 'bundle exec ruby script/i18n_lint.rb "plugins/**/locales/{client,server}.en.yml"',
+ ) unless ENV["SKIP_PLUGINS"]
unless ENV["SKIP_CORE"]
puts "Listing prettier offenses in core:"
- @good &&= run_or_fail('yarn pprettier --list-different "app/assets/stylesheets/**/*.scss" "app/assets/javascripts/**/*.js"')
+ @good &&=
+ run_or_fail(
+ 'yarn pprettier --list-different "app/assets/stylesheets/**/*.scss" "app/assets/javascripts/**/*.js"',
+ )
end
unless ENV["SKIP_PLUGINS"]
puts "Listing prettier offenses in plugins:"
- @good &&= run_or_fail('yarn pprettier --list-different "plugins/**/assets/stylesheets/**/*.scss" "plugins/**/assets/javascripts/**/*.{js,es6}"')
+ @good &&=
+ run_or_fail(
+ 'yarn pprettier --list-different "plugins/**/assets/stylesheets/**/*.scss" "plugins/**/assets/javascripts/**/*.{js,es6}"',
+ )
end
end
end
- unless ENV['SKIP_TESTS']
+ unless ENV["SKIP_TESTS"]
puts "Cleaning up old test tmp data in tmp/test_data"
`rm -fr tmp/test_data && mkdir -p tmp/test_data/redis && mkdir tmp/test_data/pg`
puts "Starting background redis"
- @redis_pid = Process.spawn('redis-server --dir tmp/test_data/redis')
+ @redis_pid = Process.spawn("redis-server --dir tmp/test_data/redis")
- unless ENV['SKIP_DB_CREATE']
+ unless ENV["SKIP_DB_CREATE"]
puts "Initializing postgres"
system("script/start_test_db.rb --skip-run", exception: true)
end
@@ -114,27 +139,24 @@ task 'docker:test' do
# for js tests
ENV["SKIP_MULTISITE"] = "1" if ENV["JS_ONLY"]
- unless ENV['SKIP_DB_CREATE']
- @good &&= run_or_fail("bundle exec rake db:create")
- end
+ @good &&= run_or_fail("bundle exec rake db:create") unless ENV["SKIP_DB_CREATE"]
- if ENV['USE_TURBO']
- @good &&= run_or_fail("bundle exec rake parallel:create")
- end
+ @good &&= run_or_fail("bundle exec rake parallel:create") if ENV["USE_TURBO"]
if ENV["INSTALL_OFFICIAL_PLUGINS"]
@good &&= run_or_fail("bundle exec rake plugin:install_all_official")
end
- if ENV["UPDATE_ALL_PLUGINS"]
- @good &&= run_or_fail("bundle exec rake plugin:update_all")
- end
+ @good &&= run_or_fail("bundle exec rake plugin:update_all") if ENV["UPDATE_ALL_PLUGINS"]
if skip_install = ENV["SKIP_INSTALL_PLUGINS"]
- skip_install.split(",").map(&:strip).each do |plugin|
- puts "[SKIP_INSTALL_PLUGINS] Removing #{plugin}"
- `rm -fr plugins/#{plugin}`
- end
+ skip_install
+ .split(",")
+ .map(&:strip)
+ .each do |plugin|
+ puts "[SKIP_INSTALL_PLUGINS] Removing #{plugin}"
+ `rm -fr plugins/#{plugin}`
+ end
end
command_prefix =
@@ -147,31 +169,27 @@ task 'docker:test' do
@good &&= run_or_fail("#{command_prefix}bundle exec rake db:migrate")
- if ENV['USE_TURBO']
+ if ENV["USE_TURBO"]
@good &&= run_or_fail("#{command_prefix}bundle exec rake parallel:migrate")
end
unless ENV["JS_ONLY"]
- if ENV['WARMUP_TMP_FOLDER']
- run_or_fail('bundle exec rspec ./spec/requests/groups_controller_spec.rb')
+ if ENV["WARMUP_TMP_FOLDER"]
+ run_or_fail("bundle exec rspec ./spec/requests/groups_controller_spec.rb")
end
unless ENV["SKIP_CORE"]
params = []
- unless ENV['USE_TURBO']
+ unless ENV["USE_TURBO"]
params << "--profile"
params << "--fail-fast"
- if ENV["BISECT"]
- params << "--bisect"
- end
- if ENV["RSPEC_SEED"]
- params << "--seed #{ENV["RSPEC_SEED"]}"
- end
+ params << "--bisect" if ENV["BISECT"]
+ params << "--seed #{ENV["RSPEC_SEED"]}" if ENV["RSPEC_SEED"]
end
- if ENV['PARALLEL']
- parts = ENV['PARALLEL'].split("/")
+ if ENV["PARALLEL"]
+ parts = ENV["PARALLEL"].split("/")
total = parts[1].to_i
subset = parts[0].to_i - 1
@@ -182,15 +200,16 @@ task 'docker:test' do
spec_partials[1].concat(spec_partials[total - 2].shift(30))
end
- params << spec_partials[subset].join(' ')
+ params << spec_partials[subset].join(" ")
puts "Running spec subset #{subset + 1} of #{total}"
end
- if ENV['USE_TURBO']
- @good &&= run_or_fail("bundle exec ./bin/turbo_rspec --verbose #{params.join(' ')}".strip)
+ if ENV["USE_TURBO"]
+ @good &&=
+ run_or_fail("bundle exec ./bin/turbo_rspec --verbose #{params.join(" ")}".strip)
else
- @good &&= run_or_fail("bundle exec rspec #{params.join(' ')}".strip)
+ @good &&= run_or_fail("bundle exec rspec #{params.join(" ")}".strip)
end
end
@@ -208,12 +227,18 @@ task 'docker:test' do
js_timeout = ENV["JS_TIMEOUT"].presence || 900_000 # 15 minutes
unless ENV["SKIP_CORE"]
- @good &&= run_or_fail("cd app/assets/javascripts/discourse && CI=1 yarn ember exam --load-balance --parallel=3 --random")
+ @good &&=
+ run_or_fail(
+ "cd app/assets/javascripts/discourse && CI=1 yarn ember exam --load-balance --parallel=3 --random",
+ )
end
unless ENV["SKIP_PLUGINS"]
if ENV["SINGLE_PLUGIN"]
- @good &&= run_or_fail("CI=1 bundle exec rake plugin:qunit['#{ENV['SINGLE_PLUGIN']}','#{js_timeout}']")
+ @good &&=
+ run_or_fail(
+ "CI=1 bundle exec rake plugin:qunit['#{ENV["SINGLE_PLUGIN"]}','#{js_timeout}']",
+ )
else
@good &&= run_or_fail("CI=1 bundle exec rake plugin:qunit['*','#{js_timeout}']")
end
@@ -223,7 +248,7 @@ task 'docker:test' do
ensure
puts "Terminating"
- if ENV['PAUSE_ON_TERMINATE']
+ if ENV["PAUSE_ON_TERMINATE"]
puts "Pausing prior to termination"
sleep
end
diff --git a/lib/tasks/emails.rake b/lib/tasks/emails.rake
index 0c31c645b14..c9042d8dd38 100644
--- a/lib/tasks/emails.rake
+++ b/lib/tasks/emails.rake
@@ -4,7 +4,7 @@ def process_popmail(popmail)
begin
mail_string = popmail.pop
Email::Receiver.new(mail_string).process
- rescue
+ rescue StandardError
putc "!"
else
putc "."
@@ -19,9 +19,9 @@ task "emails:import" => :environment do
exit(1)
end
- address = ENV["ADDRESS"].presence || "pop.gmail.com"
- port = (ENV["PORT"].presence || 995).to_i
- ssl = (ENV["SSL"].presence || "1") == "1"
+ address = ENV["ADDRESS"].presence || "pop.gmail.com"
+ port = (ENV["PORT"].presence || 995).to_i
+ ssl = (ENV["SSL"].presence || "1") == "1"
username = ENV["USERNAME"].presence
password = ENV["PASSWORD"].presence
@@ -41,9 +41,7 @@ task "emails:import" => :environment do
while mails_left > 0
pop3.start(username, password) do |pop|
- pop.delete_all do |p|
- process_popmail(p)
- end
+ pop.delete_all { |p| process_popmail(p) }
mails_left = pop.n_mails
end
end
@@ -58,14 +56,13 @@ task "emails:import" => :environment do
end
desc "Check if SMTP connection is successful and send test message"
-task 'emails:test', [:email] => [:environment] do |_, args|
+task "emails:test", [:email] => [:environment] do |_, args|
email = args[:email]
message = "OK"
begin
smtp = Discourse::Application.config.action_mailer.smtp_settings
- if smtp[:address].match(/smtp\.gmail\.com/)
- puts <<~TEXT
+ puts <<~TEXT if smtp[:address].match(/smtp\.gmail\.com/)
#{smtp}
============================== WARNING ==============================
@@ -76,7 +73,6 @@ task 'emails:test', [:email] => [:environment] do |_, args|
========================= CONTINUING TEST ============================
TEXT
- end
puts "Testing sending to #{email} using #{smtp[:address]}:#{smtp[:port]}, username:#{smtp[:user_name]} with #{smtp[:authentication]} auth."
@@ -85,13 +81,12 @@ task 'emails:test', [:email] => [:environment] do |_, args|
EmailSettingsValidator.validate_smtp(
host: smtp[:address],
port: smtp[:port],
- domain: smtp[:domain] || 'localhost',
+ domain: smtp[:domain] || "localhost",
username: smtp[:user_name],
password: smtp[:password],
- authentication: smtp[:authentication] || 'plain'
+ authentication: smtp[:authentication] || "plain",
)
rescue Exception => e
-
if e.to_s.match(/execution expired/)
message = <<~TEXT
======================================== ERROR ========================================
@@ -101,11 +96,9 @@ task 'emails:test', [:email] => [:environment] do |_, args|
If you are using a service like Mailgun or Sendgrid, try using port 2525.
=======================================================================================
TEXT
-
elsif e.to_s.match(/530.*STARTTLS/)
# We can't run a preliminary test with STARTTLS, we'll just try sending the test email.
message = "OK"
-
elsif e.to_s.match(/535/)
message = <<~TEXT
======================================== ERROR ========================================
@@ -118,7 +111,6 @@ task 'emails:test', [:email] => [:environment] do |_, args|
Check them and try again.
=======================================================================================
TEXT
-
elsif e.to_s.match(/Connection refused/)
message = <<~TEXT
======================================== ERROR ========================================
@@ -133,7 +125,6 @@ task 'emails:test', [:email] => [:environment] do |_, args|
Check the port and your networking configuration.
=======================================================================================
TEXT
-
elsif e.to_s.match(/service not known/)
message = <<~TEXT
======================================== ERROR ========================================
@@ -146,7 +137,6 @@ task 'emails:test', [:email] => [:environment] do |_, args|
Check it and try again.
=======================================================================================
TEXT
-
else
message = <<~TEXT
======================================== ERROR ========================================
@@ -210,12 +200,10 @@ task 'emails:test', [:email] => [:environment] do |_, args|
puts error.message
end
- if SiteSetting.disable_emails != 'no'
- puts <<~TEXT
+ puts <<~TEXT if SiteSetting.disable_emails != "no"
### WARNING
The `disable_emails` site setting is currently set to #{SiteSetting.disable_emails}.
Consider changing it to 'no' before performing any further troubleshooting.
TEXT
- end
end
diff --git a/lib/tasks/emoji.rake b/lib/tasks/emoji.rake
index f85e22b379b..fe049fc550d 100644
--- a/lib/tasks/emoji.rake
+++ b/lib/tasks/emoji.rake
@@ -19,244 +19,221 @@ EMOJI_ORDERING_URL ||= "http://www.unicode.org/emoji/charts/emoji-ordering.html"
# eg: "right_anger_bubble" => [ "anger_right" ]
# your app will physically have right_anger_bubble.png and anger_right.png
EMOJI_ALIASES ||= {
- "right_anger_bubble" => [ "anger_right" ],
- "ballot_box" => [ "ballot_box_with_ballot" ],
- "basketball_man" => [ "basketball_player", "person_with_ball" ],
- "beach_umbrella" => [ "umbrella_on_ground", "beach", "beach_with_umbrella" ],
- "parasol_on_ground" => [ "umbrella_on_ground" ],
- "bellhop_bell" => [ "bellhop" ],
- "biohazard" => [ "biohazard_sign" ],
- "bow_and_arrow" => [ "archery" ],
- "spiral_calendar" => [ "calendar_spiral", "spiral_calendar_pad" ],
- "card_file_box" => [ "card_box" ],
- "champagne" => [ "bottle_with_popping_cork" ],
- "cheese" => [ "cheese_wedge" ],
- "city_sunset" => [ "city_dusk" ],
- "couch_and_lamp" => [ "couch" ],
- "crayon" => [ "lower_left_crayon" ],
- "cricket_bat_and_ball" => [ "cricket_bat_ball" ],
- "latin_cross" => [ "cross" ],
- "dagger" => [ "dagger_knife" ],
- "desktop_computer" => [ "desktop" ],
- "card_index_dividers" => [ "dividers" ],
- "dove" => [ "dove_of_peace" ],
- "footprints" => [ "feet" ],
- "fire" => [ "flame" ],
- "black_flag" => [ "flag_black", "waving_black_flag" ],
- "cn" => [ "flag_cn" ],
- "de" => [ "flag_de" ],
- "es" => [ "flag_es" ],
- "fr" => [ "flag_fr" ],
- "uk" => [ "gb", "flag_gb" ],
- "it" => [ "flag_it" ],
- "jp" => [ "flag_jp" ],
- "kr" => [ "flag_kr" ],
- "ru" => [ "flag_ru" ],
- "us" => [ "flag_us" ],
- "white_flag" => [ "flag_white", "waving_white_flag" ],
- "plate_with_cutlery" => [ "fork_knife_plate", "fork_and_knife_with_plate" ],
- "framed_picture" => [ "frame_photo", "frame_with_picture" ],
- "hammer_and_pick" => [ "hammer_pick" ],
- "heavy_heart_exclamation" => [ "heart_exclamation", "heavy_heart_exclamation_mark_ornament" ],
- "houses" => [ "homes", "house_buildings" ],
- "hotdog" => [ "hot_dog" ],
- "derelict_house" => [ "house_abandoned", "derelict_house_building" ],
- "desert_island" => [ "island" ],
- "old_key" => [ "key2" ],
- "laughing" => [ "satisfied" ],
- "business_suit_levitating" => [ "levitate", "man_in_business_suit_levitating" ],
- "weight_lifting_man" => [ "lifter", "weight_lifter" ],
- "medal_sports" => [ "medal", "sports_medal" ],
- "metal" => [ "sign_of_the_horns" ],
- "fu" => [ "middle_finger", "reversed_hand_with_middle_finger_extended" ],
- "motorcycle" => [ "racing_motorcycle" ],
- "mountain_snow" => [ "snow_capped_mountain" ],
- "newspaper_roll" => [ "newspaper2", "rolled_up_newspaper" ],
- "spiral_notepad" => [ "notepad_spiral", "spiral_note_pad" ],
- "oil_drum" => [ "oil" ],
- "older_woman" => [ "grandma" ],
- "paintbrush" => [ "lower_left_paintbrush" ],
- "paperclips" => [ "linked_paperclips" ],
- "pause_button" => [ "double_vertical_bar" ],
- "peace_symbol" => [ "peace" ],
- "fountain_pen" => [ "pen_fountain", "lower_left_fountain_pen" ],
- "ping_pong" => [ "table_tennis" ],
- "place_of_worship" => [ "worship_symbol" ],
- "poop" => [ "shit", "hankey", "poo" ],
- "radioactive" => [ "radioactive_sign" ],
- "railway_track" => [ "railroad_track" ],
- "robot" => [ "robot_face" ],
- "skull" => [ "skeleton" ],
- "skull_and_crossbones" => [ "skull_crossbones" ],
- "speaking_head" => [ "speaking_head_in_silhouette" ],
- "male_detective" => [ "spy", "sleuth_or_spy" ],
- "thinking" => [ "thinking_face" ],
- "-1" => [ "thumbsdown" ],
- "+1" => [ "thumbsup" ],
- "cloud_with_lightning_and_rain" => [ "thunder_cloud_rain", "thunder_cloud_and_rain" ],
- "tickets" => [ "admission_tickets" ],
- "next_track_button" => [ "track_next", "next_track" ],
- "previous_track_button" => [ "track_previous", "previous_track" ],
- "unicorn" => [ "unicorn_face" ],
- "funeral_urn" => [ "urn" ],
- "sun_behind_large_cloud" => [ "white_sun_cloud", "white_sun_behind_cloud" ],
- "sun_behind_rain_cloud" => [ "white_sun_rain_cloud", "white_sun_behind_cloud_with_rain" ],
- "partly_sunny" => [ "white_sun_small_cloud", "white_sun_with_small_cloud" ],
- "open_umbrella" => [ "umbrella2" ],
- "hammer_and_wrench" => [ "tools" ],
- "face_with_thermometer" => [ "thermometer_face" ],
- "timer_clock" => [ "timer" ],
- "keycap_ten" => [ "ten" ],
- "memo" => [ "pencil" ],
- "rescue_worker_helmet" => [ "helmet_with_cross", "helmet_with_white_cross" ],
- "slightly_smiling_face" => [ "slightly_smiling", "slight_smile"],
- "construction_worker_man" => [ "construction_worker" ],
- "upside_down_face" => [ "upside_down" ],
- "money_mouth_face" => [ "money_mouth" ],
- "nerd_face" => [ "nerd" ],
- "hugs" => [ "hugging", "hugging_face" ],
- "roll_eyes" => [ "rolling_eyes", "face_with_rolling_eyes" ],
- "slightly_frowning_face" => [ "frowning", "slight_frown" ],
- "frowning_face" => [ "frowning2", "white_frowning_face" ],
- "zipper_mouth_face" => [ "zipper_mouth" ],
- "face_with_head_bandage" => [ "head_bandage" ],
- "raised_hand_with_fingers_splayed" => [ "hand_splayed" ],
- "raised_hand" => [ "hand" ],
- "vulcan_salute" => [ "vulcan", "raised_hand_with_part_between_middle_and_ring_fingers" ],
- "policeman" => [ "cop" ],
- "running_man" => [ "runner" ],
- "walking_man" => [ "walking" ],
- "bowing_man" => [ "bow" ],
- "no_good_woman" => [ "no_good" ],
- "raising_hand_woman" => [ "raising_hand" ],
- "pouting_woman" => [ "person_with_pouting_face" ],
- "frowning_woman" => [ "person_frowning" ],
- "haircut_woman" => [ "haircut" ],
- "massage_woman" => [ "massage" ],
- "tshirt" => [ "shirt" ],
- "biking_man" => [ "bicyclist" ],
- "mountain_biking_man" => [ "mountain_bicyclist" ],
- "passenger_ship" => [ "cruise_ship" ],
- "motor_boat" => [ "motorboat", "boat" ],
- "flight_arrival" => [ "airplane_arriving" ],
- "flight_departure" => [ "airplane_departure" ],
- "small_airplane" => [ "airplane_small" ],
- "racing_car" => [ "race_car" ],
- "family_man_woman_boy_boy" => [ "family_man_woman_boys" ],
- "family_man_woman_girl_girl" => [ "family_man_woman_girls" ],
- "family_woman_woman_boy" => [ "family_women_boy" ],
- "family_woman_woman_girl" => [ "family_women_girl" ],
- "family_woman_woman_girl_boy" => [ "family_women_girl_boy" ],
- "family_woman_woman_boy_boy" => [ "family_women_boys" ],
- "family_woman_woman_girl_girl" => [ "family_women_girls" ],
- "family_man_man_boy" => [ "family_men_boy" ],
- "family_man_man_girl" => [ "family_men_girl" ],
- "family_man_man_girl_boy" => [ "family_men_girl_boy" ],
- "family_man_man_boy_boy" => [ "family_men_boys" ],
- "family_man_man_girl_girl" => [ "family_men_girls" ],
- "cloud_with_lightning" => [ "cloud_lightning" ],
- "tornado" => [ "cloud_tornado", "cloud_with_tornado" ],
- "cloud_with_rain" => [ "cloud_rain" ],
- "cloud_with_snow" => [ "cloud_snow" ],
- "asterisk" => [ "keycap_star" ],
- "studio_microphone" => [ "microphone2" ],
- "medal_military" => [ "military_medal" ],
- "couple_with_heart_woman_woman" => [ "female_couple_with_heart" ],
- "couple_with_heart_man_man" => [ "male_couple_with_heart" ],
- "couplekiss_woman_woman" => [ "female_couplekiss" ],
- "couplekiss_man_man" => [ "male_couplekiss" ],
- "honeybee" => [ "bee" ],
- "lion" => [ "lion_face" ],
- "artificial_satellite" => [ "satellite_orbital" ],
- "computer_mouse" => [ "mouse_three_button", "three_button_mouse" ],
- "hocho" => [ "knife" ],
- "swimming_man" => [ "swimmer" ],
- "wind_face" => [ "wind_blowing_face" ],
- "golfing_man" => [ "golfer" ],
- "facepunch" => [ "punch" ],
- "building_construction" => [ "construction_site" ],
- "family_man_woman_girl_boy" => [ "family" ],
- "ice_hockey" => [ "hockey" ],
- "snowman_with_snow" => [ "snowman2" ],
- "play_or_pause_button" => [ "play_pause" ],
- "film_projector" => [ "projector" ],
- "shopping" => [ "shopping_bags" ],
- "open_book" => [ "book" ],
- "national_park" => [ "park" ],
- "world_map" => [ "map" ],
- "pen" => [ "pen_ballpoint", "lower_left_ballpoint_pen" ],
- "email" => [ "envelope", "e-mail" ],
- "phone" => [ "telephone" ],
- "atom_symbol" => [ "atom" ],
- "mantelpiece_clock" => [ "clock" ],
- "camera_flash" => [ "camera_with_flash" ],
- "film_strip" => [ "film_frames" ],
- "balance_scale" => [ "scales" ],
- "surfing_man" => [ "surfer" ],
- "couplekiss_man_woman" => [ "couplekiss" ],
- "couple_with_heart_woman_man" => [ "couple_with_heart" ],
- "clamp" => [ "compression" ],
- "dancing_women" => [ "dancers" ],
- "blonde_man" => [ "person_with_blond_hair" ],
- "sleeping_bed" => [ "sleeping_accommodation" ],
- "om" => [ "om_symbol" ],
- "tipping_hand_woman" => [ "information_desk_person" ],
- "rowing_man" => [ "rowboat" ],
- "new_moon" => [ "moon" ],
- "oncoming_automobile" => [ "car", "automobile" ],
- "fleur_de_lis" => [ "fleur-de-lis" ],
- "face_vomiting" => [ "puke" ],
- "smile" => [ "grinning_face_with_smiling_eyes" ],
+ "right_anger_bubble" => ["anger_right"],
+ "ballot_box" => ["ballot_box_with_ballot"],
+ "basketball_man" => %w[basketball_player person_with_ball],
+ "beach_umbrella" => %w[umbrella_on_ground beach beach_with_umbrella],
+ "parasol_on_ground" => ["umbrella_on_ground"],
+ "bellhop_bell" => ["bellhop"],
+ "biohazard" => ["biohazard_sign"],
+ "bow_and_arrow" => ["archery"],
+ "spiral_calendar" => %w[calendar_spiral spiral_calendar_pad],
+ "card_file_box" => ["card_box"],
+ "champagne" => ["bottle_with_popping_cork"],
+ "cheese" => ["cheese_wedge"],
+ "city_sunset" => ["city_dusk"],
+ "couch_and_lamp" => ["couch"],
+ "crayon" => ["lower_left_crayon"],
+ "cricket_bat_and_ball" => ["cricket_bat_ball"],
+ "latin_cross" => ["cross"],
+ "dagger" => ["dagger_knife"],
+ "desktop_computer" => ["desktop"],
+ "card_index_dividers" => ["dividers"],
+ "dove" => ["dove_of_peace"],
+ "footprints" => ["feet"],
+ "fire" => ["flame"],
+ "black_flag" => %w[flag_black waving_black_flag],
+ "cn" => ["flag_cn"],
+ "de" => ["flag_de"],
+ "es" => ["flag_es"],
+ "fr" => ["flag_fr"],
+ "uk" => %w[gb flag_gb],
+ "it" => ["flag_it"],
+ "jp" => ["flag_jp"],
+ "kr" => ["flag_kr"],
+ "ru" => ["flag_ru"],
+ "us" => ["flag_us"],
+ "white_flag" => %w[flag_white waving_white_flag],
+ "plate_with_cutlery" => %w[fork_knife_plate fork_and_knife_with_plate],
+ "framed_picture" => %w[frame_photo frame_with_picture],
+ "hammer_and_pick" => ["hammer_pick"],
+ "heavy_heart_exclamation" => %w[heart_exclamation heavy_heart_exclamation_mark_ornament],
+ "houses" => %w[homes house_buildings],
+ "hotdog" => ["hot_dog"],
+ "derelict_house" => %w[house_abandoned derelict_house_building],
+ "desert_island" => ["island"],
+ "old_key" => ["key2"],
+ "laughing" => ["satisfied"],
+ "business_suit_levitating" => %w[levitate man_in_business_suit_levitating],
+ "weight_lifting_man" => %w[lifter weight_lifter],
+ "medal_sports" => %w[medal sports_medal],
+ "metal" => ["sign_of_the_horns"],
+ "fu" => %w[middle_finger reversed_hand_with_middle_finger_extended],
+ "motorcycle" => ["racing_motorcycle"],
+ "mountain_snow" => ["snow_capped_mountain"],
+ "newspaper_roll" => %w[newspaper2 rolled_up_newspaper],
+ "spiral_notepad" => %w[notepad_spiral spiral_note_pad],
+ "oil_drum" => ["oil"],
+ "older_woman" => ["grandma"],
+ "paintbrush" => ["lower_left_paintbrush"],
+ "paperclips" => ["linked_paperclips"],
+ "pause_button" => ["double_vertical_bar"],
+ "peace_symbol" => ["peace"],
+ "fountain_pen" => %w[pen_fountain lower_left_fountain_pen],
+ "ping_pong" => ["table_tennis"],
+ "place_of_worship" => ["worship_symbol"],
+ "poop" => %w[shit hankey poo],
+ "radioactive" => ["radioactive_sign"],
+ "railway_track" => ["railroad_track"],
+ "robot" => ["robot_face"],
+ "skull" => ["skeleton"],
+ "skull_and_crossbones" => ["skull_crossbones"],
+ "speaking_head" => ["speaking_head_in_silhouette"],
+ "male_detective" => %w[spy sleuth_or_spy],
+ "thinking" => ["thinking_face"],
+ "-1" => ["thumbsdown"],
+ "+1" => ["thumbsup"],
+ "cloud_with_lightning_and_rain" => %w[thunder_cloud_rain thunder_cloud_and_rain],
+ "tickets" => ["admission_tickets"],
+ "next_track_button" => %w[track_next next_track],
+ "previous_track_button" => %w[track_previous previous_track],
+ "unicorn" => ["unicorn_face"],
+ "funeral_urn" => ["urn"],
+ "sun_behind_large_cloud" => %w[white_sun_cloud white_sun_behind_cloud],
+ "sun_behind_rain_cloud" => %w[white_sun_rain_cloud white_sun_behind_cloud_with_rain],
+ "partly_sunny" => %w[white_sun_small_cloud white_sun_with_small_cloud],
+ "open_umbrella" => ["umbrella2"],
+ "hammer_and_wrench" => ["tools"],
+ "face_with_thermometer" => ["thermometer_face"],
+ "timer_clock" => ["timer"],
+ "keycap_ten" => ["ten"],
+ "memo" => ["pencil"],
+ "rescue_worker_helmet" => %w[helmet_with_cross helmet_with_white_cross],
+ "slightly_smiling_face" => %w[slightly_smiling slight_smile],
+ "construction_worker_man" => ["construction_worker"],
+ "upside_down_face" => ["upside_down"],
+ "money_mouth_face" => ["money_mouth"],
+ "nerd_face" => ["nerd"],
+ "hugs" => %w[hugging hugging_face],
+ "roll_eyes" => %w[rolling_eyes face_with_rolling_eyes],
+ "slightly_frowning_face" => %w[frowning slight_frown],
+ "frowning_face" => %w[frowning2 white_frowning_face],
+ "zipper_mouth_face" => ["zipper_mouth"],
+ "face_with_head_bandage" => ["head_bandage"],
+ "raised_hand_with_fingers_splayed" => ["hand_splayed"],
+ "raised_hand" => ["hand"],
+ "vulcan_salute" => %w[vulcan raised_hand_with_part_between_middle_and_ring_fingers],
+ "policeman" => ["cop"],
+ "running_man" => ["runner"],
+ "walking_man" => ["walking"],
+ "bowing_man" => ["bow"],
+ "no_good_woman" => ["no_good"],
+ "raising_hand_woman" => ["raising_hand"],
+ "pouting_woman" => ["person_with_pouting_face"],
+ "frowning_woman" => ["person_frowning"],
+ "haircut_woman" => ["haircut"],
+ "massage_woman" => ["massage"],
+ "tshirt" => ["shirt"],
+ "biking_man" => ["bicyclist"],
+ "mountain_biking_man" => ["mountain_bicyclist"],
+ "passenger_ship" => ["cruise_ship"],
+ "motor_boat" => %w[motorboat boat],
+ "flight_arrival" => ["airplane_arriving"],
+ "flight_departure" => ["airplane_departure"],
+ "small_airplane" => ["airplane_small"],
+ "racing_car" => ["race_car"],
+ "family_man_woman_boy_boy" => ["family_man_woman_boys"],
+ "family_man_woman_girl_girl" => ["family_man_woman_girls"],
+ "family_woman_woman_boy" => ["family_women_boy"],
+ "family_woman_woman_girl" => ["family_women_girl"],
+ "family_woman_woman_girl_boy" => ["family_women_girl_boy"],
+ "family_woman_woman_boy_boy" => ["family_women_boys"],
+ "family_woman_woman_girl_girl" => ["family_women_girls"],
+ "family_man_man_boy" => ["family_men_boy"],
+ "family_man_man_girl" => ["family_men_girl"],
+ "family_man_man_girl_boy" => ["family_men_girl_boy"],
+ "family_man_man_boy_boy" => ["family_men_boys"],
+ "family_man_man_girl_girl" => ["family_men_girls"],
+ "cloud_with_lightning" => ["cloud_lightning"],
+ "tornado" => %w[cloud_tornado cloud_with_tornado],
+ "cloud_with_rain" => ["cloud_rain"],
+ "cloud_with_snow" => ["cloud_snow"],
+ "asterisk" => ["keycap_star"],
+ "studio_microphone" => ["microphone2"],
+ "medal_military" => ["military_medal"],
+ "couple_with_heart_woman_woman" => ["female_couple_with_heart"],
+ "couple_with_heart_man_man" => ["male_couple_with_heart"],
+ "couplekiss_woman_woman" => ["female_couplekiss"],
+ "couplekiss_man_man" => ["male_couplekiss"],
+ "honeybee" => ["bee"],
+ "lion" => ["lion_face"],
+ "artificial_satellite" => ["satellite_orbital"],
+ "computer_mouse" => %w[mouse_three_button three_button_mouse],
+ "hocho" => ["knife"],
+ "swimming_man" => ["swimmer"],
+ "wind_face" => ["wind_blowing_face"],
+ "golfing_man" => ["golfer"],
+ "facepunch" => ["punch"],
+ "building_construction" => ["construction_site"],
+ "family_man_woman_girl_boy" => ["family"],
+ "ice_hockey" => ["hockey"],
+ "snowman_with_snow" => ["snowman2"],
+ "play_or_pause_button" => ["play_pause"],
+ "film_projector" => ["projector"],
+ "shopping" => ["shopping_bags"],
+ "open_book" => ["book"],
+ "national_park" => ["park"],
+ "world_map" => ["map"],
+ "pen" => %w[pen_ballpoint lower_left_ballpoint_pen],
+ "email" => %w[envelope e-mail],
+ "phone" => ["telephone"],
+ "atom_symbol" => ["atom"],
+ "mantelpiece_clock" => ["clock"],
+ "camera_flash" => ["camera_with_flash"],
+ "film_strip" => ["film_frames"],
+ "balance_scale" => ["scales"],
+ "surfing_man" => ["surfer"],
+ "couplekiss_man_woman" => ["couplekiss"],
+ "couple_with_heart_woman_man" => ["couple_with_heart"],
+ "clamp" => ["compression"],
+ "dancing_women" => ["dancers"],
+ "blonde_man" => ["person_with_blond_hair"],
+ "sleeping_bed" => ["sleeping_accommodation"],
+ "om" => ["om_symbol"],
+ "tipping_hand_woman" => ["information_desk_person"],
+ "rowing_man" => ["rowboat"],
+ "new_moon" => ["moon"],
+ "oncoming_automobile" => %w[car automobile],
+ "fleur_de_lis" => ["fleur-de-lis"],
+ "face_vomiting" => ["puke"],
+ "smile" => ["grinning_face_with_smiling_eyes"],
"frowning_with_open_mouth" => ["frowning_face_with_open_mouth"],
}
EMOJI_GROUPS ||= [
- {
- "name" => "smileys_&_emotion",
- "tabicon" => "grinning"
- },
- {
- "name" => "people_&_body",
- "tabicon" => "wave"
- },
- {
- "name" => "animals_&_nature",
- "tabicon" => "evergreen_tree"
- },
- {
- "name" => "food_&_drink",
- "tabicon" => "hamburger"
- },
- {
- "name" => "travel_&_places",
- "tabicon" => "airplane"
- },
- {
- "name" => "activities",
- "tabicon" => "soccer"
- },
- {
- "name" => "objects",
- "tabicon" => "eyeglasses"
- },
- {
- "name" => "symbols",
- "tabicon" => "white_check_mark"
- },
- {
- "name" => "flags",
- "tabicon" => "checkered_flag"
- }
+ { "name" => "smileys_&_emotion", "tabicon" => "grinning" },
+ { "name" => "people_&_body", "tabicon" => "wave" },
+ { "name" => "animals_&_nature", "tabicon" => "evergreen_tree" },
+ { "name" => "food_&_drink", "tabicon" => "hamburger" },
+ { "name" => "travel_&_places", "tabicon" => "airplane" },
+ { "name" => "activities", "tabicon" => "soccer" },
+ { "name" => "objects", "tabicon" => "eyeglasses" },
+ { "name" => "symbols", "tabicon" => "white_check_mark" },
+ { "name" => "flags", "tabicon" => "checkered_flag" },
]
-FITZPATRICK_SCALE ||= [ "1f3fb", "1f3fc", "1f3fd", "1f3fe", "1f3ff" ]
+FITZPATRICK_SCALE ||= %w[1f3fb 1f3fc 1f3fd 1f3fe 1f3ff]
DEFAULT_SET ||= "twitter"
# Replace the platform by another when downloading the image (accepts names or categories)
EMOJI_IMAGES_PATCH ||= {
- "apple" => { "snowboarder" => "twitter" },
- "windows" => { "country-flag" => "twitter" }
+ "apple" => {
+ "snowboarder" => "twitter",
+ },
+ "windows" => {
+ "country-flag" => "twitter",
+ },
}
EMOJI_SETS ||= {
@@ -278,23 +255,24 @@ def search_aliases(emojis)
# Format is search pattern => associated emojis
# eg: "cry" => [ "sob" ]
# for a "cry" query should return: cry and sob
- @aliases ||= begin
- aliases = {
- "sad" => [ "frowning_face", "slightly_frowning_face", "sob", "crying_cat_face", "cry" ],
- "cry" => [ "sob" ]
- }
-
- emojis.each do |_, config|
- next if config["search_aliases"].blank?
- config["search_aliases"].each do |name|
- aliases[name] ||= []
- aliases[name] << config["name"]
+ @aliases ||=
+ begin
+ aliases = {
+ "sad" => %w[frowning_face slightly_frowning_face sob crying_cat_face cry],
+ "cry" => ["sob"],
+ }
+
+ emojis.each do |_, config|
+ next if config["search_aliases"].blank?
+ config["search_aliases"].each do |name|
+ aliases[name] ||= []
+ aliases[name] << config["name"]
+ end
end
- end
- aliases.map { |_, names| names.uniq! }
- aliases
- end
+ aliases.map { |_, names| names.uniq! }
+ aliases
+ end
end
desc "update emoji images"
@@ -318,16 +296,15 @@ end
desc "test the emoji generation script"
task "emoji:test" do
- ENV['EMOJI_TEST'] = "1"
+ ENV["EMOJI_TEST"] = "1"
Rake::Task["emoji:update"].invoke
end
def optimize_images(images)
images.each do |filename|
- FileHelper.image_optim(
- allow_pngquant: true,
- strip_image_metadata: true
- ).optimize_image!(filename)
+ FileHelper.image_optim(allow_pngquant: true, strip_image_metadata: true).optimize_image!(
+ filename,
+ )
end
end
@@ -351,15 +328,20 @@ end
def fix_incomplete_sets(emojis)
emojis.each do |code, config|
EMOJI_SETS.each do |set_name, set_destination|
- patch_set = EMOJI_SETS[EMOJI_IMAGES_PATCH.dig(set_name, config["name"])] ||
- EMOJI_SETS[EMOJI_IMAGES_PATCH.dig(set_name, config["category"])]
-
- if patch_set || !File.exist?(File.join(EMOJI_IMAGES_PATH, set_destination, "#{config['name']}.png"))
- origin = File.join(EMOJI_IMAGES_PATH, patch_set || EMOJI_SETS[DEFAULT_SET], config['name'])
-
- FileUtils.cp("#{origin}.png", File.join(EMOJI_IMAGES_PATH, set_destination, "#{config['name']}.png"))
+ patch_set =
+ EMOJI_SETS[EMOJI_IMAGES_PATCH.dig(set_name, config["name"])] ||
+ EMOJI_SETS[EMOJI_IMAGES_PATCH.dig(set_name, config["category"])]
+
+ if patch_set ||
+ !File.exist?(File.join(EMOJI_IMAGES_PATH, set_destination, "#{config["name"]}.png"))
+ origin = File.join(EMOJI_IMAGES_PATH, patch_set || EMOJI_SETS[DEFAULT_SET], config["name"])
+
+ FileUtils.cp(
+ "#{origin}.png",
+ File.join(EMOJI_IMAGES_PATH, set_destination, "#{config["name"]}.png"),
+ )
if File.directory?(origin)
- FileUtils.cp_r(origin, File.join(EMOJI_IMAGES_PATH, set_destination, config['name']))
+ FileUtils.cp_r(origin, File.join(EMOJI_IMAGES_PATH, set_destination, config["name"]))
end
end
end
@@ -370,7 +352,7 @@ def generate_emoji_groups(keywords, sections)
puts "Generating groups..."
list = URI.parse(EMOJI_ORDERING_URL).read
- doc = Nokogiri::HTML5(list)
+ doc = Nokogiri.HTML5(list)
table = doc.css("table")[0]
EMOJI_GROUPS.map do |group|
@@ -380,19 +362,23 @@ def generate_emoji_groups(keywords, sections)
sub_sections.each do |section|
title_section = table.css("tr th a[@name='#{section}']")
emoji_list_section = title_section.first.parent.parent.next_element
- emoji_list_section.css("a.plain img").each do |link|
- emoji_code = link.attr("title")
- .scan(/U\+(.{4,5})\b/)
- .flatten
- .map { |code| code.downcase.strip }
- .join("_")
-
- emoji_char = code_to_emoji(emoji_code)
-
- if emoji = keywords[emoji_char]
- group["icons"] << { name: emoji["name"], diversity: emoji["fitzpatrick_scale"] }
+ emoji_list_section
+ .css("a.plain img")
+ .each do |link|
+ emoji_code =
+ link
+ .attr("title")
+ .scan(/U\+(.{4,5})\b/)
+ .flatten
+ .map { |code| code.downcase.strip }
+ .join("_")
+
+ emoji_char = code_to_emoji(emoji_code)
+
+ if emoji = keywords[emoji_char]
+ group["icons"] << { name: emoji["name"], diversity: emoji["fitzpatrick_scale"] }
+ end
end
- end
end
group.delete("sections")
group
@@ -405,7 +391,10 @@ def write_aliases
EMOJI_SETS.each do |set_name, set_destination|
origin_file = File.join(EMOJI_IMAGES_PATH, set_destination, "#{original}.png")
origin_dir = File.join(EMOJI_IMAGES_PATH, set_destination, original)
- FileUtils.cp(origin_file, File.join(EMOJI_IMAGES_PATH, set_destination, "#{emoji_alias}.png"))
+ FileUtils.cp(
+ origin_file,
+ File.join(EMOJI_IMAGES_PATH, set_destination, "#{emoji_alias}.png"),
+ )
if File.directory?(origin_dir)
FileUtils.cp_r(origin_dir, File.join(EMOJI_IMAGES_PATH, set_destination, emoji_alias))
@@ -423,29 +412,31 @@ def write_db_json(emojis, translations, search_aliases)
FileUtils.mkdir_p(File.expand_path("..", EMOJI_DB_PATH))
# skin tones variations of emojis shouldn’t appear in autocomplete
- emojis_without_tones = emojis
- .select { |char, config|
- !FITZPATRICK_SCALE.any? { |scale|
- codepoints_to_code(char.codepoints, config["fitzpatrick_scale"])[scale]
- }
- }
- .map { |char, config|
- {
- "code" => codepoints_to_code(char.codepoints, config["fitzpatrick_scale"]).tr("_", "-"),
- "name" => config["name"]
- }
- }
+ emojis_without_tones =
+ emojis
+ .select do |char, config|
+ !FITZPATRICK_SCALE.any? do |scale|
+ codepoints_to_code(char.codepoints, config["fitzpatrick_scale"])[scale]
+ end
+ end
+ .map do |char, config|
+ {
+ "code" => codepoints_to_code(char.codepoints, config["fitzpatrick_scale"]).tr("_", "-"),
+ "name" => config["name"],
+ }
+ end
- emoji_with_tones = emojis
- .select { |code, config| config["fitzpatrick_scale"] }
- .map { |code, config| config["name"] }
+ emoji_with_tones =
+ emojis
+ .select { |code, config| config["fitzpatrick_scale"] }
+ .map { |code, config| config["name"] }
db = {
"emojis" => emojis_without_tones,
"tonableEmojis" => emoji_with_tones,
"aliases" => EMOJI_ALIASES,
"searchAliases" => search_aliases,
- "translations" => translations
+ "translations" => translations,
}
File.write(EMOJI_DB_PATH, JSON.pretty_generate(db))
@@ -462,29 +453,23 @@ def write_js_groups(emojis, groups)
end
def code_to_emoji(code)
- code
- .split("_")
- .map { |e| e.to_i(16) }
- .pack "U*"
+ code.split("_").map { |e| e.to_i(16) }.pack "U*"
end
def codepoints_to_code(codepoints, fitzpatrick_scale)
- codepoints = codepoints
- .map { |c| c.to_s(16).rjust(4, "0") }
- .join("_")
- .downcase
+ codepoints = codepoints.map { |c| c.to_s(16).rjust(4, "0") }.join("_").downcase
- if !fitzpatrick_scale
- codepoints.gsub!(/_fe0f$/, "")
- end
+ codepoints.gsub!(/_fe0f$/, "") if !fitzpatrick_scale
codepoints
end
def confirm_overwrite(path)
- return if ENV['EMOJI_TEST']
+ return if ENV["EMOJI_TEST"]
- STDOUT.puts("[!] You are about to overwrite #{path}, are you sure? [CTRL+c] to cancel, [ENTER] to continue")
+ STDOUT.puts(
+ "[!] You are about to overwrite #{path}, are you sure? [CTRL+c] to cancel, [ENTER] to continue",
+ )
STDIN.gets.chomp
end
@@ -505,11 +490,11 @@ class TestEmojiUpdate < MiniTest::Test
end
def test_codepoints_to_code
- assert_equal "1f6b5_200d_2640", codepoints_to_code([128693, 8205, 9792, 65039], false)
+ assert_equal "1f6b5_200d_2640", codepoints_to_code([128_693, 8205, 9792, 65_039], false)
end
def test_codepoints_to_code_with_scale
- assert_equal "1f6b5_200d_2640_fe0f", codepoints_to_code([128693, 8205, 9792, 65039], true)
+ assert_equal "1f6b5_200d_2640_fe0f", codepoints_to_code([128_693, 8205, 9792, 65_039], true)
end
def test_groups_js_es6_creation
diff --git a/lib/tasks/export.rake b/lib/tasks/export.rake
index 1b4a63ed2fe..e7d900697fc 100644
--- a/lib/tasks/export.rake
+++ b/lib/tasks/export.rake
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-desc 'Export all the categories'
-task 'export:categories', [:category_ids] => [:environment] do |_, args|
+desc "Export all the categories"
+task "export:categories", [:category_ids] => [:environment] do |_, args|
require "import_export"
ids = args[:category_ids].split(" ")
@@ -9,24 +9,24 @@ task 'export:categories', [:category_ids] => [:environment] do |_, args|
puts "", "Done", ""
end
-desc 'Export only the structure of all categories'
-task 'export:category_structure', [:include_group_users, :file_name] => [:environment] do |_, args|
+desc "Export only the structure of all categories"
+task "export:category_structure", %i[include_group_users file_name] => [:environment] do |_, args|
require "import_export"
ImportExport.export_category_structure(args[:include_group_users], args[:file_name])
puts "", "Done", ""
end
-desc 'Export all user groups'
-task 'export:groups', [:include_group_users, :file_name] => [:environment] do |_, args|
+desc "Export all user groups"
+task "export:groups", %i[include_group_users file_name] => [:environment] do |_, args|
require "import_export"
ImportExport.export_groups(args[:include_group_users], args[:file_name])
puts "", "Done", ""
end
-desc 'Export all translation overrides'
-task 'export:translation_overrides' => [:environment] do |_, args|
+desc "Export all translation overrides"
+task "export:translation_overrides" => [:environment] do |_, args|
require "import_export"
ImportExport.export_translation_overrides
diff --git a/lib/tasks/groups.rake b/lib/tasks/groups.rake
index 242ecbb16ef..b1913eeb309 100644
--- a/lib/tasks/groups.rake
+++ b/lib/tasks/groups.rake
@@ -1,7 +1,7 @@
# frozen_string_literal: true
# bulk grant badge to members of a specific group
-task "groups:grant_badge", [:group_id, :badge_id] => [:environment] do |_, args|
+task "groups:grant_badge", %i[group_id badge_id] => [:environment] do |_, args|
group_id = args[:group_id]
badge_id = args[:badge_id]
diff --git a/lib/tasks/i18n.rake b/lib/tasks/i18n.rake
index b35cce8fdc2..cdac46bb907 100644
--- a/lib/tasks/i18n.rake
+++ b/lib/tasks/i18n.rake
@@ -1,9 +1,9 @@
# frozen_string_literal: true
-require 'i18n/locale_file_checker'
-require 'seed_data/categories'
-require 'seed_data/topics'
-require 'colored2'
+require "i18n/locale_file_checker"
+require "seed_data/categories"
+require "seed_data/topics"
+require "colored2"
desc "Checks locale files for errors"
task "i18n:check" => [:environment] do |_, args|
@@ -27,7 +27,7 @@ task "i18n:check" => [:environment] do |_, args|
locales.each do |locale|
begin
all_errors = LocaleFileChecker.new.check(locale)
- rescue
+ rescue StandardError
failed_locales << locale
next
end
diff --git a/lib/tasks/import.rake b/lib/tasks/import.rake
index 7b1b02eeefa..ed6bdc25ce6 100644
--- a/lib/tasks/import.rake
+++ b/lib/tasks/import.rake
@@ -425,7 +425,7 @@ def log(message)
end
task "import:create_phpbb_permalinks" => :environment do
- log 'Creating Permalinks...'
+ log "Creating Permalinks..."
# /[^\/]+\/.*-t(\d+).html/
SiteSetting.permalink_normalizations = '/[^\/]+\/.*-t(\d+).html/thread/\1'
@@ -433,7 +433,11 @@ task "import:create_phpbb_permalinks" => :environment do
Topic.listable_topics.find_each do |topic|
tcf = topic.custom_fields
if tcf && tcf["import_id"]
- Permalink.create(url: "thread/#{tcf["import_id"]}", topic_id: topic.id) rescue nil
+ begin
+ Permalink.create(url: "thread/#{tcf["import_id"]}", topic_id: topic.id)
+ rescue StandardError
+ nil
+ end
end
end
@@ -441,38 +445,45 @@ task "import:create_phpbb_permalinks" => :environment do
end
task "import:remap_old_phpbb_permalinks" => :environment do
- log 'Remapping Permalinks...'
+ log "Remapping Permalinks..."
i = 0
- Post.where("raw LIKE ?", "%discussions.example.com%").each do |p|
- begin
- new_raw = p.raw.dup
- # \((https?:\/\/discussions\.example\.com\/\S*-t\d+.html)\)
- new_raw.gsub!(/\((https?:\/\/discussions\.example\.com\/\S*-t\d+.html)\)/) do
- normalized_url = Permalink.normalize_url($1)
- permalink = Permalink.find_by_url(normalized_url) rescue nil
- if permalink && permalink.target_url
- "(#{permalink.target_url})"
- else
- "(#{$1})"
+ Post
+ .where("raw LIKE ?", "%discussions.example.com%")
+ .each do |p|
+ begin
+ new_raw = p.raw.dup
+ # \((https?:\/\/discussions\.example\.com\/\S*-t\d+.html)\)
+ new_raw.gsub!(%r{\((https?://discussions\.example\.com/\S*-t\d+.html)\)}) do
+ normalized_url = Permalink.normalize_url($1)
+ permalink =
+ begin
+ Permalink.find_by_url(normalized_url)
+ rescue StandardError
+ nil
+ end
+ if permalink && permalink.target_url
+ "(#{permalink.target_url})"
+ else
+ "(#{$1})"
+ end
end
- end
- if new_raw != p.raw
- p.revise(Discourse.system_user, { raw: new_raw }, bypass_bump: true, skip_revision: true)
- putc "."
- i += 1
+ if new_raw != p.raw
+ p.revise(Discourse.system_user, { raw: new_raw }, bypass_bump: true, skip_revision: true)
+ putc "."
+ i += 1
+ end
+ rescue StandardError
+ # skip
end
- rescue
- # skip
end
- end
log "Done! #{i} posts remapped."
end
task "import:create_vbulletin_permalinks" => :environment do
- log 'Creating Permalinks...'
+ log "Creating Permalinks..."
# /showthread.php\?t=(\d+).*/
SiteSetting.permalink_normalizations = '/showthread.php\?t=(\d+).*/showthread.php?t=\1'
@@ -480,22 +491,30 @@ task "import:create_vbulletin_permalinks" => :environment do
Topic.listable_topics.find_each do |topic|
tcf = topic.custom_fields
if tcf && tcf["import_id"]
- Permalink.create(url: "showthread.php?t=#{tcf["import_id"]}", topic_id: topic.id) rescue nil
+ begin
+ Permalink.create(url: "showthread.php?t=#{tcf["import_id"]}", topic_id: topic.id)
+ rescue StandardError
+ nil
+ end
end
end
Category.find_each do |cat|
ccf = cat.custom_fields
if ccf && ccf["import_id"]
- Permalink.create(url: "forumdisplay.php?f=#{ccf["import_id"]}", category_id: cat.id) rescue nil
+ begin
+ Permalink.create(url: "forumdisplay.php?f=#{ccf["import_id"]}", category_id: cat.id)
+ rescue StandardError
+ nil
+ end
end
end
log "Done!"
end
-desc 'Import existing exported file'
-task 'import:file', [:file_name] => [:environment] do |_, args|
+desc "Import existing exported file"
+task "import:file", [:file_name] => [:environment] do |_, args|
require "import_export"
ImportExport.import(args[:file_name])
diff --git a/lib/tasks/incoming_emails.rake b/lib/tasks/incoming_emails.rake
index 1ea94bb98f1..0aed441f6d2 100644
--- a/lib/tasks/incoming_emails.rake
+++ b/lib/tasks/incoming_emails.rake
@@ -3,7 +3,11 @@
desc "removes attachments and truncates long raw message"
task "incoming_emails:truncate_long" => :environment do
IncomingEmail.find_each do |incoming_email|
- truncated_raw = Email::Cleaner.new(incoming_email.raw, rejected: incoming_email.rejection_message.present?).execute
+ truncated_raw =
+ Email::Cleaner.new(
+ incoming_email.raw,
+ rejected: incoming_email.rejection_message.present?,
+ ).execute
# raw email is using \n as line separator, mail gem is using \r\n
# we need to determine if anything change to avoid updating all records
diff --git a/lib/tasks/integration.rake b/lib/tasks/integration.rake
index 9f46772c2ea..66a122841d3 100644
--- a/lib/tasks/integration.rake
+++ b/lib/tasks/integration.rake
@@ -1,43 +1,36 @@
# frozen_string_literal: true
-require 'open-uri'
-
-desc 'Creates the integration fixtures. Requires a development instance running.'
-task 'integration:create_fixtures' => :environment do
+require "open-uri"
+desc "Creates the integration fixtures. Requires a development instance running."
+task "integration:create_fixtures" => :environment do
fixtures = {
- discovery: ["/latest.json", "/categories.json", "/c/bug/l/latest.json"],
+ discovery: %w[/latest.json /categories.json /c/bug/l/latest.json],
topic: ["/t/280.json"],
- user: ["/u/eviltrout.json",
- "/user_actions.json",
- "/topics/created-by/eviltrout.json"],
- static: ["/faq", '/tos', '/privacy'],
- unknown: ['/404-body']
+ user: %w[/u/eviltrout.json /user_actions.json /topics/created-by/eviltrout.json],
+ static: %w[/faq /tos /privacy],
+ unknown: ["/404-body"],
}
fixtures.each do |type, urls|
-
filename = "#{Rails.root}/test/javascripts/fixtures/#{type}_fixtures.js"
content = "export default {\n"
urls.each do |url|
-
http_result = fake_xhr("http://localhost:3000#{url}")
# If the result is not JSON, convert it to JSON
begin
parsed = ::JSON.parse(http_result)
- rescue
+ rescue StandardError
http_result = http_result.to_json
end
content << "\"#{url}\": #{http_result},\n"
-
end
content << "};\n"
File.write(filename, content)
end
-
end
def fake_xhr(url)
@@ -52,5 +45,4 @@ def fake_xhr(url)
end
result
-
end
diff --git a/lib/tasks/javascript.rake b/lib/tasks/javascript.rake
index ebdbe1702b6..2f701589f73 100644
--- a/lib/tasks/javascript.rake
+++ b/lib/tasks/javascript.rake
@@ -17,10 +17,11 @@ def library_src
end
def html_for_section(group)
- icons = group["icons"].map do |icon|
- class_attr = icon["diversity"] ? " class=\"diversity\"" : ""
- " {{replace-emoji \":#{icon['name']}:\" (hash lazy=true#{class_attr} tabIndex=\"0\")}}"
- end
+ icons =
+ group["icons"].map do |icon|
+ class_attr = icon["diversity"] ? " class=\"diversity\"" : ""
+ " {{replace-emoji \":#{icon["name"]}:\" (hash lazy=true#{class_attr} tabIndex=\"0\")}}"
+ end
<<~HTML
<div class="section" data-section="#{group["name"]}">
@@ -45,7 +46,7 @@ def write_template(path, task_name, template)
File.write(output_path, "#{header}\n\n#{template}")
puts "#{basename} created"
- %x{yarn run prettier --write #{output_path}}
+ `yarn run prettier --write #{output_path}`
puts "#{basename} prettified"
end
@@ -58,109 +59,89 @@ def write_hbs_template(path, task_name, template)
basename = File.basename(path)
output_path = "#{Rails.root}/app/assets/javascripts/#{path}"
File.write(output_path, "#{header}\n#{template}")
- %x{yarn run prettier --write #{output_path}}
+ `yarn run prettier --write #{output_path}`
puts "#{basename} created"
end
def dependencies
[
+ { source: "ace-builds/src-min-noconflict/ace.js", destination: "ace.js", public: true },
{
- source: 'ace-builds/src-min-noconflict/ace.js',
- destination: 'ace.js',
- public: true
- }, {
- source: '@json-editor/json-editor/dist/jsoneditor.js',
- package_name: '@json-editor/json-editor',
- public: true
- }, {
- source: 'chart.js/dist/chart.min.js',
- public: true
- }, {
- source: 'chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.min.js',
- public: true
- }, {
- source: 'diffhtml/dist/diffhtml.min.js',
- public: true
- }, {
- source: 'magnific-popup/dist/jquery.magnific-popup.min.js',
- public: true
- }, {
- source: 'pikaday/pikaday.js',
- public: true
- }, {
- source: '@highlightjs/cdn-assets/.',
- destination: 'highlightjs'
- }, {
- source: 'moment/moment.js'
- }, {
- source: 'moment/locale/.',
- destination: 'moment-locale',
- }, {
- source: 'moment-timezone/builds/moment-timezone-with-data-10-year-range.js',
- destination: 'moment-timezone-with-data.js'
- }, {
- source: '@discourse/moment-timezone-names-translations/locales/.',
- destination: 'moment-timezone-names-locale'
- }, {
- source: 'workbox-sw/build/.',
- destination: 'workbox',
+ source: "@json-editor/json-editor/dist/jsoneditor.js",
+ package_name: "@json-editor/json-editor",
public: true,
- skip_versioning: true
- }, {
- source: 'workbox-routing/build/.',
- destination: 'workbox',
- public: true,
- skip_versioning: true
- }, {
- source: 'workbox-core/build/.',
- destination: 'workbox',
+ },
+ { source: "chart.js/dist/chart.min.js", public: true },
+ { source: "chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.min.js", public: true },
+ { source: "diffhtml/dist/diffhtml.min.js", public: true },
+ { source: "magnific-popup/dist/jquery.magnific-popup.min.js", public: true },
+ { source: "pikaday/pikaday.js", public: true },
+ { source: "@highlightjs/cdn-assets/.", destination: "highlightjs" },
+ { source: "moment/moment.js" },
+ { source: "moment/locale/.", destination: "moment-locale" },
+ {
+ source: "moment-timezone/builds/moment-timezone-with-data-10-year-range.js",
+ destination: "moment-timezone-with-data.js",
+ },
+ {
+ source: "@discourse/moment-timezone-names-translations/locales/.",
+ destination: "moment-timezone-names-locale",
+ },
+ { source: "workbox-sw/build/.", destination: "workbox", public: true, skip_versioning: true },
+ {
+ source: "workbox-routing/build/.",
+ destination: "workbox",
public: true,
- skip_versioning: true
- }, {
- source: 'workbox-strategies/build/.',
- destination: 'workbox',
+ skip_versioning: true,
+ },
+ { source: "workbox-core/build/.", destination: "workbox", public: true, skip_versioning: true },
+ {
+ source: "workbox-strategies/build/.",
+ destination: "workbox",
public: true,
- skip_versioning: true
- }, {
- source: 'workbox-expiration/build/.',
- destination: 'workbox',
+ skip_versioning: true,
+ },
+ {
+ source: "workbox-expiration/build/.",
+ destination: "workbox",
public: true,
- skip_versioning: true
- }, {
- source: 'workbox-cacheable-response/build/.',
- destination: 'workbox',
skip_versioning: true,
- public: true
},
{
- source: 'squoosh/codecs/mozjpeg/enc/mozjpeg_enc.js',
- destination: 'squoosh',
+ source: "workbox-cacheable-response/build/.",
+ destination: "workbox",
+ skip_versioning: true,
public: true,
- skip_versioning: true
},
{
- source: 'squoosh/codecs/mozjpeg/enc/mozjpeg_enc.wasm',
- destination: 'squoosh',
+ source: "squoosh/codecs/mozjpeg/enc/mozjpeg_enc.js",
+ destination: "squoosh",
public: true,
- skip_versioning: true
+ skip_versioning: true,
+ },
+ {
+ source: "squoosh/codecs/mozjpeg/enc/mozjpeg_enc.wasm",
+ destination: "squoosh",
+ public: true,
+ skip_versioning: true,
},
{
- source: 'squoosh/codecs/resize/pkg/squoosh_resize.js',
- destination: 'squoosh',
+ source: "squoosh/codecs/resize/pkg/squoosh_resize.js",
+ destination: "squoosh",
public: true,
- skip_versioning: true
+ skip_versioning: true,
},
{
- source: 'squoosh/codecs/resize/pkg/squoosh_resize_bg.wasm',
- destination: 'squoosh',
+ source: "squoosh/codecs/resize/pkg/squoosh_resize_bg.wasm",
+ destination: "squoosh",
public: true,
- skip_versioning: true
- }
+ skip_versioning: true,
+ },
]
end
def node_package_name(f)
- f[:package_name] || f[:source].split('/').first
+ f[:package_name] || f[:source].split("/").first
end
def public_path_name(f)
@@ -175,8 +156,8 @@ def absolute_sourcemap(dest)
end
end
-task 'javascript:update_constants' => :environment do
- task_name = 'update_constants'
+task "javascript:update_constants" => :environment do
+ task_name = "update_constants"
write_template("discourse/app/lib/constants.js", task_name, <<~JS)
export const SEARCH_PRIORITIES = #{Searchable::PRIORITIES.to_json};
@@ -184,9 +165,7 @@ task 'javascript:update_constants' => :environment do
export const SEARCH_PHRASE_REGEXP = '#{Search::PHRASE_MATCH_REGEXP_PATTERN}';
JS
- pretty_notifications = Notification.types.map do |n|
- " #{n[0]}: #{n[1]},"
- end.join("\n")
+ pretty_notifications = Notification.types.map { |n| " #{n[0]}: #{n[1]}," }.join("\n")
write_template("discourse/tests/fixtures/concerns/notification-types.js", task_name, <<~JS)
export const NOTIFICATION_TYPES = {
@@ -209,24 +188,21 @@ task 'javascript:update_constants' => :environment do
groups_json = JSON.parse(File.read("lib/emoji/groups.json"))
- emoji_buttons = groups_json.map do |group|
- <<~HTML
+ emoji_buttons = groups_json.map { |group| <<~HTML }
<button type="button" data-section="#{group["name"]}" {{on "click" (fn this.onCategorySelection "#{group["name"]}")}} class="btn btn-default category-button emoji">
{{replace-emoji ":#{group["tabicon"]}:"}}
</button>
HTML
- end
emoji_sections = groups_json.map { |group| html_for_section(group) }
components_dir = "discourse/app/templates/components"
write_hbs_template("#{components_dir}/emoji-group-buttons.hbs", task_name, emoji_buttons.join)
write_hbs_template("#{components_dir}/emoji-group-sections.hbs", task_name, emoji_sections.join)
-
end
-task 'javascript:update' => 'clean_up' do
- require 'uglifier'
+task "javascript:update" => "clean_up" do
+ require "uglifier"
yarn = system("yarn install")
abort('Unable to run "yarn install"') unless yarn
@@ -248,8 +224,8 @@ task 'javascript:update' => 'clean_up' do
system("rm -rf node_modules/@highlightjs/cdn-assets/styles")
# We don't need every language for tests
- langs = ['javascript', 'sql', 'ruby']
- test_bundle_dest = 'vendor/assets/javascripts/highlightjs/highlight-test-bundle.min.js'
+ langs = %w[javascript sql ruby]
+ test_bundle_dest = "vendor/assets/javascripts/highlightjs/highlight-test-bundle.min.js"
File.write(test_bundle_dest, HighlightJs.bundle(langs))
end
@@ -260,7 +236,8 @@ task 'javascript:update' => 'clean_up' do
dest = "#{public_js}/#{filename}"
else
package_dir_name = public_path_name(f)
- package_version = JSON.parse(File.read("#{library_src}/#{node_package_name(f)}/package.json"))["version"]
+ package_version =
+ JSON.parse(File.read("#{library_src}/#{node_package_name(f)}/package.json"))["version"]
versions[filename.downcase] = "#{package_dir_name}/#{package_version}/#{filename}"
path = "#{public_js}/#{package_dir_name}/#{package_version}"
@@ -275,16 +252,20 @@ task 'javascript:update' => 'clean_up' do
if src.include? "ace.js"
versions["ace/ace.js"] = versions.delete("ace.js")
ace_root = "#{library_src}/ace-builds/src-min-noconflict/"
- addtl_files = [ "ext-searchbox", "mode-html", "mode-scss", "mode-sql", "theme-chrome", "theme-chaos", "worker-html"]
- dest_path = dest.split('/')[0..-2].join('/')
- addtl_files.each do |file|
- FileUtils.cp_r("#{ace_root}#{file}.js", dest_path)
- end
+ addtl_files = %w[
+ ext-searchbox
+ mode-html
+ mode-scss
+ mode-sql
+ theme-chrome
+ theme-chaos
+ worker-html
+ ]
+ dest_path = dest.split("/")[0..-2].join("/")
+ addtl_files.each { |file| FileUtils.cp_r("#{ace_root}#{file}.js", dest_path) }
end
- unless File.exist?(dest)
- STDERR.puts "New dependency added: #{dest}"
- end
+ STDERR.puts "New dependency added: #{dest}" unless File.exist?(dest)
if f[:uglify]
File.write(dest, Uglifier.new.compile(File.read(src)))
@@ -300,7 +281,7 @@ task 'javascript:update' => 'clean_up' do
STDERR.puts "Completed copying dependencies: #{(Time.now - start).round(2)} secs"
end
-task 'javascript:clean_up' do
+task "javascript:clean_up" do
processed = []
dependencies.each do |f|
next unless f[:public] && !f[:skip_versioning]
@@ -308,7 +289,7 @@ task 'javascript:clean_up' do
package_dir_name = public_path_name(f)
next if processed.include?(package_dir_name)
- versions = Dir["#{File.join(public_js, package_dir_name)}/*"].collect { |p| p.split('/').last }
+ versions = Dir["#{File.join(public_js, package_dir_name)}/*"].collect { |p| p.split("/").last }
next unless versions.present?
versions = versions.sort { |a, b| Gem::Version.new(a) <=> Gem::Version.new(b) }
diff --git a/lib/tasks/maxminddb.rake b/lib/tasks/maxminddb.rake
index 4565f34258b..ffb6a06514d 100644
--- a/lib/tasks/maxminddb.rake
+++ b/lib/tasks/maxminddb.rake
@@ -2,11 +2,11 @@
desc "downloads MaxMind's GeoLite2-City database"
task "maxminddb:get" do
- require 'discourse_ip_info'
+ require "discourse_ip_info"
puts "Downloading MaxMindDb's GeoLite2-City..."
- DiscourseIpInfo.mmdb_download('GeoLite2-City')
+ DiscourseIpInfo.mmdb_download("GeoLite2-City")
puts "Downloading MaxMindDb's GeoLite2-ASN..."
- DiscourseIpInfo.mmdb_download('GeoLite2-ASN')
+ DiscourseIpInfo.mmdb_download("GeoLite2-ASN")
end
diff --git a/lib/tasks/plugin.rake b/lib/tasks/plugin.rake
index c3c822eed45..32255f2f301 100644
--- a/lib/tasks/plugin.rake
+++ b/lib/tasks/plugin.rake
@@ -1,33 +1,27 @@
# frozen_string_literal: true
-directory 'plugins'
+directory "plugins"
-desc 'install all official plugins (use GIT_WRITE=1 to pull with write access)'
-task 'plugin:install_all_official' do
- skip = Set.new([
- 'customer-flair',
- 'lazy-yt',
- 'poll'
- ])
+desc "install all official plugins (use GIT_WRITE=1 to pull with write access)"
+task "plugin:install_all_official" do
+ skip = Set.new(%w[customer-flair lazy-yt poll])
- map = {
- 'Canned Replies' => 'https://github.com/discourse/discourse-canned-replies'
- }
+ map = { "Canned Replies" => "https://github.com/discourse/discourse-canned-replies" }
- STDERR.puts "Allowing write to all repos!" if ENV['GIT_WRITE']
+ STDERR.puts "Allowing write to all repos!" if ENV["GIT_WRITE"]
Plugin::Metadata::OFFICIAL_PLUGINS.each do |name|
next if skip.include? name
repo = map[name] || "https://github.com/discourse/#{name}"
- dir = repo.split('/').last
- path = File.expand_path('plugins/' + dir)
+ dir = repo.split("/").last
+ path = File.expand_path("plugins/" + dir)
if Dir.exist? path
STDERR.puts "Skipping #{dir} cause it already exists!"
next
end
- if ENV['GIT_WRITE']
+ if ENV["GIT_WRITE"]
repo = repo.gsub("https://github.com/", "[email protected]:")
repo += ".git"
end
@@ -37,63 +31,62 @@ task 'plugin:install_all_official' do
attempts += 1
system("git clone #{repo} #{path}", exception: true)
rescue StandardError
- if attempts >= 3
- abort("Failed to clone #{repo}")
- end
+ abort("Failed to clone #{repo}") if attempts >= 3
STDERR.puts "Failed to clone #{repo}... trying again..."
retry
end
end
end
-desc 'install plugin'
-task 'plugin:install', :repo do |t, args|
- repo = ENV['REPO'] || ENV['repo'] || args[:repo]
- name = ENV['NAME'] || ENV['name'] || File.basename(repo, '.git')
+desc "install plugin"
+task "plugin:install", :repo do |t, args|
+ repo = ENV["REPO"] || ENV["repo"] || args[:repo]
+ name = ENV["NAME"] || ENV["name"] || File.basename(repo, ".git")
- plugin_path = File.expand_path('plugins/' + name)
+ plugin_path = File.expand_path("plugins/" + name)
if File.directory?(File.expand_path(plugin_path))
- abort('Plugin directory, ' + plugin_path + ', already exists.')
+ abort("Plugin directory, " + plugin_path + ", already exists.")
end
- clone_status = system('git clone ' + repo + ' ' + plugin_path)
+ clone_status = system("git clone " + repo + " " + plugin_path)
unless clone_status
FileUtils.rm_rf(plugin_path)
- abort('Unable to clone plugin')
+ abort("Unable to clone plugin")
end
end
-desc 'update all plugins'
-task 'plugin:update_all' do |t|
+desc "update all plugins"
+task "plugin:update_all" do |t|
# Loop through each directory
- plugins = Dir.glob(File.expand_path('plugins/*')).select { |f| File.directory? f }
+ plugins = Dir.glob(File.expand_path("plugins/*")).select { |f| File.directory? f }
# run plugin:update
plugins.each do |plugin|
next unless File.directory?(plugin + "/.git")
- Rake::Task['plugin:update'].invoke(plugin)
- Rake::Task['plugin:update'].reenable
+ Rake::Task["plugin:update"].invoke(plugin)
+ Rake::Task["plugin:update"].reenable
end
- Rake::Task['plugin:versions'].invoke
+ Rake::Task["plugin:versions"].invoke
end
-desc 'update a plugin'
-task 'plugin:update', :plugin do |t, args|
- plugin = ENV['PLUGIN'] || ENV['plugin'] || args[:plugin]
+desc "update a plugin"
+task "plugin:update", :plugin do |t, args|
+ plugin = ENV["PLUGIN"] || ENV["plugin"] || args[:plugin]
plugin_path = plugin
plugin = File.basename(plugin)
unless File.directory?(plugin_path)
- if File.directory?('plugins/' + plugin)
- plugin_path = File.expand_path('plugins/' + plugin)
+ if File.directory?("plugins/" + plugin)
+ plugin_path = File.expand_path("plugins/" + plugin)
else
- abort('Plugin ' + plugin + ' not found')
+ abort("Plugin " + plugin + " not found")
end
end
`git -C '#{plugin_path}' fetch origin --tags --force`
- upstream_branch = `git -C '#{plugin_path}' for-each-ref --format='%(upstream:short)' $(git -C '#{plugin_path}' symbolic-ref -q HEAD)`.strip
- has_origin_main = `git -C '#{plugin_path}' branch -a`.match?(/remotes\/origin\/main$/)
+ upstream_branch =
+ `git -C '#{plugin_path}' for-each-ref --format='%(upstream:short)' $(git -C '#{plugin_path}' symbolic-ref -q HEAD)`.strip
+ has_origin_main = `git -C '#{plugin_path}' branch -a`.match?(%r{remotes/origin/main$})
has_local_main = `git -C '#{plugin_path}' show-ref refs/heads/main`.present?
if upstream_branch == "origin/master" && has_origin_main
@@ -113,36 +106,34 @@ task 'plugin:update', :plugin do |t, args|
abort("Unable to pull latest version of plugin #{plugin_path}") unless update_status
end
-desc 'pull compatible plugin versions for all plugins'
-task 'plugin:pull_compatible_all' do |t|
- if GlobalSetting.load_plugins?
- STDERR.puts <<~TEXT
+desc "pull compatible plugin versions for all plugins"
+task "plugin:pull_compatible_all" do |t|
+ STDERR.puts <<~TEXT if GlobalSetting.load_plugins?
WARNING: Plugins were activated before running `rake plugin:pull_compatible_all`
You should prefix this command with LOAD_PLUGINS=0
TEXT
- end
# Loop through each directory
- plugins = Dir.glob(File.expand_path('plugins/*')).select { |f| File.directory? f }
+ plugins = Dir.glob(File.expand_path("plugins/*")).select { |f| File.directory? f }
# run plugin:pull_compatible
plugins.each do |plugin|
next unless File.directory?(plugin + "/.git")
- Rake::Task['plugin:pull_compatible'].invoke(plugin)
- Rake::Task['plugin:pull_compatible'].reenable
+ Rake::Task["plugin:pull_compatible"].invoke(plugin)
+ Rake::Task["plugin:pull_compatible"].reenable
end
end
-desc 'pull a compatible plugin version'
-task 'plugin:pull_compatible', :plugin do |t, args|
- plugin = ENV['PLUGIN'] || ENV['plugin'] || args[:plugin]
+desc "pull a compatible plugin version"
+task "plugin:pull_compatible", :plugin do |t, args|
+ plugin = ENV["PLUGIN"] || ENV["plugin"] || args[:plugin]
plugin_path = plugin
plugin = File.basename(plugin)
unless File.directory?(plugin_path)
- if File.directory?('plugins/' + plugin)
- plugin_path = File.expand_path('plugins/' + plugin)
+ if File.directory?("plugins/" + plugin)
+ plugin_path = File.expand_path("plugins/" + plugin)
else
- abort('Plugin ' + plugin + ' not found')
+ abort("Plugin " + plugin + " not found")
end
end
@@ -151,23 +142,26 @@ task 'plugin:pull_compatible', :plugin do |t, args|
# Checkout value of the version compat
if checkout_version
puts "checking out compatible #{plugin} version: #{checkout_version}"
- update_status = system("git -C '#{plugin_path}' cat-file -e #{checkout_version} || git -C '#{plugin_path}' fetch --depth 1 $(git -C '#{plugin_path}' rev-parse --symbolic-full-name @{upstream} | awk -F '/' '{print $3}') #{checkout_version}; git -C '#{plugin_path}' reset --hard #{checkout_version}")
- abort('Unable to checkout a compatible plugin version') unless update_status
+ update_status =
+ system(
+ "git -C '#{plugin_path}' cat-file -e #{checkout_version} || git -C '#{plugin_path}' fetch --depth 1 $(git -C '#{plugin_path}' rev-parse --symbolic-full-name @{upstream} | awk -F '/' '{print $3}') #{checkout_version}; git -C '#{plugin_path}' reset --hard #{checkout_version}",
+ )
+ abort("Unable to checkout a compatible plugin version") unless update_status
else
puts "#{plugin} is already at latest compatible version"
end
end
-desc 'install all plugin gems'
-task 'plugin:install_all_gems' do |t|
+desc "install all plugin gems"
+task "plugin:install_all_gems" do |t|
# Left intentionally blank.
# When the app is being loaded, all missing gems are installed
# See: lib/plugin_gem.rb
puts "Done"
end
-desc 'install plugin gems'
-task 'plugin:install_gems', :plugin do |t, args|
+desc "install plugin gems"
+task "plugin:install_gems", :plugin do |t, args|
# Left intentionally blank.
# When the app is being loaded, all missing gems are installed
# See: lib/plugin_gem.rb
@@ -176,9 +170,9 @@ end
def spec(plugin, parallel: false)
params = []
- params << '--profile' if !parallel
- params << '--fail-fast' if ENV['RSPEC_FAILFAST']
- params << "--seed #{ENV['RSPEC_SEED']}" if Integer(ENV['RSPEC_SEED'], exception: false)
+ params << "--profile" if !parallel
+ params << "--fail-fast" if ENV["RSPEC_FAILFAST"]
+ params << "--seed #{ENV["RSPEC_SEED"]}" if Integer(ENV["RSPEC_SEED"], exception: false)
ruby = `which ruby`.strip
# reject system specs as they are slow and need dedicated setup
@@ -186,32 +180,32 @@ def spec(plugin, parallel: false)
Dir.glob("./plugins/#{plugin}/spec/**/*_spec.rb").reject { |f| f.include?("spec/system/") }.sort
if files.length > 0
cmd = parallel ? "bin/turbo_rspec" : "bin/rspec"
- sh "LOAD_PLUGINS=1 #{cmd} #{files.join(' ')} #{params.join(' ')}"
+ sh "LOAD_PLUGINS=1 #{cmd} #{files.join(" ")} #{params.join(" ")}"
else
abort "No specs found."
end
end
-desc 'run plugin specs'
-task 'plugin:spec', :plugin do |t, args|
+desc "run plugin specs"
+task "plugin:spec", :plugin do |t, args|
args.with_defaults(plugin: "*")
spec(args[:plugin])
end
-desc 'run plugin specs in parallel'
-task 'plugin:turbo_spec', :plugin do |t, args|
+desc "run plugin specs in parallel"
+task "plugin:turbo_spec", :plugin do |t, args|
args.with_defaults(plugin: "*")
spec(args[:plugin], parallel: true)
end
-desc 'run plugin qunit tests'
-task 'plugin:qunit', [:plugin, :timeout] do |t, args|
+desc "run plugin qunit tests"
+task "plugin:qunit", %i[plugin timeout] do |t, args|
args.with_defaults(plugin: "*")
rake = "#{Rails.root}/bin/rake"
- cmd = 'LOAD_PLUGINS=1 '
- cmd += 'QUNIT_SKIP_CORE=1 '
+ cmd = "LOAD_PLUGINS=1 "
+ cmd += "QUNIT_SKIP_CORE=1 "
if args[:plugin] == "*"
puts "Running qunit tests for all plugins"
@@ -227,15 +221,13 @@ task 'plugin:qunit', [:plugin, :timeout] do |t, args|
exit $?.exitstatus
end
-desc 'run all migrations of a plugin'
-namespace 'plugin:migrate' do
+desc "run all migrations of a plugin"
+namespace "plugin:migrate" do
def list_migrations(plugin_name)
plugin_root = File.join(Rails.root, "plugins", plugin_name)
migrations_root = File.join(plugin_root, "db", "{post_migrate,migrate}", "*.rb")
Dir[migrations_root]
- .map do |migration_filename|
- File.basename(migration_filename)[/(^.*?)_/, 1].to_i
- end
+ .map { |migration_filename| File.basename(migration_filename)[/(^.*?)_/, 1].to_i }
.sort
end
@@ -250,29 +242,25 @@ namespace 'plugin:migrate' do
end
task :up, [:plugin] do |t, args|
- list_migrations(args[:plugin]).each do |migration_number|
- sh cmd(:up, migration_number)
- end
+ list_migrations(args[:plugin]).each { |migration_number| sh cmd(:up, migration_number) }
end
end
-desc 'display all plugin versions'
-task 'plugin:versions' do |t, args|
+desc "display all plugin versions"
+task "plugin:versions" do |t, args|
versions =
Dir
- .glob('*', base: 'plugins')
- .map { |plugin|
- [plugin, "plugins/#{plugin}", "plugins/#{plugin}/.git"]
- }
- .select { |plugin, plugin_dir, plugin_git_dir|
+ .glob("*", base: "plugins")
+ .map { |plugin| [plugin, "plugins/#{plugin}", "plugins/#{plugin}/.git"] }
+ .select do |plugin, plugin_dir, plugin_git_dir|
File.directory?(plugin_dir) && File.exist?(plugin_git_dir)
- }
+ end
.sort_by { |plugin, _, _| plugin }
- .map { |plugin, _, plugin_git_dir|
+ .map do |plugin, _, plugin_git_dir|
version = `git --git-dir \"#{plugin_git_dir}\" rev-parse HEAD`
abort("unable to get #{plugin} version") unless version
[plugin, version.strip[0...8]]
- }
+ end
.to_h
puts JSON.pretty_generate(versions)
diff --git a/lib/tasks/populate.rake b/lib/tasks/populate.rake
index 1ebd4d8940e..15a018db3f5 100644
--- a/lib/tasks/populate.rake
+++ b/lib/tasks/populate.rake
@@ -1,52 +1,56 @@
# frozen_string_literal: true
-desc 'Creates sample categories'
-task 'groups:populate' => ['db:load_config'] do |_, args|
+desc "Creates sample categories"
+task "groups:populate" => ["db:load_config"] do |_, args|
DiscourseDev::Group.populate!
end
-desc 'Creates sample user accounts'
-task 'users:populate' => ['db:load_config'] do |_, args|
+desc "Creates sample user accounts"
+task "users:populate" => ["db:load_config"] do |_, args|
DiscourseDev::User.populate!
end
-desc 'Creates sample categories'
-task 'categories:populate' => ['db:load_config'] do |_, args|
+desc "Creates sample categories"
+task "categories:populate" => ["db:load_config"] do |_, args|
DiscourseDev::Category.populate!
end
-desc 'Creates sample tags'
-task 'tags:populate' => ['db:load_config'] do |_, args|
+desc "Creates sample tags"
+task "tags:populate" => ["db:load_config"] do |_, args|
DiscourseDev::Tag.populate!
end
-desc 'Creates sample topics'
-task 'topics:populate' => ['db:load_config'] do |_, args|
- if ENV['IGNORE_CURRENT_COUNT'] == "true"
+desc "Creates sample topics"
+task "topics:populate" => ["db:load_config"] do |_, args|
+ if ENV["IGNORE_CURRENT_COUNT"] == "true"
DiscourseDev::Topic.populate!(ignore_current_count: true)
else
DiscourseDev::Topic.populate!
end
end
-desc 'Creates sample private messages'
-task 'private_messages:populate', [:recipient] => ['db:load_config'] do |_, args|
- args.with_defaults(type: 'string')
+desc "Creates sample private messages"
+task "private_messages:populate", [:recipient] => ["db:load_config"] do |_, args|
+ args.with_defaults(type: "string")
if !args[:recipient]
puts "ERROR: Expecting rake private_messages:populate[recipient]"
exit 1
end
- DiscourseDev::Topic.populate!(private_messages: true, recipient: args[:recipient], ignore_current_count: true)
+ DiscourseDev::Topic.populate!(
+ private_messages: true,
+ recipient: args[:recipient],
+ ignore_current_count: true,
+ )
end
-desc 'Create post revisions'
-task 'post_revisions:populate' => ['db:load_config'] do |_, args|
+desc "Create post revisions"
+task "post_revisions:populate" => ["db:load_config"] do |_, args|
DiscourseDev::PostRevision.populate!
end
-desc 'Add replies to a topic'
-task 'replies:populate', [:topic_id, :count] => ['db:load_config'] do |_, args|
+desc "Add replies to a topic"
+task "replies:populate", %i[topic_id count] => ["db:load_config"] do |_, args|
DiscourseDev::Post.add_replies!(args)
end
diff --git a/lib/tasks/posts.rake b/lib/tasks/posts.rake
index 0304e80caac..9fd1f480f3c 100644
--- a/lib/tasks/posts.rake
+++ b/lib/tasks/posts.rake
@@ -1,30 +1,28 @@
# frozen_string_literal: true
-require 'file_store/local_store'
+require "file_store/local_store"
-desc 'Update each post with latest markdown'
-task 'posts:rebake' => :environment do
- ENV['RAILS_DB'] ? rebake_posts : rebake_posts_all_sites
+desc "Update each post with latest markdown"
+task "posts:rebake" => :environment do
+ ENV["RAILS_DB"] ? rebake_posts : rebake_posts_all_sites
end
-task 'posts:rebake_uncooked_posts' => :environment do
+task "posts:rebake_uncooked_posts" => :environment do
# rebaking uncooked posts can very quickly saturate sidekiq
# this provides an insurance policy so you can safely run and stop
# this rake task without worrying about your sidekiq imploding
Jobs.run_immediately!
- ENV['RAILS_DB'] ? rebake_uncooked_posts : rebake_uncooked_posts_all_sites
+ ENV["RAILS_DB"] ? rebake_uncooked_posts : rebake_uncooked_posts_all_sites
end
def rebake_uncooked_posts_all_sites
- RailsMultisite::ConnectionManagement.each_connection do |db|
- rebake_uncooked_posts
- end
+ RailsMultisite::ConnectionManagement.each_connection { |db| rebake_uncooked_posts }
end
def rebake_uncooked_posts
puts "Rebaking uncooked posts on #{RailsMultisite::ConnectionManagement.current_db}"
- uncooked = Post.where('baked_version <> ? or baked_version IS NULL', Post::BAKED_VERSION)
+ uncooked = Post.where("baked_version <> ? or baked_version IS NULL", Post::BAKED_VERSION)
rebaked = 0
total = uncooked.count
@@ -37,9 +35,7 @@ def rebake_uncooked_posts
# may have been cooked in interim
post = uncooked.where(id: id).first
- if post
- rebake_post(post)
- end
+ rebake_post(post) if post
print_status(rebaked += 1, total)
end
@@ -47,17 +43,23 @@ def rebake_uncooked_posts
puts "", "#{rebaked} posts done!", ""
end
-desc 'Update each post with latest markdown and refresh oneboxes'
-task 'posts:refresh_oneboxes' => :environment do
- ENV['RAILS_DB'] ? rebake_posts(invalidate_oneboxes: true) : rebake_posts_all_sites(invalidate_oneboxes: true)
+desc "Update each post with latest markdown and refresh oneboxes"
+task "posts:refresh_oneboxes" => :environment do
+ if ENV["RAILS_DB"]
+ rebake_posts(invalidate_oneboxes: true)
+ else
+ rebake_posts_all_sites(invalidate_oneboxes: true)
+ end
end
-desc 'Rebake all posts with a quote using a letter_avatar'
-task 'posts:fix_letter_avatars' => :environment do
+desc "Rebake all posts with a quote using a letter_avatar"
+task "posts:fix_letter_avatars" => :environment do
next unless SiteSetting.external_system_avatars_enabled
- search = Post.where("user_id <> -1")
- .where("raw LIKE '%/letter\_avatar/%' OR cooked LIKE '%/letter\_avatar/%'")
+ search =
+ Post.where("user_id <> -1").where(
+ "raw LIKE '%/letter\_avatar/%' OR cooked LIKE '%/letter\_avatar/%'",
+ )
rebaked = 0
total = search.count
@@ -70,9 +72,9 @@ task 'posts:fix_letter_avatars' => :environment do
puts "", "#{rebaked} posts done!", ""
end
-desc 'Rebake all posts matching string/regex and optionally delay the loop'
-task 'posts:rebake_match', [:pattern, :type, :delay] => [:environment] do |_, args|
- args.with_defaults(type: 'string')
+desc "Rebake all posts matching string/regex and optionally delay the loop"
+task "posts:rebake_match", %i[pattern type delay] => [:environment] do |_, args|
+ args.with_defaults(type: "string")
pattern = args[:pattern]
type = args[:type]&.downcase
delay = args[:delay]&.to_i
@@ -83,7 +85,7 @@ task 'posts:rebake_match', [:pattern, :type, :delay] => [:environment] do |_, ar
elsif delay && delay < 1
puts "ERROR: delay parameter should be an integer and greater than 0"
exit 1
- elsif type != 'string' && type != 'regex'
+ elsif type != "string" && type != "regex"
puts "ERROR: Expecting rake posts:rebake_match[pattern,type] where type is string or regex"
exit 1
end
@@ -103,9 +105,7 @@ task 'posts:rebake_match', [:pattern, :type, :delay] => [:environment] do |_, ar
end
def rebake_posts_all_sites(opts = {})
- RailsMultisite::ConnectionManagement.each_connection do |db|
- rebake_posts(opts)
- end
+ RailsMultisite::ConnectionManagement.each_connection { |db| rebake_posts(opts) }
end
def rebake_posts(opts = {})
@@ -118,13 +118,17 @@ def rebake_posts(opts = {})
total = Post.count
rebaked = 0
batch = 1000
- Post.update_all('baked_version = NULL')
+ Post.update_all("baked_version = NULL")
(0..(total - 1).abs).step(batch) do |i|
- Post.order(id: :desc).offset(i).limit(batch).each do |post|
- rebake_post(post, opts)
- print_status(rebaked += 1, total)
- end
+ Post
+ .order(id: :desc)
+ .offset(i)
+ .limit(batch)
+ .each do |post|
+ rebake_post(post, opts)
+ print_status(rebaked += 1, total)
+ end
end
ensure
SiteSetting.disable_system_edit_notifications = disable_system_edit_notifications
@@ -134,72 +138,77 @@ def rebake_posts(opts = {})
end
def rebake_post(post, opts = {})
- if !opts[:priority]
- opts[:priority] = :ultra_low
- end
+ opts[:priority] = :ultra_low if !opts[:priority]
post.rebake!(**opts)
rescue => e
- puts "", "Failed to rebake (topic_id: #{post.topic_id}, post_id: #{post.id})", e, e.backtrace.join("\n")
+ puts "",
+ "Failed to rebake (topic_id: #{post.topic_id}, post_id: #{post.id})",
+ e,
+ e.backtrace.join("\n")
end
def print_status(current, max)
print "\r%9d / %d (%5.1f%%)" % [current, max, ((current.to_f / max.to_f) * 100).round(1)]
end
-desc 'normalize all markdown so <pre><code> is not used and instead backticks'
-task 'posts:normalize_code' => :environment do
- lang = ENV['CODE_LANG'] || ''
- require 'import/normalize'
+desc "normalize all markdown so <pre><code> is not used and instead backticks"
+task "posts:normalize_code" => :environment do
+ lang = ENV["CODE_LANG"] || ""
+ require "import/normalize"
puts "Normalizing"
i = 0
- Post.where("raw like '%<pre>%<code>%'").each do |p|
- normalized = Import::Normalize.normalize_code_blocks(p.raw, lang)
- if normalized != p.raw
- p.revise(Discourse.system_user, raw: normalized)
- putc "."
- i += 1
+ Post
+ .where("raw like '%<pre>%<code>%'")
+ .each do |p|
+ normalized = Import::Normalize.normalize_code_blocks(p.raw, lang)
+ if normalized != p.raw
+ p.revise(Discourse.system_user, raw: normalized)
+ putc "."
+ i += 1
+ end
end
- end
puts
puts "#{i} posts normalized!"
end
def remap_posts(find, type, ignore_case, replace = "")
- ignore_case = ignore_case == 'true'
+ ignore_case = ignore_case == "true"
i = 0
- Post.raw_match(find, type).find_each do |p|
- regex =
- case type
- when 'string' then
- Regexp.new(Regexp.escape(find), ignore_case)
- when 'regex' then
- Regexp.new(find, ignore_case)
- end
+ Post
+ .raw_match(find, type)
+ .find_each do |p|
+ regex =
+ case type
+ when "string"
+ Regexp.new(Regexp.escape(find), ignore_case)
+ when "regex"
+ Regexp.new(find, ignore_case)
+ end
- new_raw = p.raw.gsub(regex, replace)
+ new_raw = p.raw.gsub(regex, replace)
- if new_raw != p.raw
- begin
- p.revise(Discourse.system_user, { raw: new_raw }, bypass_bump: true, skip_revision: true)
- putc "."
- i += 1
- rescue
- puts "\nFailed to remap post (topic_id: #{p.topic_id}, post_id: #{p.id})\n"
+ if new_raw != p.raw
+ begin
+ p.revise(Discourse.system_user, { raw: new_raw }, bypass_bump: true, skip_revision: true)
+ putc "."
+ i += 1
+ rescue StandardError
+ puts "\nFailed to remap post (topic_id: #{p.topic_id}, post_id: #{p.id})\n"
+ end
end
end
- end
i
end
-desc 'Remap all posts matching specific string'
-task 'posts:remap', [:find, :replace, :type, :ignore_case] => [:environment] do |_, args|
- require 'highline/import'
+desc "Remap all posts matching specific string"
+task "posts:remap", %i[find replace type ignore_case] => [:environment] do |_, args|
+ require "highline/import"
- args.with_defaults(type: 'string', ignore_case: 'false')
+ args.with_defaults(type: "string", ignore_case: "false")
find = args[:find]
replace = args[:replace]
type = args[:type]&.downcase
@@ -211,15 +220,18 @@ task 'posts:remap', [:find, :replace, :type, :ignore_case] => [:environment] do
elsif !replace
puts "ERROR: Expecting rake posts:remap['find','replace']. Want to delete a word/string instead? Try rake posts:delete_word['word-to-delete']"
exit 1
- elsif type != 'string' && type != 'regex'
+ elsif type != "string" && type != "regex"
puts "ERROR: Expecting rake posts:remap['find','replace',type] where type is string or regex"
exit 1
- elsif ignore_case != 'true' && ignore_case != 'false'
+ elsif ignore_case != "true" && ignore_case != "false"
puts "ERROR: Expecting rake posts:remap['find','replace',type,ignore_case] where ignore_case is true or false"
exit 1
else
- confirm_replace = ask("Are you sure you want to replace all #{type} occurrences of '#{find}' with '#{replace}'? (Y/n)")
- exit 1 unless (confirm_replace == "" || confirm_replace.downcase == 'y')
+ confirm_replace =
+ ask(
+ "Are you sure you want to replace all #{type} occurrences of '#{find}' with '#{replace}'? (Y/n)",
+ )
+ exit 1 unless (confirm_replace == "" || confirm_replace.downcase == "y")
end
puts "Remapping"
@@ -227,11 +239,11 @@ task 'posts:remap', [:find, :replace, :type, :ignore_case] => [:environment] do
puts "", "#{total} posts remapped!", ""
end
-desc 'Delete occurrence of a word/string'
-task 'posts:delete_word', [:find, :type, :ignore_case] => [:environment] do |_, args|
- require 'highline/import'
+desc "Delete occurrence of a word/string"
+task "posts:delete_word", %i[find type ignore_case] => [:environment] do |_, args|
+ require "highline/import"
- args.with_defaults(type: 'string', ignore_case: 'false')
+ args.with_defaults(type: "string", ignore_case: "false")
find = args[:find]
type = args[:type]&.downcase
ignore_case = args[:ignore_case]&.downcase
@@ -239,15 +251,16 @@ task 'posts:delete_word', [:find, :type, :ignore_case] => [:environment] do |_,
if !find
puts "ERROR: Expecting rake posts:delete_word['word-to-delete']"
exit 1
- elsif type != 'string' && type != 'regex'
+ elsif type != "string" && type != "regex"
puts "ERROR: Expecting rake posts:delete_word[pattern, type] where type is string or regex"
exit 1
- elsif ignore_case != 'true' && ignore_case != 'false'
+ elsif ignore_case != "true" && ignore_case != "false"
puts "ERROR: Expecting rake posts:delete_word[pattern, type,ignore_case] where ignore_case is true or false"
exit 1
else
- confirm_delete = ask("Are you sure you want to remove all #{type} occurrences of '#{find}'? (Y/n)")
- exit 1 unless (confirm_delete == "" || confirm_delete.downcase == 'y')
+ confirm_delete =
+ ask("Are you sure you want to remove all #{type} occurrences of '#{find}'? (Y/n)")
+ exit 1 unless (confirm_delete == "" || confirm_delete.downcase == "y")
end
puts "Processing"
@@ -255,9 +268,8 @@ task 'posts:delete_word', [:find, :type, :ignore_case] => [:environment] do |_,
puts "", "#{total} posts updated!", ""
end
-desc 'Delete all likes'
-task 'posts:delete_all_likes' => :environment do
-
+desc "Delete all likes"
+task "posts:delete_all_likes" => :environment do
post_actions = PostAction.where(post_action_type_id: PostActionType.types[:like])
likes_deleted = 0
@@ -267,7 +279,7 @@ task 'posts:delete_all_likes' => :environment do
begin
post_action.remove_act!(Discourse.system_user)
print_status(likes_deleted += 1, total)
- rescue
+ rescue StandardError
# skip
end
end
@@ -277,8 +289,8 @@ task 'posts:delete_all_likes' => :environment do
puts "", "#{likes_deleted} likes deleted!", ""
end
-desc 'Refreshes each post that was received via email'
-task 'posts:refresh_emails', [:topic_id] => [:environment] do |_, args|
+desc "Refreshes each post that was received via email"
+task "posts:refresh_emails", [:topic_id] => [:environment] do |_, args|
posts = Post.where.not(raw_email: nil).where(via_email: true)
posts = posts.where(topic_id: args[:topic_id]) if args[:topic_id]
@@ -290,12 +302,17 @@ task 'posts:refresh_emails', [:topic_id] => [:environment] do |_, args|
receiver = Email::Receiver.new(post.raw_email)
body, elided = receiver.select_body
- body = receiver.add_attachments(body || '', post.user)
+ body = receiver.add_attachments(body || "", post.user)
body << Email::Receiver.elided_html(elided) if elided.present?
- post.revise(Discourse.system_user, { raw: body, cook_method: Post.cook_methods[:regular] },
- skip_revision: true, skip_validations: true, bypass_bump: true)
- rescue
+ post.revise(
+ Discourse.system_user,
+ { raw: body, cook_method: Post.cook_methods[:regular] },
+ skip_revision: true,
+ skip_validations: true,
+ bypass_bump: true,
+ )
+ rescue StandardError
puts "Failed to refresh post (topic_id: #{post.topic_id}, post_id: #{post.id})"
end
@@ -307,10 +324,9 @@ task 'posts:refresh_emails', [:topic_id] => [:environment] do |_, args|
puts "", "Done. #{updated} posts updated.", ""
end
-desc 'Reorders all posts based on their creation_date'
-task 'posts:reorder_posts', [:topic_id] => [:environment] do |_, args|
+desc "Reorders all posts based on their creation_date"
+task "posts:reorder_posts", [:topic_id] => [:environment] do |_, args|
Post.transaction do
-
builder = DB.build <<~SQL
WITH ordered_posts AS (
SELECT
@@ -342,11 +358,11 @@ task 'posts:reorder_posts', [:topic_id] => [:environment] do |_, args|
builder.exec
[
- ["notifications", "post_number"],
- ["post_timings", "post_number"],
- ["posts", "reply_to_post_number"],
- ["topic_users", "last_read_post_number"],
- ["topic_users", "last_emailed_post_number"],
+ %w[notifications post_number],
+ %w[post_timings post_number],
+ %w[posts reply_to_post_number],
+ %w[topic_users last_read_post_number],
+ %w[topic_users last_emailed_post_number],
].each do |table, column|
builder = DB.build <<~SQL
UPDATE
@@ -385,7 +401,6 @@ task 'posts:reorder_posts', [:topic_id] => [:environment] do |_, args|
builder.where("topic_id = ?", args[:topic_id]) if args[:topic_id]
builder.where("post_number < 0")
builder.exec
-
end
puts "", "Done.", ""
@@ -398,63 +413,69 @@ def missing_uploads
count_missing = 0
- missing = Post.find_missing_uploads(include_local_upload: true) do |post, src, path, sha1|
- next if sha1.present?
- puts "Fixing missing uploads: " if count_missing == 0
- count_missing += 1
+ missing =
+ Post.find_missing_uploads(include_local_upload: true) do |post, src, path, sha1|
+ next if sha1.present?
+ puts "Fixing missing uploads: " if count_missing == 0
+ count_missing += 1
- upload_id = nil
+ upload_id = nil
- # recovering old scheme upload.
- local_store = FileStore::LocalStore.new
- public_path = "#{local_store.public_dir}#{path}"
- file_path = nil
+ # recovering old scheme upload.
+ local_store = FileStore::LocalStore.new
+ public_path = "#{local_store.public_dir}#{path}"
+ file_path = nil
- if File.file?(public_path)
- file_path = public_path
- else
- tombstone_path = public_path.sub("/uploads/", "/uploads/tombstone/")
- file_path = tombstone_path if File.file?(tombstone_path)
- end
+ if File.file?(public_path)
+ file_path = public_path
+ else
+ tombstone_path = public_path.sub("/uploads/", "/uploads/tombstone/")
+ file_path = tombstone_path if File.file?(tombstone_path)
+ end
- if file_path.present?
- if (upload = UploadCreator.new(File.open(file_path), File.basename(path)).create_for(Discourse.system_user.id)).persisted?
- upload_id = upload.id
-
- post.reload
- new_raw = post.raw.dup
- new_raw = new_raw.gsub(path, upload.url)
-
- PostRevisor.new(post, Topic.with_deleted.find_by(id: post.topic_id)).revise!(
- Discourse.system_user,
- {
- raw: new_raw
- },
- skip_validations: true,
- force_new_version: true,
- bypass_bump: true
- )
-
- print "🆗"
+ if file_path.present?
+ if (
+ upload =
+ UploadCreator.new(File.open(file_path), File.basename(path)).create_for(
+ Discourse.system_user.id,
+ )
+ ).persisted?
+ upload_id = upload.id
+
+ post.reload
+ new_raw = post.raw.dup
+ new_raw = new_raw.gsub(path, upload.url)
+
+ PostRevisor.new(post, Topic.with_deleted.find_by(id: post.topic_id)).revise!(
+ Discourse.system_user,
+ { raw: new_raw },
+ skip_validations: true,
+ force_new_version: true,
+ bypass_bump: true,
+ )
+
+ print "🆗"
+ else
+ print "❌"
+ end
else
- print "❌"
+ print "🚫"
+ old_scheme_upload_count += 1
end
- else
- print "🚫"
- old_scheme_upload_count += 1
- end
- upload_id
- end
+ upload_id
+ end
puts "", "#{missing[:count]} post uploads are missing.", ""
if missing[:count] > 0
puts "#{missing[:uploads].count} uploads are missing."
- puts "#{old_scheme_upload_count} of #{missing[:uploads].count} are old scheme uploads." if old_scheme_upload_count > 0
+ if old_scheme_upload_count > 0
+ puts "#{old_scheme_upload_count} of #{missing[:uploads].count} are old scheme uploads."
+ end
puts "#{missing[:post_uploads].count} of #{Post.count} posts are affected.", ""
- if ENV['GIVE_UP'] == "1"
+ if ENV["GIVE_UP"] == "1"
missing[:post_uploads].each do |id, uploads|
post = Post.with_deleted.find_by(id: id)
if post
@@ -466,11 +487,9 @@ def missing_uploads
end
end
- if ENV['VERBOSE'] == "1"
+ if ENV["VERBOSE"] == "1"
puts "missing uploads!"
- missing[:uploads].each do |path|
- puts "#{path}"
- end
+ missing[:uploads].each { |path| puts "#{path}" }
if missing[:post_uploads].count > 0
puts
@@ -490,14 +509,12 @@ def missing_uploads
missing[:count] == 0
end
-desc 'Finds missing post upload records from cooked HTML content'
-task 'posts:missing_uploads' => :environment do |_, args|
+desc "Finds missing post upload records from cooked HTML content"
+task "posts:missing_uploads" => :environment do |_, args|
if ENV["RAILS_DB"]
missing_uploads
else
- RailsMultisite::ConnectionManagement.each_connection do
- missing_uploads
- end
+ RailsMultisite::ConnectionManagement.each_connection { missing_uploads }
end
end
@@ -506,56 +523,55 @@ def recover_uploads_from_index(path)
db = RailsMultisite::ConnectionManagement.current_db
cdn_path = SiteSetting.cdn_path("/uploads/#{db}").sub(/https?:/, "")
- Post.where("cooked LIKE ?", "%#{cdn_path}%").each do |post|
- regex = Regexp.new("((https?:)?#{Regexp.escape(cdn_path)}[^,;\\]\\>\\t\\n\\s)\"\']+)")
- uploads = []
- post.raw.scan(regex).each do |match|
- uploads << match[0]
- end
-
- if uploads.length > 0
- lookup << [post.id, uploads]
- else
- print "."
- post.rebake!
+ Post
+ .where("cooked LIKE ?", "%#{cdn_path}%")
+ .each do |post|
+ regex = Regexp.new("((https?:)?#{Regexp.escape(cdn_path)}[^,;\\]\\>\\t\\n\\s)\"\']+)")
+ uploads = []
+ post.raw.scan(regex).each { |match| uploads << match[0] }
+
+ if uploads.length > 0
+ lookup << [post.id, uploads]
+ else
+ print "."
+ post.rebake!
+ end
end
- end
- PostCustomField.where(name: Post::MISSING_UPLOADS).pluck(:post_id, :value).each do |post_id, uploads|
- uploads = JSON.parse(uploads)
- raw = Post.where(id: post_id).pluck_first(:raw)
- uploads.map! do |upload|
- orig = upload
- if raw.scan(upload).length == 0
- upload = upload.sub(SiteSetting.Upload.s3_cdn_url, SiteSetting.Upload.s3_base_url)
- end
- if raw.scan(upload).length == 0
- upload = upload.sub(SiteSetting.Upload.s3_base_url, Discourse.base_url)
- end
- if raw.scan(upload).length == 0
- upload = upload.sub(Discourse.base_url + "/", "/")
- end
- if raw.scan(upload).length == 0
- # last resort, try for sha
- sha = upload.split("/")[-1]
- sha = sha.split(".")[0]
-
- if sha.length == 40 && raw.scan(sha).length == 1
- raw.match(Regexp.new("([^\"'<\\s\\n]+#{sha}[^\"'>\\s\\n]+)"))
- upload = $1
+ PostCustomField
+ .where(name: Post::MISSING_UPLOADS)
+ .pluck(:post_id, :value)
+ .each do |post_id, uploads|
+ uploads = JSON.parse(uploads)
+ raw = Post.where(id: post_id).pluck_first(:raw)
+ uploads.map! do |upload|
+ orig = upload
+ if raw.scan(upload).length == 0
+ upload = upload.sub(SiteSetting.Upload.s3_cdn_url, SiteSetting.Upload.s3_base_url)
end
+ if raw.scan(upload).length == 0
+ upload = upload.sub(SiteSetting.Upload.s3_base_url, Discourse.base_url)
+ end
+ upload = upload.sub(Discourse.base_url + "/", "/") if raw.scan(upload).length == 0
+ if raw.scan(upload).length == 0
+ # last resort, try for sha
+ sha = upload.split("/")[-1]
+ sha = sha.split(".")[0]
+
+ if sha.length == 40 && raw.scan(sha).length == 1
+ raw.match(Regexp.new("([^\"'<\\s\\n]+#{sha}[^\"'>\\s\\n]+)"))
+ upload = $1
+ end
+ end
+ if raw.scan(upload).length == 0
+ puts "can not find #{orig} in\n\n#{raw}"
+ upload = nil
+ end
+ upload
end
- if raw.scan(upload).length == 0
- puts "can not find #{orig} in\n\n#{raw}"
- upload = nil
- end
- upload
+ uploads.compact!
+ lookup << [post_id, uploads] if uploads.length > 0
end
- uploads.compact!
- if uploads.length > 0
- lookup << [post_id, uploads]
- end
- end
lookup.each do |post_id, uploads|
post = Post.find(post_id)
@@ -573,7 +589,12 @@ def recover_uploads_from_index(path)
puts "Skipping #{url} in #{post.full_url} cause it appears to have a short file name"
next
end
- found = `cat #{path} | grep #{name} | grep original`.split("\n")[0] rescue nil
+ found =
+ begin
+ `cat #{path} | grep #{name} | grep original`.split("\n")[0]
+ rescue StandardError
+ nil
+ end
if found.blank?
puts "Skipping #{url} in #{post.full_url} cause it missing from index"
next
@@ -609,8 +630,8 @@ def recover_uploads_from_index(path)
end
end
-desc 'Attempts to recover missing uploads from an index file'
-task 'posts:recover_uploads_from_index' => :environment do |_, args|
+desc "Attempts to recover missing uploads from an index file"
+task "posts:recover_uploads_from_index" => :environment do |_, args|
path = File.expand_path(Rails.root + "public/uploads/all_the_files")
if File.exist?(path)
puts "Found existing index file at #{path}"
@@ -621,14 +642,12 @@ task 'posts:recover_uploads_from_index' => :environment do |_, args|
if RailsMultisite::ConnectionManagement.current_db != "default"
recover_uploads_from_index(path)
else
- RailsMultisite::ConnectionManagement.each_connection do
- recover_uploads_from_index(path)
- end
+ RailsMultisite::ConnectionManagement.each_connection { recover_uploads_from_index(path) }
end
end
-desc 'invalidate broken images'
-task 'posts:invalidate_broken_images' => :environment do
+desc "invalidate broken images"
+task "posts:invalidate_broken_images" => :environment do
puts "Invalidating broken images.."
posts = Post.where("raw like '%<img%'")
@@ -646,8 +665,8 @@ task 'posts:invalidate_broken_images' => :environment do
end
desc "Coverts full upload URLs in `Post#raw` to short upload url"
-task 'posts:inline_uploads' => :environment do |_, args|
- if ENV['RAILS_DB']
+task "posts:inline_uploads" => :environment do |_, args|
+ if ENV["RAILS_DB"]
correct_inline_uploads
else
RailsMultisite::ConnectionManagement.each_connection do |db|
@@ -662,11 +681,14 @@ def correct_inline_uploads
dry_run = (ENV["DRY_RUN"].nil? ? true : ENV["DRY_RUN"] != "false")
verbose = ENV["VERBOSE"]
- scope = Post.joins(:upload_references).distinct("posts.id")
- .where(
- "raw LIKE ?",
- "%/uploads/#{RailsMultisite::ConnectionManagement.current_db}/original/%",
- )
+ scope =
+ Post
+ .joins(:upload_references)
+ .distinct("posts.id")
+ .where(
+ "raw LIKE ?",
+ "%/uploads/#{RailsMultisite::ConnectionManagement.current_db}/original/%",
+ )
affected_posts_count = scope.count
fixed_count = 0
@@ -684,20 +706,17 @@ def correct_inline_uploads
if post.raw != new_raw
if !dry_run
- PostRevisor.new(post, Topic.with_deleted.find_by(id: post.topic_id))
- .revise!(
- Discourse.system_user,
- {
- raw: new_raw
- },
- skip_validations: true,
- force_new_version: true,
- bypass_bump: true
- )
+ PostRevisor.new(post, Topic.with_deleted.find_by(id: post.topic_id)).revise!(
+ Discourse.system_user,
+ { raw: new_raw },
+ skip_validations: true,
+ force_new_version: true,
+ bypass_bump: true,
+ )
end
if verbose
- require 'diffy'
+ require "diffy"
Diffy::Diff.default_format = :color
puts "Cooked diff for Post #{post.id}"
puts Diffy::Diff.new(PrettyText.cook(post.raw), PrettyText.cook(new_raw), context: 1)
@@ -713,7 +732,7 @@ def correct_inline_uploads
putc "X"
not_corrected_post_ids << post.id
end
- rescue
+ rescue StandardError
putc "!"
failed_to_correct_post_ids << post.id
end
@@ -730,7 +749,5 @@ def correct_inline_uploads
puts "Ids of posts that encountered failures: #{failed_to_correct_post_ids}"
end
- if dry_run
- puts "Task was ran in dry run mode. Set `DRY_RUN=false` to revise affected posts"
- end
+ puts "Task was ran in dry run mode. Set `DRY_RUN=false` to revise affected posts" if dry_run
end
diff --git a/lib/tasks/profile.rake b/lib/tasks/profile.rake
index 1b44ff3511c..ec4df4b3f0d 100644
--- a/lib/tasks/profile.rake
+++ b/lib/tasks/profile.rake
@@ -2,23 +2,26 @@
desc "generate a user api key for given user in profiling environment"
task "user_api_key:create", [:username] => :environment do |task, args|
- raise "user_api_key:create rake task is only meant for the profiling env" if ENV["RAILS_ENV"] != "profile"
+ if ENV["RAILS_ENV"] != "profile"
+ raise "user_api_key:create rake task is only meant for the profiling env"
+ end
raise "Supply a username for the key" if !args[:username]
user = User.find_by_username(args[:username])
raise "'#{args[:username]}' is not a valid username" if !user
- application_name = 'perf test application'
+ application_name = "perf test application"
user_api_key = UserApiKey.where(application_name: application_name).destroy_all
- user_api_key = UserApiKey.create!(
- application_name: application_name,
- client_id: '1234',
- scopes: ['read'].map { |name| UserApiKeyScope.new(name: name) },
- user_id: user.id
- )
+ user_api_key =
+ UserApiKey.create!(
+ application_name: application_name,
+ client_id: "1234",
+ scopes: ["read"].map { |name| UserApiKeyScope.new(name: name) },
+ user_id: user.id,
+ )
puts user_api_key.key
end
diff --git a/lib/tasks/qunit.rake b/lib/tasks/qunit.rake
index 76781a4cd79..16cc88ad44c 100644
--- a/lib/tasks/qunit.rake
+++ b/lib/tasks/qunit.rake
@@ -1,7 +1,7 @@
# frozen_string_literal: true
desc "Runs the qunit test suite"
-task "qunit:test", [:timeout, :qunit_path, :filter] do |_, args|
+task "qunit:test", %i[timeout qunit_path filter] do |_, args|
require "socket"
require "chrome_installed_checker"
@@ -15,7 +15,7 @@ task "qunit:test", [:timeout, :qunit_path, :filter] do |_, args|
abort "Yarn is not installed. Download from https://yarnpkg.com/lang/en/docs/install/"
end
- report_requests = ENV['REPORT_REQUESTS'] == "1"
+ report_requests = ENV["REPORT_REQUESTS"] == "1"
system("yarn install")
@@ -32,15 +32,11 @@ task "qunit:test", [:timeout, :qunit_path, :filter] do |_, args|
puts "The 'legacy' ember environment is discontinued - running tests with ember-cli assets..."
end
- port = ENV['TEST_SERVER_PORT'] || 60099
- while !port_available? port
- port += 1
- end
+ port = ENV["TEST_SERVER_PORT"] || 60_099
+ port += 1 while !port_available? port
- unicorn_port = 60098
- while unicorn_port == port || !port_available?(unicorn_port)
- unicorn_port += 1
- end
+ unicorn_port = 60_098
+ unicorn_port += 1 while unicorn_port == port || !port_available?(unicorn_port)
env = {
"RAILS_ENV" => ENV["QUNIT_RAILS_ENV"] || "test",
@@ -55,11 +51,7 @@ task "qunit:test", [:timeout, :qunit_path, :filter] do |_, args|
"UNICORN_TIMEOUT" => "90",
}
- pid = Process.spawn(
- env,
- "#{Rails.root}/bin/unicorn",
- pgroup: true
- )
+ pid = Process.spawn(env, "#{Rails.root}/bin/unicorn", pgroup: true)
begin
success = true
@@ -69,13 +61,17 @@ task "qunit:test", [:timeout, :qunit_path, :filter] do |_, args|
options = { seed: (ENV["QUNIT_SEED"] || Random.new.seed), hidepassed: 1 }
- %w{module filter qunit_skip_core qunit_single_plugin theme_name theme_url theme_id}.each do |arg|
- options[arg] = ENV[arg.upcase] if ENV[arg.upcase].present?
- end
+ %w[
+ module
+ filter
+ qunit_skip_core
+ qunit_single_plugin
+ theme_name
+ theme_url
+ theme_id
+ ].each { |arg| options[arg] = ENV[arg.upcase] if ENV[arg.upcase].present? }
- if report_requests
- options['report_requests'] = '1'
- end
+ options["report_requests"] = "1" if report_requests
query = options.to_query
@@ -85,7 +81,7 @@ task "qunit:test", [:timeout, :qunit_path, :filter] do |_, args|
end
# wait for server to accept connections
- require 'net/http'
+ require "net/http"
warmup_path = "/srv/status"
uri = URI("http://localhost:#{unicorn_port}/#{warmup_path}")
puts "Warming up Rails server"
diff --git a/lib/tasks/redis.rake b/lib/tasks/redis.rake
index ee45cb0e19f..f81c5c91b79 100644
--- a/lib/tasks/redis.rake
+++ b/lib/tasks/redis.rake
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-task 'redis:clean_up' => ['environment'] do
+task "redis:clean_up" => ["environment"] do
next unless Rails.configuration.multisite
dbs = RailsMultisite::ConnectionManagement.all_dbs
@@ -20,9 +20,7 @@ task 'redis:clean_up' => ['environment'] do
if match = key.match(regexp)
db_name = match[:message_bus] || match[:namespace]
- if !dbs.include?(db_name)
- transaction.del(key)
- end
+ transaction.del(key) if !dbs.include?(db_name)
end
end
end
diff --git a/lib/tasks/release_note.rake b/lib/tasks/release_note.rake
index f3d36187fc9..8f665d6eba8 100644
--- a/lib/tasks/release_note.rake
+++ b/lib/tasks/release_note.rake
@@ -16,13 +16,9 @@ task "release_note:generate", :from, :to, :repo do |t, args|
repo = args[:repo] || "."
changes = find_changes(repo, args[:from], args[:to])
- CHANGE_TYPES.each do |ct|
- print_changes(ct[:heading], changes[ct], "###")
- end
+ CHANGE_TYPES.each { |ct| print_changes(ct[:heading], changes[ct], "###") }
- if changes.values.all?(&:empty?)
- puts "(no changes)", ""
- end
+ puts "(no changes)", "" if changes.values.all?(&:empty?)
end
# To use with all-the-plugins:
@@ -37,10 +33,13 @@ task "release_note:plugins:generate", :from, :to, :plugin_glob, :org do |t, args
plugin_glob = args[:plugin_glob] || "./plugins/*"
git_org = args[:org]
- all_repos = Dir.glob(plugin_glob).filter { |f| File.directory?(f) && File.exist?("#{f}/.git") }
+ all_repos = Dir.glob(plugin_glob).filter { |f| File.directory?(f) && File.exist?("#{f}/.git") }
if git_org
- all_repos = all_repos.filter { |dir| `git -C #{dir} remote get-url origin`.match?(/github.com[\/:]#{git_org}\//) }
+ all_repos =
+ all_repos.filter do |dir|
+ `git -C #{dir} remote get-url origin`.match?(%r{github.com[/:]#{git_org}/})
+ end
end
no_changes_repos = []
@@ -55,9 +54,7 @@ task "release_note:plugins:generate", :from, :to, :plugin_glob, :org do |t, args
end
puts "### #{name}\n\n"
- CHANGE_TYPES.each do |ct|
- print_changes_plugin(ct[:heading], changes[ct])
- end
+ CHANGE_TYPES.each { |ct| print_changes_plugin(ct[:heading], changes[ct]) }
end
puts "(No changes found in #{no_changes_repos.join(", ")})"
@@ -83,9 +80,7 @@ def find_changes(repo, from, to)
raise "Status #{$?.exitstatus} running git log\n#{out}" if !$?.success?
changes = {}
- CHANGE_TYPES.each do |ct|
- changes[ct] = Set.new
- end
+ CHANGE_TYPES.each { |ct| changes[ct] = Set.new }
out.each_line do |comment|
next if comment =~ /^\s*Revert/
@@ -117,7 +112,7 @@ def better(line)
line = remove_prefix(line)
line = escape_brackets(line)
line = remove_pull_request(line)
- line[0] = '\#' if line[0] == '#'
+ line[0] = '\#' if line[0] == "#"
if line[0]
line[0] = line[0].capitalize
"- " + line
@@ -131,10 +126,7 @@ def remove_prefix(line)
end
def escape_brackets(line)
- line.gsub("<", "`<")
- .gsub(">", ">`")
- .gsub("[", "`[")
- .gsub("]", "]`")
+ line.gsub("<", "`<").gsub(">", ">`").gsub("[", "`[").gsub("]", "]`")
end
def remove_pull_request(line)
@@ -143,7 +135,7 @@ end
def split_comments(text)
text = normalize_terms(text)
- terms = ["FIX:", "FEATURE:", "UX:", "SECURITY:" , "PERF:" , "A11Y:"]
+ terms = %w[FIX: FEATURE: UX: SECURITY: PERF: A11Y:]
terms.each do |term|
text = text.gsub(/(#{term})+/i, term)
text = newlines_at_term(text, term)
@@ -161,8 +153,6 @@ def normalize_terms(text)
end
def newlines_at_term(text, term)
- if text.include?(term)
- text = text.split(term).map { |l| l.strip }.join("\n#{term} ")
- end
+ text = text.split(term).map { |l| l.strip }.join("\n#{term} ") if text.include?(term)
text
end
diff --git a/lib/tasks/revisions.rake b/lib/tasks/revisions.rake
index 722d67471de..ac295ad5449 100644
--- a/lib/tasks/revisions.rake
+++ b/lib/tasks/revisions.rake
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-desc 'Print debug information about post_revisions which cannot be deserialized'
-task 'revisions:debug_deserialization' => :environment do
+desc "Print debug information about post_revisions which cannot be deserialized"
+task "revisions:debug_deserialization" => :environment do
puts "Checking #{PostRevision.count} PostRevision records in batches of 1000... this may take some time..."
sleep 1
diff --git a/lib/tasks/rspec.rake b/lib/tasks/rspec.rake
index 87275a1f940..7e0ffa2a3b6 100644
--- a/lib/tasks/rspec.rake
+++ b/lib/tasks/rspec.rake
@@ -1,7 +1,7 @@
# frozen_string_literal: true
if Rails.env.development? || Rails.env.test?
- require 'rspec/core/rake_task'
+ require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
end
diff --git a/lib/tasks/s3.rake b/lib/tasks/s3.rake
index 9a3b61c5d23..56e5859dafe 100644
--- a/lib/tasks/s3.rake
+++ b/lib/tasks/s3.rake
@@ -20,30 +20,25 @@ def prefix_s3_path(path)
end
def should_skip?(path)
- return false if ENV['FORCE_S3_UPLOADS']
+ return false if ENV["FORCE_S3_UPLOADS"]
existing_assets.include?(prefix_s3_path(path))
end
def upload(path, remote_path, content_type, content_encoding = nil)
-
options = {
- cache_control: 'max-age=31556952, public, immutable',
+ cache_control: "max-age=31556952, public, immutable",
content_type: content_type,
- acl: 'public-read'
+ acl: "public-read",
}
- if content_encoding
- options[:content_encoding] = content_encoding
- end
+ options[:content_encoding] = content_encoding if content_encoding
if should_skip?(remote_path)
puts "Skipping: #{remote_path}"
else
puts "Uploading: #{remote_path}"
- File.open(path) do |file|
- helper.upload(file, remote_path, options)
- end
+ File.open(path) { |file| helper.upload(file, remote_path, options) }
end
File.delete(path) if (File.exist?(path) && ENV["DELETE_ASSETS_AFTER_S3_UPLOAD"])
@@ -59,7 +54,12 @@ end
def assets
cached = Rails.application.assets&.cached
- manifest = Sprockets::Manifest.new(cached, Rails.root + 'public/assets', Rails.application.config.assets.manifest)
+ manifest =
+ Sprockets::Manifest.new(
+ cached,
+ Rails.root + "public/assets",
+ Rails.application.config.assets.manifest,
+ )
results = []
@@ -73,19 +73,18 @@ def assets
asset_path = "assets/#{path}"
results << [fullpath, asset_path, content_type]
- if File.exist?(fullpath + '.br')
- results << [fullpath + '.br', brotli_s3_path(asset_path), content_type, 'br']
+ if File.exist?(fullpath + ".br")
+ results << [fullpath + ".br", brotli_s3_path(asset_path), content_type, "br"]
end
- if File.exist?(fullpath + '.gz')
- results << [fullpath + '.gz', gzip_s3_path(asset_path), content_type, 'gzip']
+ if File.exist?(fullpath + ".gz")
+ results << [fullpath + ".gz", gzip_s3_path(asset_path), content_type, "gzip"]
end
- if File.exist?(fullpath + '.map')
- results << [fullpath + '.map', asset_path + '.map', 'application/json']
+ if File.exist?(fullpath + ".map")
+ results << [fullpath + ".map", asset_path + ".map", "application/json"]
end
end
-
end
results
@@ -102,7 +101,7 @@ def ensure_s3_configured!
end
end
-task 's3:correct_acl' => :environment do
+task "s3:correct_acl" => :environment do
ensure_s3_configured!
puts "ensuring public-read is set on every upload and optimized image"
@@ -129,14 +128,11 @@ task 's3:correct_acl' => :environment do
puts "Skipping #{type} #{id} url is #{url} #{e}"
end
end
- if i % 100 == 0
- puts "#{i} done"
- end
+ puts "#{i} done" if i % 100 == 0
end
-
end
-task 's3:correct_cachecontrol' => :environment do
+task "s3:correct_cachecontrol" => :environment do
ensure_s3_configured!
puts "ensuring cache-control is set on every upload and optimized image"
@@ -145,7 +141,7 @@ task 's3:correct_cachecontrol' => :environment do
base_url = Discourse.store.absolute_base_url
- cache_control = 'max-age=31556952, public, immutable'
+ cache_control = "max-age=31556952, public, immutable"
objects = Upload.pluck(:id, :url).map { |array| array << :upload }
objects.concat(OptimizedImage.pluck(:id, :url).map { |array| array << :optimized_image })
@@ -166,20 +162,17 @@ task 's3:correct_cachecontrol' => :environment do
cache_control: cache_control,
content_type: object.content_type,
content_disposition: object.content_disposition,
- metadata_directive: 'REPLACE'
+ metadata_directive: "REPLACE",
)
rescue => e
puts "Skipping #{type} #{id} url is #{url} #{e}"
end
end
- if i % 100 == 0
- puts "#{i} done"
- end
+ puts "#{i} done" if i % 100 == 0
end
-
end
-task 's3:ensure_cors_rules' => :environment do
+task "s3:ensure_cors_rules" => :environment do
ensure_s3_configured!
puts "Installing CORS rules..."
@@ -195,13 +188,11 @@ task 's3:ensure_cors_rules' => :environment do
puts "Direct upload rules status: #{result[:direct_upload_rules_status]}."
end
-task 's3:upload_assets' => [:environment, 's3:ensure_cors_rules'] do
- assets.each do |asset|
- upload(*asset)
- end
+task "s3:upload_assets" => [:environment, "s3:ensure_cors_rules"] do
+ assets.each { |asset| upload(*asset) }
end
-task 's3:expire_missing_assets' => :environment do
+task "s3:expire_missing_assets" => :environment do
ensure_s3_configured!
puts "Checking for stale S3 assets..."
diff --git a/lib/tasks/scheduler.rake b/lib/tasks/scheduler.rake
index 6bfb28eceaa..5cff1bfb715 100644
--- a/lib/tasks/scheduler.rake
+++ b/lib/tasks/scheduler.rake
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'benchmark'
+require "benchmark"
desc "This task is called by the Heroku scheduler add-on"
@@ -21,7 +21,7 @@ task version_check: :environment do
end
desc "run every task the scheduler knows about in that order, use only for debugging"
-task 'scheduler:run_all' => :environment do
+task "scheduler:run_all" => :environment do
MiniScheduler::Manager.discover_schedules.each do |schedule|
puts "Running #{schedule}"
elapsed = Benchmark.realtime { schedule.new.execute({}) }
diff --git a/lib/tasks/search.rake b/lib/tasks/search.rake
index ce2bad6f3cb..146a1088af5 100644
--- a/lib/tasks/search.rake
+++ b/lib/tasks/search.rake
@@ -1,21 +1,23 @@
# frozen_string_literal: true
task "search:reindex" => :environment do
- ENV['RAILS_DB'] ? reindex_search : reindex_search_all_sites
+ ENV["RAILS_DB"] ? reindex_search : reindex_search_all_sites
end
def reindex_search(db = RailsMultisite::ConnectionManagement.current_db)
puts "Reindexing '#{db}'"
puts ""
puts "Posts"
- Post.includes(topic: [:category, :tags]).find_each do |p|
- if p.post_number == 1
- SearchIndexer.index(p.topic, force: true)
- else
- SearchIndexer.index(p, force: true)
+ Post
+ .includes(topic: %i[category tags])
+ .find_each do |p|
+ if p.post_number == 1
+ SearchIndexer.index(p.topic, force: true)
+ else
+ SearchIndexer.index(p, force: true)
+ end
+ putc "."
end
- putc "."
- end
puts
puts "Users"
@@ -44,7 +46,5 @@ def reindex_search(db = RailsMultisite::ConnectionManagement.current_db)
end
def reindex_search_all_sites
- RailsMultisite::ConnectionManagement.each_connection do |db|
- reindex_search(db)
- end
+ RailsMultisite::ConnectionManagement.each_connection { |db| reindex_search(db) }
end
diff --git a/lib/tasks/site.rake b/lib/tasks/site.rake
index 870e31dc1b8..94d78a034e3 100644
--- a/lib/tasks/site.rake
+++ b/lib/tasks/site.rake
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'yaml'
-require 'zip'
+require "yaml"
+require "zip"
class ZippedSiteStructure
attr_reader :zip
@@ -16,9 +16,7 @@ class ZippedSiteStructure
end
def set(name, data)
- @zip.get_output_stream("#{name}.json") do |file|
- file.write(data.to_json)
- end
+ @zip.get_output_stream("#{name}.json") { |file| file.write(data.to_json) }
end
def get(name)
@@ -47,8 +45,9 @@ class ZippedSiteStructure
return @uploads[upload.id]
end
- local_path = upload.local? ? Discourse.store.path_for(upload) : Discourse.store.download(upload).path
- zip_path = File.join('uploads', File.basename(local_path))
+ local_path =
+ upload.local? ? Discourse.store.path_for(upload) : Discourse.store.download(upload).path
+ zip_path = File.join("uploads", File.basename(local_path))
zip_path = get_unique_path(zip_path)
puts " - Exporting upload #{upload_or_id_or_url} to #{zip_path}"
@@ -60,18 +59,20 @@ class ZippedSiteStructure
def get_upload(upload, opts = {})
return nil if upload.blank?
- if @uploads[upload['path']].present?
- puts " - Already imported upload #{upload['filename']} from #{upload['path']}"
- return @uploads[upload['path']]
+ if @uploads[upload["path"]].present?
+ puts " - Already imported upload #{upload["filename"]} from #{upload["path"]}"
+ return @uploads[upload["path"]]
end
- puts " - Importing upload #{upload['filename']} from #{upload['path']}"
+ puts " - Importing upload #{upload["filename"]} from #{upload["path"]}"
- tempfile = Tempfile.new(upload['filename'], binmode: true)
- tempfile.write(@zip.get_input_stream(upload['path']).read)
+ tempfile = Tempfile.new(upload["filename"], binmode: true)
+ tempfile.write(@zip.get_input_stream(upload["path"]).read)
tempfile.rewind
- @uploads[upload['path']] ||= UploadCreator.new(tempfile, upload['filename'], opts).create_for(Discourse::SYSTEM_USER_ID)
+ @uploads[upload["path"]] ||= UploadCreator.new(tempfile, upload["filename"], opts).create_for(
+ Discourse::SYSTEM_USER_ID,
+ )
end
private
@@ -92,8 +93,8 @@ class ZippedSiteStructure
end
end
-desc 'Exports site structure (settings, groups, categories, tags, themes, etc) to a ZIP file'
-task 'site:export_structure', [:zip_path] => :environment do |task, args|
+desc "Exports site structure (settings, groups, categories, tags, themes, etc) to a ZIP file"
+task "site:export_structure", [:zip_path] => :environment do |task, args|
if args[:zip_path].blank?
STDERR.puts "ERROR: rake site:export_structure[<path to ZIP file>]"
exit 1
@@ -110,19 +111,21 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
settings = {}
- SiteSetting.all_settings(include_hidden: true).each do |site_setting|
- next if site_setting[:default] == site_setting[:value]
+ SiteSetting
+ .all_settings(include_hidden: true)
+ .each do |site_setting|
+ next if site_setting[:default] == site_setting[:value]
- puts "- Site setting #{site_setting[:setting]} -> #{site_setting[:value].inspect}"
+ puts "- Site setting #{site_setting[:setting]} -> #{site_setting[:value].inspect}"
- settings[site_setting[:setting]] = if site_setting[:type] == 'upload'
- data.set_upload(site_setting[:value])
- else
- site_setting[:value]
+ settings[site_setting[:setting]] = if site_setting[:type] == "upload"
+ data.set_upload(site_setting[:value])
+ else
+ site_setting[:value]
+ end
end
- end
- data.set('site_settings', settings)
+ data.set("site_settings", settings)
puts
puts "Exporting users"
@@ -130,19 +133,22 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
users = []
- User.real.where(admin: true).each do |u|
- puts "- User #{u.username}"
-
- users << {
- username: u.username,
- name: u.name,
- email: u.email,
- active: u.active,
- admin: u.admin,
- }
- end
+ User
+ .real
+ .where(admin: true)
+ .each do |u|
+ puts "- User #{u.username}"
+
+ users << {
+ username: u.username,
+ name: u.name,
+ email: u.email,
+ active: u.active,
+ admin: u.admin,
+ }
+ end
- data.set('users', users)
+ data.set("users", users)
puts
puts "Exporting groups"
@@ -150,38 +156,40 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
groups = []
- Group.where(automatic: false).each do |g|
- puts "- Group #{g.name}"
-
- groups << {
- name: g.name,
- automatic_membership_email_domains: g.automatic_membership_email_domains,
- primary_group: g.primary_group,
- title: g.title,
- grant_trust_level: g.grant_trust_level,
- incoming_email: g.incoming_email,
- has_messages: g.has_messages,
- flair_bg_color: g.flair_bg_color,
- flair_color: g.flair_color,
- bio_raw: g.bio_raw,
- allow_membership_requests: g.allow_membership_requests,
- full_name: g.full_name,
- default_notification_level: g.default_notification_level,
- visibility_level: g.visibility_level,
- public_exit: g.public_exit,
- public_admission: g.public_admission,
- membership_request_template: g.membership_request_template,
- messageable_level: g.messageable_level,
- mentionable_level: g.mentionable_level,
- publish_read_state: g.publish_read_state,
- members_visibility_level: g.members_visibility_level,
- flair_icon: g.flair_icon,
- flair_upload_id: data.set_upload(g.flair_upload_id),
- allow_unknown_sender_topic_replies: g.allow_unknown_sender_topic_replies,
- }
- end
+ Group
+ .where(automatic: false)
+ .each do |g|
+ puts "- Group #{g.name}"
+
+ groups << {
+ name: g.name,
+ automatic_membership_email_domains: g.automatic_membership_email_domains,
+ primary_group: g.primary_group,
+ title: g.title,
+ grant_trust_level: g.grant_trust_level,
+ incoming_email: g.incoming_email,
+ has_messages: g.has_messages,
+ flair_bg_color: g.flair_bg_color,
+ flair_color: g.flair_color,
+ bio_raw: g.bio_raw,
+ allow_membership_requests: g.allow_membership_requests,
+ full_name: g.full_name,
+ default_notification_level: g.default_notification_level,
+ visibility_level: g.visibility_level,
+ public_exit: g.public_exit,
+ public_admission: g.public_admission,
+ membership_request_template: g.membership_request_template,
+ messageable_level: g.messageable_level,
+ mentionable_level: g.mentionable_level,
+ publish_read_state: g.publish_read_state,
+ members_visibility_level: g.members_visibility_level,
+ flair_icon: g.flair_icon,
+ flair_upload_id: data.set_upload(g.flair_upload_id),
+ allow_unknown_sender_topic_replies: g.allow_unknown_sender_topic_replies,
+ }
+ end
- data.set('groups', groups)
+ data.set("groups", groups)
puts
puts "Exporting categories"
@@ -229,7 +237,7 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
}
end
- data.set('categories', categories)
+ data.set("categories", categories)
puts
puts "Exporting tag groups"
@@ -240,13 +248,10 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
TagGroup.all.each do |tg|
puts "- Tag group #{tg.name}"
- tag_groups << {
- name: tg.name,
- tag_names: tg.tags.map(&:name)
- }
+ tag_groups << { name: tg.name, tag_names: tg.tags.map(&:name) }
end
- data.set('tag_groups', tag_groups)
+ data.set("tag_groups", tag_groups)
puts
puts "Exporting tags"
@@ -263,7 +268,7 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
tags << tag
end
- data.set('tags', tags)
+ data.set("tags", tags)
puts
puts "Exporting themes and theme components"
@@ -279,18 +284,18 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
name: theme.name,
url: theme.remote_theme.remote_url,
private_key: theme.remote_theme.private_key,
- branch: theme.remote_theme.branch
+ branch: theme.remote_theme.branch,
}
else
exporter = ThemeStore::ZipExporter.new(theme)
file_path = exporter.package_filename
- file_zip_path = File.join('themes', File.basename(file_path))
+ file_zip_path = File.join("themes", File.basename(file_path))
data.zip.add(file_zip_path, file_path)
themes << { name: theme.name, filename: File.basename(file_path), path: file_zip_path }
end
end
- data.set('themes', themes)
+ data.set("themes", themes)
puts
puts "Exporting theme settings"
@@ -301,11 +306,12 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
ThemeSetting.find_each do |theme_setting|
puts "- Theme setting #{theme_setting.name} -> #{theme_setting.value}"
- value = if theme_setting.data_type == ThemeSetting.types[:upload]
- data.set_upload(theme_setting.value)
- else
- theme_setting.value
- end
+ value =
+ if theme_setting.data_type == ThemeSetting.types[:upload]
+ data.set_upload(theme_setting.value)
+ else
+ theme_setting.value
+ end
theme_settings << {
name: theme_setting.name,
@@ -315,7 +321,7 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
}
end
- data.set('theme_settings', theme_settings)
+ data.set("theme_settings", theme_settings)
puts
puts "Done"
@@ -324,8 +330,8 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
data.close
end
-desc 'Imports site structure from a ZIP file exported by site:export_structure'
-task 'site:import_structure', [:zip_path] => :environment do |task, args|
+desc "Imports site structure from a ZIP file exported by site:export_structure"
+task "site:import_structure", [:zip_path] => :environment do |task, args|
if args[:zip_path].blank?
STDERR.puts "ERROR: rake site:import_structure[<path to ZIP file>]"
exit 1
@@ -340,7 +346,7 @@ task 'site:import_structure', [:zip_path] => :environment do |task, args|
puts "Importing site settings"
puts
- settings = data.get('site_settings')
+ settings = data.get("site_settings")
imported_settings = Set.new
3.times.each do |try|
@@ -373,144 +379,159 @@ task 'site:import_structure', [:zip_path] => :environment do |task, args|
puts "Importing users"
puts
- data.get('users').each do |u|
- puts "- User #{u['username']}"
+ data
+ .get("users")
+ .each do |u|
+ puts "- User #{u["username"]}"
- begin
- user = User.find_or_initialize_by(username: u.delete('username'))
- user.update!(u)
- rescue => e
- STDERR.puts "ERROR: Cannot import user: #{e.message}"
- puts e.backtrace
+ begin
+ user = User.find_or_initialize_by(username: u.delete("username"))
+ user.update!(u)
+ rescue => e
+ STDERR.puts "ERROR: Cannot import user: #{e.message}"
+ puts e.backtrace
+ end
end
- end
puts
puts "Importing groups"
puts
- data.get('groups').each do |g|
- puts "- Group #{g['name']}"
+ data
+ .get("groups")
+ .each do |g|
+ puts "- Group #{g["name"]}"
- begin
- group = Group.find_or_initialize_by(name: g.delete('name'))
- group.update!(g)
- rescue => e
- STDERR.puts "ERROR: Cannot import group: #{e.message}"
- puts e.backtrace
+ begin
+ group = Group.find_or_initialize_by(name: g.delete("name"))
+ group.update!(g)
+ rescue => e
+ STDERR.puts "ERROR: Cannot import group: #{e.message}"
+ puts e.backtrace
+ end
end
- end
puts
puts "Importing categories"
puts
- data.get('categories').each do |c|
- puts "- Category #{c['name']} (#{c['slug']})"
+ data
+ .get("categories")
+ .each do |c|
+ puts "- Category #{c["name"]} (#{c["slug"]})"
- begin
- category = Category.find_or_initialize_by(slug: c.delete('slug'))
- category.user ||= Discourse.system_user
- category.parent_category = Category.find_by(slug: c.delete('parent_category'))
- category.permissions = c.delete('permissions')
- category.update!(c)
- rescue => e
- STDERR.puts "ERROR: Cannot import category: #{e.message}"
- puts e.backtrace
+ begin
+ category = Category.find_or_initialize_by(slug: c.delete("slug"))
+ category.user ||= Discourse.system_user
+ category.parent_category = Category.find_by(slug: c.delete("parent_category"))
+ category.permissions = c.delete("permissions")
+ category.update!(c)
+ rescue => e
+ STDERR.puts "ERROR: Cannot import category: #{e.message}"
+ puts e.backtrace
+ end
end
- end
puts
puts "Importing tag groups"
puts
- data.get('tag_groups').each do |tg|
- puts "- Tag group #{tg['name']}"
+ data
+ .get("tag_groups")
+ .each do |tg|
+ puts "- Tag group #{tg["name"]}"
- tag_group = TagGroup.find_or_initialize_by(name: tg.delete('name'))
- tag_group.update!(tg)
- end
+ tag_group = TagGroup.find_or_initialize_by(name: tg.delete("name"))
+ tag_group.update!(tg)
+ end
puts
puts "Importing tags"
puts
- data.get('tags').each do |t|
- puts "- Tag #{t['name']}"
+ data
+ .get("tags")
+ .each do |t|
+ puts "- Tag #{t["name"]}"
+
+ if t["target_tag"].present?
+ begin
+ t["target_tag"] = Tag.find_or_create_by!(name: t.delete("target_tag"))
+ rescue => e
+ STDERR.puts "ERROR: Cannot import target tag: #{e.message}"
+ puts e.backtrace
+ end
+ end
- if t['target_tag'].present?
begin
- t['target_tag'] = Tag.find_or_create_by!(name: t.delete('target_tag'))
+ tag = Tag.find_or_initialize_by(name: t.delete("name"))
+ tag.update!(t)
rescue => e
- STDERR.puts "ERROR: Cannot import target tag: #{e.message}"
+ STDERR.puts "ERROR: Cannot import tag: #{e.message}"
puts e.backtrace
end
end
- begin
- tag = Tag.find_or_initialize_by(name: t.delete('name'))
- tag.update!(t)
- rescue => e
- STDERR.puts "ERROR: Cannot import tag: #{e.message}"
- puts e.backtrace
- end
- end
-
puts
puts "Importing themes and theme components"
puts
- data.get('themes').each do |t|
- puts "- Theme #{t['name']}"
-
- begin
- if t['url'].present?
- next if Theme.find_by(name: t['name']).present?
-
- RemoteTheme.import_theme(
- t['url'],
- Discourse.system_user,
- private_key: t['private_key'],
- branch: t['branch']
- )
- elsif t['filename'].present?
- tempfile = Tempfile.new(t['filename'], binmode: true)
- tempfile.write(data.zip.get_input_stream(t['path']).read)
- tempfile.flush
-
- RemoteTheme.update_zipped_theme(
- tempfile.path,
- t['filename'],
- user: Discourse.system_user,
- theme_id: Theme.find_by(name: t['name'])&.id,
- )
+ data
+ .get("themes")
+ .each do |t|
+ puts "- Theme #{t["name"]}"
+
+ begin
+ if t["url"].present?
+ next if Theme.find_by(name: t["name"]).present?
+
+ RemoteTheme.import_theme(
+ t["url"],
+ Discourse.system_user,
+ private_key: t["private_key"],
+ branch: t["branch"],
+ )
+ elsif t["filename"].present?
+ tempfile = Tempfile.new(t["filename"], binmode: true)
+ tempfile.write(data.zip.get_input_stream(t["path"]).read)
+ tempfile.flush
+
+ RemoteTheme.update_zipped_theme(
+ tempfile.path,
+ t["filename"],
+ user: Discourse.system_user,
+ theme_id: Theme.find_by(name: t["name"])&.id,
+ )
+ end
+ rescue => e
+ STDERR.puts "ERROR: Cannot import theme: #{e.message}"
+ puts e.backtrace
end
- rescue => e
- STDERR.puts "ERROR: Cannot import theme: #{e.message}"
- puts e.backtrace
end
- end
puts
puts "Importing theme settings"
puts
- data.get('theme_settings').each do |ts|
- puts "- Theme setting #{ts['name']} -> #{ts['value']}"
+ data
+ .get("theme_settings")
+ .each do |ts|
+ puts "- Theme setting #{ts["name"]} -> #{ts["value"]}"
- begin
- if ts['data_type'] == ThemeSetting.types[:upload]
- ts['value'] = data.get_upload(ts['value'], for_theme: true)
- end
+ begin
+ if ts["data_type"] == ThemeSetting.types[:upload]
+ ts["value"] = data.get_upload(ts["value"], for_theme: true)
+ end
- ThemeSetting
- .find_or_initialize_by(name: ts['name'], theme: Theme.find_by(name: ts['theme']))
- .update!(data_type: ts['data_type'], value: ts['value'])
- rescue => e
- STDERR.puts "ERROR: Cannot import theme setting: #{e.message}"
- puts e.backtrace
+ ThemeSetting.find_or_initialize_by(
+ name: ts["name"],
+ theme: Theme.find_by(name: ts["theme"]),
+ ).update!(data_type: ts["data_type"], value: ts["value"])
+ rescue => e
+ STDERR.puts "ERROR: Cannot import theme setting: #{e.message}"
+ puts e.backtrace
+ end
end
- end
puts
puts "Done"
diff --git a/lib/tasks/site_settings.rake b/lib/tasks/site_settings.rake
index 85447443a18..3791d4a1590 100644
--- a/lib/tasks/site_settings.rake
+++ b/lib/tasks/site_settings.rake
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'yaml'
+require "yaml"
desc "Exports site settings"
task "site_settings:export" => :environment do
@@ -10,8 +10,8 @@ end
desc "Imports site settings"
task "site_settings:import" => :environment do
- yml = (STDIN.tty?) ? '' : STDIN.read
- if yml == ''
+ yml = (STDIN.tty?) ? "" : STDIN.read
+ if yml == ""
puts
puts "Please specify a settings yml file"
puts "Example: rake site_settings:import < settings.yml"
@@ -32,7 +32,5 @@ task "site_settings:import" => :environment do
puts " Not Found: #{counts[:not_found]}"
puts " Errors: #{counts[:errors]}"
- if counts[:not_found] + counts[:errors] > 0
- exit 1
- end
+ exit 1 if counts[:not_found] + counts[:errors] > 0
end
diff --git a/lib/tasks/smoke_test.rake b/lib/tasks/smoke_test.rake
index 156e21ff49e..502f135976f 100644
--- a/lib/tasks/smoke_test.rake
+++ b/lib/tasks/smoke_test.rake
@@ -20,17 +20,17 @@ task "smoke:test" do
puts "Testing: #{url}"
- require 'open-uri'
- require 'net/http'
+ require "open-uri"
+ require "net/http"
uri = URI(url)
request = Net::HTTP::Get.new(uri)
if ENV["AUTH_USER"] && ENV["AUTH_PASSWORD"]
- request.basic_auth(ENV['AUTH_USER'], ENV['AUTH_PASSWORD'])
+ request.basic_auth(ENV["AUTH_USER"], ENV["AUTH_PASSWORD"])
end
- dir = ENV["SMOKE_TEST_SCREENSHOT_PATH"] || 'tmp/smoke-test-screenshots'
+ dir = ENV["SMOKE_TEST_SCREENSHOT_PATH"] || "tmp/smoke-test-screenshots"
FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
wait = ENV["WAIT_FOR_URL"].to_i
@@ -40,9 +40,10 @@ task "smoke:test" do
retries = 0
loop do
- response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
- http.request(request)
- end
+ response =
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
+ http.request(request)
+ end
success = response.code == "200"
code = response.code
@@ -56,25 +57,23 @@ task "smoke:test" do
end
end
- if !success
- raise "TRIVIAL GET FAILED WITH #{code}: retried #{retries} times"
- end
+ raise "TRIVIAL GET FAILED WITH #{code}: retried #{retries} times" if !success
results = +""
node_arguments = []
- node_arguments << '--inspect-brk' if ENV["DEBUG_NODE"]
+ node_arguments << "--inspect-brk" if ENV["DEBUG_NODE"]
node_arguments << "#{Rails.root}/test/smoke_test.js"
node_arguments << url
- IO.popen("node #{node_arguments.join(' ')}").each do |line|
- puts line
- results << line
- end
+ IO
+ .popen("node #{node_arguments.join(" ")}")
+ .each do |line|
+ puts line
+ results << line
+ end
- if results !~ /ALL PASSED/
- raise "FAILED"
- end
+ raise "FAILED" if results !~ /ALL PASSED/
api_key = ENV["ADMIN_API_KEY"]
api_username = ENV["ADMIN_API_USERNAME"]
@@ -84,24 +83,12 @@ task "smoke:test" do
puts "Running QUnit tests for theme #{theme_url.inspect} using API key #{api_key[0..3]}... and username #{api_username.inspect}"
- query_params = {
- seed: Random.new.seed,
- theme_url: theme_url,
- hidepassed: 1,
- report_requests: 1
- }
- url += '/' if !url.end_with?('/')
+ query_params = { seed: Random.new.seed, theme_url: theme_url, hidepassed: 1, report_requests: 1 }
+ url += "/" if !url.end_with?("/")
full_url = "#{url}theme-qunit?#{query_params.to_query}"
timeout = 1000 * 60 * 10
- sh(
- "node",
- "#{Rails.root}/test/run-qunit.js",
- full_url,
- timeout.to_s
- )
+ sh("node", "#{Rails.root}/test/run-qunit.js", full_url, timeout.to_s)
- if !$?.success?
- raise "THEME TESTS FAILED!"
- end
+ raise "THEME TESTS FAILED!" if !$?.success?
end
diff --git a/lib/tasks/svg_icons.rake b/lib/tasks/svg_icons.rake
index cfb4defb504..5549b4379e2 100644
--- a/lib/tasks/svg_icons.rake
+++ b/lib/tasks/svg_icons.rake
@@ -8,17 +8,11 @@ def library_src
"#{Rails.root}/node_modules"
end
-task 'svgicons:update' do
-
+task "svgicons:update" do
yarn = system("yarn install")
abort('Unable to run "yarn install"') unless yarn
- dependencies = [
- {
- source: '@fortawesome/fontawesome-free/sprites',
- destination: 'fontawesome',
- }
- ]
+ dependencies = [{ source: "@fortawesome/fontawesome-free/sprites", destination: "fontawesome" }]
start = Time.now
diff --git a/lib/tasks/tags.rake b/lib/tasks/tags.rake
index 6767b299484..50bd6396e2e 100644
--- a/lib/tasks/tags.rake
+++ b/lib/tasks/tags.rake
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-task "tags:bulk_tag_category", [:tags, :category, :append] => [:environment] do |_, args|
+task "tags:bulk_tag_category", %i[tags category append] => [:environment] do |_, args|
args.with_defaults(append: false)
tags = args[:tags].split("|")
category_id = args[:category]
diff --git a/lib/tasks/themes.rake b/lib/tasks/themes.rake
index 289823643fe..3e27bd3387b 100644
--- a/lib/tasks/themes.rake
+++ b/lib/tasks/themes.rake
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'yaml'
+require "yaml"
#
# 2 different formats are accepted:
@@ -26,15 +26,16 @@ require 'yaml'
#
desc "Install themes & theme components"
task "themes:install" => :environment do |task, args|
- theme_args = (STDIN.tty?) ? '' : STDIN.read
- use_json = theme_args == ''
+ theme_args = (STDIN.tty?) ? "" : STDIN.read
+ use_json = theme_args == ""
- theme_args = begin
- use_json ? JSON.parse(ARGV.last.gsub('--', '')) : YAML::safe_load(theme_args)
- rescue
- puts use_json ? "Invalid JSON input. \n#{ARGV.last}" : "Invalid YML: \n#{theme_args}"
- exit 1
- end
+ theme_args =
+ begin
+ use_json ? JSON.parse(ARGV.last.gsub("--", "")) : YAML.safe_load(theme_args)
+ rescue StandardError
+ puts use_json ? "Invalid JSON input. \n#{ARGV.last}" : "Invalid YML: \n#{theme_args}"
+ exit 1
+ end
log, counts = ThemesInstallTask.install(theme_args)
@@ -47,9 +48,7 @@ task "themes:install" => :environment do |task, args|
puts " Errors: #{counts[:errors]}"
puts " Skipped: #{counts[:skipped]}"
- if counts[:errors] > 0
- exit 1
- end
+ exit 1 if counts[:errors] > 0
end
desc "Install themes & theme components from an archive"
@@ -59,39 +58,42 @@ task "themes:install:archive" => :environment do |task, args|
end
def update_themes
- Theme.includes(:remote_theme).where(enabled: true, auto_update: true).find_each do |theme|
- begin
- remote_theme = theme.remote_theme
- next if remote_theme.blank? || remote_theme.remote_url.blank?
-
- print "Checking '#{theme.name}' for '#{RailsMultisite::ConnectionManagement.current_db}'... "
- remote_theme.update_remote_version
- if remote_theme.out_of_date?
- puts "updating from #{remote_theme.local_version[0..7]} to #{remote_theme.remote_version[0..7]}"
- remote_theme.update_from_remote
- theme.save!
- else
- puts "up to date"
+ Theme
+ .includes(:remote_theme)
+ .where(enabled: true, auto_update: true)
+ .find_each do |theme|
+ begin
+ remote_theme = theme.remote_theme
+ next if remote_theme.blank? || remote_theme.remote_url.blank?
+
+ print "Checking '#{theme.name}' for '#{RailsMultisite::ConnectionManagement.current_db}'... "
+ remote_theme.update_remote_version
+ if remote_theme.out_of_date?
+ puts "updating from #{remote_theme.local_version[0..7]} to #{remote_theme.remote_version[0..7]}"
+ remote_theme.update_from_remote
+ theme.save!
+ else
+ puts "up to date"
+ end
+
+ if remote_theme.last_error_text.present?
+ raise RemoteTheme::ImportError.new(remote_theme.last_error_text)
+ end
+ rescue => e
+ STDERR.puts "Failed to update '#{theme.name}': #{e}"
+ raise if ENV["RAISE_THEME_ERRORS"] == "1"
end
-
- raise RemoteTheme::ImportError.new(remote_theme.last_error_text) if remote_theme.last_error_text.present?
- rescue => e
- STDERR.puts "Failed to update '#{theme.name}': #{e}"
- raise if ENV["RAISE_THEME_ERRORS"] == "1"
end
- end
true
end
desc "Update themes & theme components"
task "themes:update" => :environment do
- if ENV['RAILS_DB'].present?
+ if ENV["RAILS_DB"].present?
update_themes
else
- RailsMultisite::ConnectionManagement.each_connection do
- update_themes
- end
+ RailsMultisite::ConnectionManagement.each_connection { update_themes }
end
end
@@ -101,30 +103,29 @@ task "themes:audit" => :environment do
puts "Selectable themes"
puts "-----------------"
- Theme.where("(enabled OR user_selectable) AND NOT component").each do |theme|
- puts theme.remote_theme&.remote_url || theme.name
- theme.child_themes.each do |child|
- if child.enabled
- repo = child.remote_theme&.remote_url || child.name
- components << repo
+ Theme
+ .where("(enabled OR user_selectable) AND NOT component")
+ .each do |theme|
+ puts theme.remote_theme&.remote_url || theme.name
+ theme.child_themes.each do |child|
+ if child.enabled
+ repo = child.remote_theme&.remote_url || child.name
+ components << repo
+ end
end
end
- end
puts
puts "Selectable components"
puts "---------------------"
- components.each do |repo|
- puts repo
- end
+ components.each { |repo| puts repo }
end
desc "Run QUnit tests of a theme/component"
task "themes:qunit", :type, :value do |t, args|
type = args[:type]
value = args[:value]
- if !%w(name url id).include?(type) || value.blank?
- raise <<~TEXT
+ raise <<~TEXT if !%w[name url id].include?(type) || value.blank?
Wrong arguments type:#{type.inspect}, value:#{value.inspect}"
Usage:
`bundle exec rake "themes:qunit[url,<theme_url>]"`
@@ -133,11 +134,10 @@ task "themes:qunit", :type, :value do |t, args|
OR
`bundle exec rake "themes:qunit[id,<theme_id>]"`
TEXT
- end
ENV["THEME_#{type.upcase}"] = value.to_s
- ENV["QUNIT_RAILS_ENV"] ||= 'development' # qunit:test will switch to `test` by default
+ ENV["QUNIT_RAILS_ENV"] ||= "development" # qunit:test will switch to `test` by default
Rake::Task["qunit:test"].reenable
- Rake::Task["qunit:test"].invoke(1200000, "/theme-qunit")
+ Rake::Task["qunit:test"].invoke(1_200_000, "/theme-qunit")
end
desc "Install a theme/component on a temporary DB and run QUnit tests"
@@ -149,7 +149,7 @@ task "themes:isolated_test" => :environment do |t, args|
# Make this behavior opt-in to make it very obvious.
if ENV["UNSET_DISCOURSE_ENV_VARS"] == "1"
ENV.keys.each do |key|
- next if !key.start_with?('DISCOURSE_')
+ next if !key.start_with?("DISCOURSE_")
next if ENV["DONT_UNSET_#{key}"] == "1"
ENV[key] = nil
end
@@ -162,10 +162,10 @@ task "themes:isolated_test" => :environment do |t, args|
db.start
db.migrate
ActiveRecord::Base.establish_connection(
- adapter: 'postgresql',
- database: 'discourse',
+ adapter: "postgresql",
+ database: "discourse",
port: db.pg_port,
- host: 'localhost'
+ host: "localhost",
)
seeded_themes = Theme.pluck(:id)
diff --git a/lib/tasks/topics.rake b/lib/tasks/topics.rake
index e3bf5790e02..ae45db60b9e 100644
--- a/lib/tasks/topics.rake
+++ b/lib/tasks/topics.rake
@@ -6,9 +6,9 @@ def close_old_topics(category)
topics = Topic.where(closed: false, category_id: category.id)
if category.auto_close_based_on_last_post
- topics = topics.where('last_posted_at < ?', category.auto_close_hours.hours.ago)
+ topics = topics.where("last_posted_at < ?", category.auto_close_hours.hours.ago)
else
- topics = topics.where('created_at < ?', category.auto_close_hours.hours.ago)
+ topics = topics.where("created_at < ?", category.auto_close_hours.hours.ago)
end
topics_closed = 0
@@ -26,8 +26,8 @@ def close_old_topics(category)
end
def apply_auto_close(category)
- topics = Topic.where(closed: false, category_id: category.id)
- .where(<<-SQL, TopicTimer.types[:close])
+ topics =
+ Topic.where(closed: false, category_id: category.id).where(<<-SQL, TopicTimer.types[:close])
NOT EXISTS (
SELECT 1
FROM topic_timers
@@ -47,7 +47,11 @@ def apply_auto_close(category)
topics.find_each do |topic|
topic.inherit_auto_close_from_category
- RakeHelpers.print_status_with_label(" applying auto-close to topics: ", topics_closed += 1, total)
+ RakeHelpers.print_status_with_label(
+ " applying auto-close to topics: ",
+ topics_closed += 1,
+ total,
+ )
end
end
@@ -72,9 +76,15 @@ task "topics:watch_all_replied_topics" => :environment do
count = 0
topics.find_each do |t|
- t.topic_users.where(posted: true).find_each do |tp|
- tp.update!(notification_level: TopicUser.notification_levels[:watching], notifications_reason_id: TopicUser.notification_reasons[:created_post])
- end
+ t
+ .topic_users
+ .where(posted: true)
+ .find_each do |tp|
+ tp.update!(
+ notification_level: TopicUser.notification_levels[:watching],
+ notifications_reason_id: TopicUser.notification_reasons[:created_post],
+ )
+ end
RakeHelpers.print_status(count += 1, total)
end
diff --git a/lib/tasks/turbo.rake b/lib/tasks/turbo.rake
index e78b2f22a3a..06d6e14b704 100644
--- a/lib/tasks/turbo.rake
+++ b/lib/tasks/turbo.rake
@@ -1,10 +1,7 @@
# frozen_string_literal: true
-task 'turbo:spec' => :test do |t|
- require './lib/turbo_tests'
+task "turbo:spec" => :test do |t|
+ require "./lib/turbo_tests"
- TurboTests::Runner.run(
- formatters: [{ name: 'progress', outputs: ['-'] }],
- files: ['spec']
- )
+ TurboTests::Runner.run(formatters: [{ name: "progress", outputs: ["-"] }], files: ["spec"])
end
diff --git a/lib/tasks/uploads.rake b/lib/tasks/uploads.rake
index 702f6846257..8410987d8e9 100644
--- a/lib/tasks/uploads.rake
+++ b/lib/tasks/uploads.rake
@@ -20,7 +20,7 @@ end
def file_exists?(path)
File.exist?(path) && File.size(path) > 0
-rescue
+rescue StandardError
false
end
@@ -30,36 +30,36 @@ def gather_uploads
puts "", "Gathering uploads for '#{current_db}'...", ""
- Upload.where("url ~ '^\/uploads\/'")
+ Upload
+ .where("url ~ '^\/uploads\/'")
.where("url !~ ?", "^\/uploads\/#{current_db}")
.find_each do |upload|
- begin
- old_db = upload.url[/^\/uploads\/([^\/]+)\//, 1]
- from = upload.url.dup
- to = upload.url.sub("/uploads/#{old_db}/", "/uploads/#{current_db}/")
- source = "#{public_directory}#{from}"
- destination = "#{public_directory}#{to}"
-
- # create destination directory & copy file unless it already exists
- unless file_exists?(destination)
- `mkdir -p '#{File.dirname(destination)}'`
- `cp --link '#{source}' '#{destination}'`
- end
+ begin
+ old_db = upload.url[%r{^/uploads/([^/]+)/}, 1]
+ from = upload.url.dup
+ to = upload.url.sub("/uploads/#{old_db}/", "/uploads/#{current_db}/")
+ source = "#{public_directory}#{from}"
+ destination = "#{public_directory}#{to}"
+
+ # create destination directory & copy file unless it already exists
+ unless file_exists?(destination)
+ `mkdir -p '#{File.dirname(destination)}'`
+ `cp --link '#{source}' '#{destination}'`
+ end
- # ensure file has been successfully copied over
- raise unless file_exists?(destination)
+ # ensure file has been successfully copied over
+ raise unless file_exists?(destination)
- # remap links in db
- DbHelper.remap(from, to)
- rescue
- putc "!"
- else
- putc "."
+ # remap links in db
+ DbHelper.remap(from, to)
+ rescue StandardError
+ putc "!"
+ else
+ putc "."
+ end
end
- end
puts "", "Done!"
-
end
################################################################################
@@ -69,18 +69,20 @@ end
task "uploads:backfill_shas" => :environment do
RailsMultisite::ConnectionManagement.each_connection do |db|
puts "Backfilling #{db}..."
- Upload.where(sha1: nil).find_each do |u|
- begin
- path = Discourse.store.path_for(u)
- sha1 = Upload.generate_digest(path)
- u.sha1 = u.secure? ? SecureRandom.hex(20) : sha1
- u.original_sha1 = u.secure? ? sha1 : nil
- u.save!
- putc "."
- rescue => e
- puts "Skipping #{u.original_filename} (#{u.url}) #{e.message}"
+ Upload
+ .where(sha1: nil)
+ .find_each do |u|
+ begin
+ path = Discourse.store.path_for(u)
+ sha1 = Upload.generate_digest(path)
+ u.sha1 = u.secure? ? SecureRandom.hex(20) : sha1
+ u.original_sha1 = u.secure? ? sha1 : nil
+ u.save!
+ putc "."
+ rescue => e
+ puts "Skipping #{u.original_filename} (#{u.url}) #{e.message}"
+ end
end
- end
end
puts "", "Done"
end
@@ -90,7 +92,9 @@ end
################################################################################
task "uploads:migrate_to_s3" => :environment do
- STDOUT.puts("Please note that migrating to S3 is currently not reversible! \n[CTRL+c] to cancel, [ENTER] to continue")
+ STDOUT.puts(
+ "Please note that migrating to S3 is currently not reversible! \n[CTRL+c] to cancel, [ENTER] to continue",
+ )
STDIN.gets
ENV["RAILS_DB"] ? migrate_to_s3 : migrate_to_s3_all_sites
@@ -115,7 +119,7 @@ def create_migration
s3_options: FileStore::ToS3Migration.s3_options_from_env,
dry_run: !!ENV["DRY_RUN"],
migrate_to_multisite: !!ENV["MIGRATE_TO_MULTISITE"],
- skip_etag_verify: !!ENV["SKIP_ETAG_VERIFY"]
+ skip_etag_verify: !!ENV["SKIP_ETAG_VERIFY"],
)
end
@@ -129,7 +133,7 @@ task "uploads:s3_migration_status" => :environment do
success &&= create_migration.migration_successful?
end
- queued_jobs = Sidekiq::Stats.new.queues.sum { |_ , x| x }
+ queued_jobs = Sidekiq::Stats.new.queues.sum { |_, x| x }
if queued_jobs > 50
puts "WARNING: There are #{queued_jobs} jobs queued! Wait till Sidekiq clears backlog prior to migrating site to a new host"
exit 1
@@ -171,7 +175,7 @@ def clean_up_uploads
Would you like to take a full backup before the clean up? (Y/N)
TEXT
- if STDIN.gets.chomp.downcase == 'y'
+ if STDIN.gets.chomp.downcase == "y"
puts "Starting backup..."
backuper = BackupRestore::Backuper.new(Discourse.system_user.id)
backuper.run
@@ -212,27 +216,26 @@ def clean_up_uploads
## FILE SYSTEM vs DATABASE
##
- uploads_directory = File.join(public_directory, 'uploads', db).to_s
+ uploads_directory = File.join(public_directory, "uploads", db).to_s
# avatars (no avatar should be stored in that old directory)
FileUtils.rm_rf("#{uploads_directory}/avatars")
# uploads and optimized images
- Dir.glob("#{uploads_directory}/**/*.*").each do |file_path|
- sha1 = Upload.generate_digest(file_path)
- url = file_path.split(public_directory, 2)[1]
-
- if (Upload.where(sha1: sha1).empty? &&
- Upload.where(url: url).empty?) &&
- (OptimizedImage.where(sha1: sha1).empty? &&
- OptimizedImage.where(url: url).empty?)
-
- FileUtils.rm(file_path)
- putc "#"
- else
- putc "."
+ Dir
+ .glob("#{uploads_directory}/**/*.*")
+ .each do |file_path|
+ sha1 = Upload.generate_digest(file_path)
+ url = file_path.split(public_directory, 2)[1]
+
+ if (Upload.where(sha1: sha1).empty? && Upload.where(url: url).empty?) &&
+ (OptimizedImage.where(sha1: sha1).empty? && OptimizedImage.where(url: url).empty?)
+ FileUtils.rm(file_path)
+ putc "#"
+ else
+ putc "."
+ end
end
- end
puts "Removing empty directories..."
puts `find #{uploads_directory} -type d -empty -exec rmdir {} \\;`
@@ -247,7 +250,7 @@ end
# list all missing uploads and optimized images
task "uploads:missing_files" => :environment do
if ENV["RAILS_DB"]
- list_missing_uploads(skip_optimized: ENV['SKIP_OPTIMIZED'])
+ list_missing_uploads(skip_optimized: ENV["SKIP_OPTIMIZED"])
else
RailsMultisite::ConnectionManagement.each_connection do |db|
if ENV["SKIP_EXTERNAL"] == "1" && Discourse.store.external?
@@ -264,7 +267,7 @@ task "uploads:missing_files" => :environment do
We recommend you run SKIP_EXTERNAL=1 rake uploads:missing to skip validating if on a multisite.
TEXT
end
- list_missing_uploads(skip_optimized: ENV['SKIP_OPTIMIZED'])
+ list_missing_uploads(skip_optimized: ENV["SKIP_OPTIMIZED"])
end
end
end
@@ -309,19 +312,17 @@ def regenerate_missing_optimized
default_scope = OptimizedImage.includes(:upload)
[
- default_scope
- .where("optimized_images.upload_id IN (?)", avatar_upload_ids),
-
+ default_scope.where("optimized_images.upload_id IN (?)", avatar_upload_ids),
default_scope
.where("optimized_images.upload_id NOT IN (?)", avatar_upload_ids)
.where("LENGTH(COALESCE(url, '')) > 0")
- .where("width > 0 AND height > 0")
+ .where("width > 0 AND height > 0"),
].each do |scope|
scope.find_each do |optimized_image|
upload = optimized_image.upload
- next unless optimized_image.url =~ /^\/[^\/]/
- next unless upload.url =~ /^\/[^\/]/
+ next unless optimized_image.url =~ %r{^/[^/]}
+ next unless upload.url =~ %r{^/[^/]}
thumbnail = "#{public_directory}#{optimized_image.url}"
original = "#{public_directory}#{upload.url}"
@@ -331,12 +332,17 @@ def regenerate_missing_optimized
if (!File.exist?(original) || File.size(original) <= 0) && upload.origin.present?
# try to fix it by redownloading it
begin
- downloaded = FileHelper.download(
- upload.origin,
- max_file_size: SiteSetting.max_image_size_kb.kilobytes,
- tmp_file_name: "discourse-missing",
- follow_redirect: true
- ) rescue nil
+ downloaded =
+ begin
+ FileHelper.download(
+ upload.origin,
+ max_file_size: SiteSetting.max_image_size_kb.kilobytes,
+ tmp_file_name: "discourse-missing",
+ follow_redirect: true,
+ )
+ rescue StandardError
+ nil
+ end
if downloaded && downloaded.size > 0
FileUtils.mkdir_p(File.dirname(original))
File.open(original, "wb") { |f| f.write(downloaded.read) }
@@ -382,7 +388,7 @@ task "uploads:stop_migration" => :environment do
puts "Migration stoped!"
end
-task "uploads:analyze", [:cache_path, :limit] => :environment do |_, args|
+task "uploads:analyze", %i[cache_path limit] => :environment do |_, args|
now = Time.zone.now
current_db = RailsMultisite::ConnectionManagement.current_db
@@ -390,7 +396,7 @@ task "uploads:analyze", [:cache_path, :limit] => :environment do |_, args|
cache_path = args[:cache_path]
current_db = RailsMultisite::ConnectionManagement.current_db
- uploads_path = Rails.root.join('public', 'uploads', current_db)
+ uploads_path = Rails.root.join("public", "uploads", current_db)
path =
if cache_path
@@ -405,45 +411,51 @@ task "uploads:analyze", [:cache_path, :limit] => :environment do |_, args|
extensions = {}
paths_count = 0
- File.readlines(path).each do |line|
- size, file_path = line.split(" ", 2)
-
- paths_count += 1
- extension = File.extname(file_path).chomp.downcase
- extensions[extension] ||= {}
- extensions[extension]["count"] ||= 0
- extensions[extension]["count"] += 1
- extensions[extension]["size"] ||= 0
- extensions[extension]["size"] += size.to_i
- end
+ File
+ .readlines(path)
+ .each do |line|
+ size, file_path = line.split(" ", 2)
+
+ paths_count += 1
+ extension = File.extname(file_path).chomp.downcase
+ extensions[extension] ||= {}
+ extensions[extension]["count"] ||= 0
+ extensions[extension]["count"] += 1
+ extensions[extension]["size"] ||= 0
+ extensions[extension]["size"] += size.to_i
+ end
uploads_count = Upload.count
optimized_images_count = OptimizedImage.count
puts <<~TEXT
Report for '#{current_db}'
- -----------#{'-' * current_db.length}
+ -----------#{"-" * current_db.length}
Number of `Upload` records in DB: #{uploads_count}
Number of `OptimizedImage` records in DB: #{optimized_images_count}
**Total DB records: #{uploads_count + optimized_images_count}**
Number of images in uploads folder: #{paths_count}
- ------------------------------------#{'-' * paths_count.to_s.length}
+ ------------------------------------#{"-" * paths_count.to_s.length}
TEXT
- helper = Class.new do
- include ActionView::Helpers::NumberHelper
- end
+ helper = Class.new { include ActionView::Helpers::NumberHelper }
helper = helper.new
- printf "%-15s | %-15s | %-15s\n", 'extname', 'total size', 'count'
+ printf "%-15s | %-15s | %-15s\n", "extname", "total size", "count"
puts "-" * 45
- extensions.sort_by { |_, value| value['size'] }.reverse.each do |extname, value|
- printf "%-15s | %-15s | %-15s\n", extname, helper.number_to_human_size(value['size']), value['count']
- end
+ extensions
+ .sort_by { |_, value| value["size"] }
+ .reverse
+ .each do |extname, value|
+ printf "%-15s | %-15s | %-15s\n",
+ extname,
+ helper.number_to_human_size(value["size"]),
+ value["count"]
+ end
puts "\n"
@@ -465,12 +477,22 @@ task "uploads:analyze", [:cache_path, :limit] => :environment do |_, args|
puts "Users using the most disk space"
puts "-------------------------------\n"
- printf "%-25s | %-25s | %-25s | %-25s\n", 'username', 'total size of uploads', 'number of uploads', 'number of optimized images'
+ printf "%-25s | %-25s | %-25s | %-25s\n",
+ "username",
+ "total size of uploads",
+ "number of uploads",
+ "number of optimized images"
puts "-" * 110
- DB.query_single(sql).each do |username, num_of_uploads, total_size_of_uploads, num_of_optimized_images|
- printf "%-25s | %-25s | %-25s | %-25s\n", username, helper.number_to_human_size(total_size_of_uploads), num_of_uploads, num_of_optimized_images
- end
+ DB
+ .query_single(sql)
+ .each do |username, num_of_uploads, total_size_of_uploads, num_of_optimized_images|
+ printf "%-25s | %-25s | %-25s | %-25s\n",
+ username,
+ helper.number_to_human_size(total_size_of_uploads),
+ num_of_uploads,
+ num_of_optimized_images
+ end
puts "\n"
puts "List of file paths @ #{path}"
@@ -486,7 +508,6 @@ task "uploads:recover_from_tombstone" => :environment do
end
task "uploads:recover" => :environment do
-
dry_run = ENV["DRY_RUN"].present?
stop_on_error = ENV["STOP_ON_ERROR"].present?
@@ -511,9 +532,7 @@ task "uploads:sync_s3_acls" => :environment do
puts "-" * 30
puts "Uploads marked as secure will get a private ACL, and uploads marked as not secure will get a public ACL."
puts "Upload ACLs will be updated in Sidekiq jobs in batches of 100 at a time, check Sidekiq queues for SyncAclsForUploads for progress."
- Upload.select(:id).find_in_batches(batch_size: 100) do |uploads|
- adjust_acls(uploads.map(&:id))
- end
+ Upload.select(:id).find_in_batches(batch_size: 100) { |uploads| adjust_acls(uploads.map(&:id)) }
puts "", "Upload ACL sync complete!"
end
end
@@ -529,7 +548,11 @@ task "uploads:disable_secure_uploads" => :environment do
SiteSetting.secure_uploads = false
- secure_uploads = Upload.joins(:upload_references).where(upload_references: { target_type: 'Post' }).where(secure: true)
+ secure_uploads =
+ Upload
+ .joins(:upload_references)
+ .where(upload_references: { target_type: "Post" })
+ .where(secure: true)
secure_upload_count = secure_uploads.count
secure_upload_ids = secure_uploads.pluck(:id)
@@ -537,12 +560,14 @@ task "uploads:disable_secure_uploads" => :environment do
secure_uploads.update_all(
secure: false,
security_last_changed_at: Time.zone.now,
- security_last_changed_reason: "marked as not secure by disable_secure_uploads task"
+ security_last_changed_reason: "marked as not secure by disable_secure_uploads task",
)
- post_ids_to_rebake = DB.query_single(
- "SELECT DISTINCT target_id FROM upload_references WHERE upload_id IN (?) AND target_type = 'Post'", secure_upload_ids
- )
+ post_ids_to_rebake =
+ DB.query_single(
+ "SELECT DISTINCT target_id FROM upload_references WHERE upload_id IN (?) AND target_type = 'Post'",
+ secure_upload_ids,
+ )
adjust_acls(secure_upload_ids)
post_rebake_errors = rebake_upload_posts(post_ids_to_rebake)
log_rebake_errors(post_rebake_errors)
@@ -574,9 +599,7 @@ task "uploads:secure_upload_analyse_and_update" => :environment do
# upload is not set to secure upload then this has no other effect on the upload,
# but we _must_ know what the access control post is because the with_secure_uploads?
# method is on the post, and this knows about the category security & PM status
- if SiteSetting.secure_uploads?
- update_uploads_access_control_post
- end
+ update_uploads_access_control_post if SiteSetting.secure_uploads?
puts "", "Analysing which uploads need to be marked secure and be rebaked.", ""
if SiteSetting.login_required?
@@ -584,7 +607,8 @@ task "uploads:secure_upload_analyse_and_update" => :environment do
post_ids_to_rebake, all_upload_ids_changed = mark_all_as_secure_login_required
else
# Otherwise only mark uploads linked to posts in secure categories or PMs as secure.
- post_ids_to_rebake, all_upload_ids_changed = update_specific_upload_security_no_login_required
+ post_ids_to_rebake, all_upload_ids_changed =
+ update_specific_upload_security_no_login_required
end
end
@@ -612,9 +636,7 @@ def adjust_acls(upload_ids_to_adjust_acl_for)
Jobs.enqueue(:sync_acls_for_uploads, upload_ids: upload_ids)
end
- if jobs_to_create > 1
- puts "ACL batching complete. Keep an eye on the Sidekiq queue for progress."
- end
+ puts "ACL batching complete. Keep an eye on the Sidekiq queue for progress." if jobs_to_create > 1
end
def mark_all_as_secure_login_required
@@ -633,7 +655,8 @@ def mark_all_as_secure_login_required
WHERE uploads.id = upl.upload_id AND NOT uploads.secure
RETURNING uploads.id
SQL
- puts "Marked #{post_upload_ids_marked_secure.count} upload(s) as secure because login_required is true.", ""
+ puts "Marked #{post_upload_ids_marked_secure.count} upload(s) as secure because login_required is true.",
+ ""
upload_ids_marked_not_secure = DB.query_single(<<~SQL, post_upload_ids_marked_secure)
UPDATE uploads
SET secure = false,
@@ -642,21 +665,22 @@ def mark_all_as_secure_login_required
WHERE id NOT IN (?) AND uploads.secure
RETURNING uploads.id
SQL
- puts "Marked #{upload_ids_marked_not_secure.count} upload(s) as not secure because they are not linked to posts.", ""
+ puts "Marked #{upload_ids_marked_not_secure.count} upload(s) as not secure because they are not linked to posts.",
+ ""
puts "Finished marking upload(s) as secure."
- post_ids_to_rebake = DB.query_single(
- "SELECT DISTINCT target_id FROM upload_references WHERE upload_id IN (?) AND target_type = 'Post'", post_upload_ids_marked_secure
- )
+ post_ids_to_rebake =
+ DB.query_single(
+ "SELECT DISTINCT target_id FROM upload_references WHERE upload_id IN (?) AND target_type = 'Post'",
+ post_upload_ids_marked_secure,
+ )
[post_ids_to_rebake, (post_upload_ids_marked_secure + upload_ids_marked_not_secure).uniq]
end
def log_rebake_errors(rebake_errors)
return if rebake_errors.empty?
puts "The following post rebakes failed with error:", ""
- rebake_errors.each do |message|
- puts message
- end
+ rebake_errors.each { |message| puts message }
end
def update_specific_upload_security_no_login_required
@@ -716,7 +740,11 @@ def update_specific_upload_security_no_login_required
puts "Finished updating upload security. Marked #{upload_ids_marked_not_secure.length} uploads not linked to posts as not secure."
all_upload_ids_changed = (upload_ids_changed + upload_ids_marked_not_secure).uniq
- post_ids_to_rebake = DB.query_single("SELECT DISTINCT target_id FROM upload_references WHERE upload_id IN (?) AND target_type = 'Post'", upload_ids_changed)
+ post_ids_to_rebake =
+ DB.query_single(
+ "SELECT DISTINCT target_id FROM upload_references WHERE upload_id IN (?) AND target_type = 'Post'",
+ upload_ids_changed,
+ )
[post_ids_to_rebake, all_upload_ids_changed]
end
@@ -760,30 +788,33 @@ def inline_uploads(post)
original_raw = post.raw
- post.raw = post.raw.gsub(/(\((\/uploads\S+).*\))/) do
- upload = Upload.find_by(url: $2)
- if !upload
- data = Upload.extract_url($2)
- if data && sha1 = data[2]
- upload = Upload.find_by(sha1: sha1)
+ post.raw =
+ post
+ .raw
+ .gsub(%r{(\((/uploads\S+).*\))}) do
+ upload = Upload.find_by(url: $2)
if !upload
- sha_map = JSON.parse(post.custom_fields["UPLOAD_SHA1_MAP"] || "{}")
- if mapped_sha = sha_map[sha1]
- upload = Upload.find_by(sha1: mapped_sha)
+ data = Upload.extract_url($2)
+ if data && sha1 = data[2]
+ upload = Upload.find_by(sha1: sha1)
+ if !upload
+ sha_map = JSON.parse(post.custom_fields["UPLOAD_SHA1_MAP"] || "{}")
+ if mapped_sha = sha_map[sha1]
+ upload = Upload.find_by(sha1: mapped_sha)
+ end
+ end
end
end
- end
- end
- result = $1
+ result = $1
- if upload&.id
- result.sub!($2, upload.short_url)
- replaced = true
- else
- puts "Upload not found #{$2} in Post #{post.id} - #{post.url}"
- end
- result
- end
+ if upload&.id
+ result.sub!($2, upload.short_url)
+ replaced = true
+ else
+ puts "Upload not found #{$2} in Post #{post.id} - #{post.url}"
+ end
+ result
+ end
if replaced
puts "Corrected image urls in #{post.full_url} raw backup stored in custom field"
@@ -798,33 +829,36 @@ def inline_img_tags(post)
replaced = false
original_raw = post.raw
- post.raw = post.raw.gsub(/(<img\s+src=["'](\/uploads\/[^'"]*)["'].*>)/i) do
- next if $2.include?("..")
-
- upload = Upload.find_by(url: $2)
- if !upload
- data = Upload.extract_url($2)
- if data && sha1 = data[2]
- upload = Upload.find_by(sha1: sha1)
- end
- end
- if !upload
- local_file = File.join(Rails.root, "public", $2)
- if File.exist?(local_file)
- File.open(local_file) do |f|
- upload = UploadCreator.new(f, "image").create_for(post.user_id)
+ post.raw =
+ post
+ .raw
+ .gsub(%r{(<img\s+src=["'](/uploads/[^'"]*)["'].*>)}i) do
+ next if $2.include?("..")
+
+ upload = Upload.find_by(url: $2)
+ if !upload
+ data = Upload.extract_url($2)
+ if data && sha1 = data[2]
+ upload = Upload.find_by(sha1: sha1)
+ end
+ end
+ if !upload
+ local_file = File.join(Rails.root, "public", $2)
+ if File.exist?(local_file)
+ File.open(local_file) do |f|
+ upload = UploadCreator.new(f, "image").create_for(post.user_id)
+ end
+ end
end
- end
- end
- if upload
- replaced = true
- "![image](#{upload.short_url})"
- else
- puts "skipping missing upload in #{post.full_url} #{$1}"
- $1
- end
- end
+ if upload
+ replaced = true
+ "![image](#{upload.short_url})"
+ else
+ puts "skipping missing upload in #{post.full_url} #{$1}"
+ $1
+ end
+ end
if replaced
puts "Corrected image urls in #{post.full_url} raw backup stored in custom field"
@@ -836,21 +870,15 @@ def inline_img_tags(post)
end
def fix_relative_links
- Post.where('raw like ?', '%](/uploads%').find_each do |post|
- inline_uploads(post)
- end
- Post.where("raw ilike ?", '%<img%src=%/uploads/%>%').find_each do |post|
- inline_img_tags(post)
- end
+ Post.where("raw like ?", "%](/uploads%").find_each { |post| inline_uploads(post) }
+ Post.where("raw ilike ?", "%<img%src=%/uploads/%>%").find_each { |post| inline_img_tags(post) }
end
task "uploads:fix_relative_upload_links" => :environment do
if RailsMultisite::ConnectionManagement.current_db != "default"
fix_relative_links
else
- RailsMultisite::ConnectionManagement.each_connection do
- fix_relative_links
- end
+ RailsMultisite::ConnectionManagement.each_connection { fix_relative_links }
end
end
@@ -868,74 +896,79 @@ def analyze_missing_s3
other = []
all = []
- DB.query(sql, invalid_etag: Upload.verification_statuses[:invalid_etag]).each do |r|
- all << r
- if r.target_id
- lookup[r.target_id] ||= []
- lookup[r.target_id] << [r.url, r.sha1, r.extension]
- else
- other << r
+ DB
+ .query(sql, invalid_etag: Upload.verification_statuses[:invalid_etag])
+ .each do |r|
+ all << r
+ if r.target_id
+ lookup[r.target_id] ||= []
+ lookup[r.target_id] << [r.url, r.sha1, r.extension]
+ else
+ other << r
+ end
end
- end
posts = Post.where(id: lookup.keys)
- posts.order(:created_at).each do |post|
- puts "#{Discourse.base_url}/p/#{post.id} #{lookup[post.id].length} missing, #{post.created_at}"
- lookup[post.id].each do |url, sha1, extension|
- puts url
- puts "#{Upload.base62_sha1(sha1)}.#{extension}"
+ posts
+ .order(:created_at)
+ .each do |post|
+ puts "#{Discourse.base_url}/p/#{post.id} #{lookup[post.id].length} missing, #{post.created_at}"
+ lookup[post.id].each do |url, sha1, extension|
+ puts url
+ puts "#{Upload.base62_sha1(sha1)}.#{extension}"
+ end
+ puts
end
- puts
- end
missing_uploads = Upload.where(verification_status: Upload.verification_statuses[:invalid_etag])
puts "Total missing uploads: #{missing_uploads.count}, newest is #{missing_uploads.maximum(:created_at)}"
- puts "Total problem posts: #{lookup.keys.count} with #{lookup.values.sum { |a| a.length } } missing uploads"
+ puts "Total problem posts: #{lookup.keys.count} with #{lookup.values.sum { |a| a.length }} missing uploads"
puts "Other missing uploads count: #{other.count}"
if all.count > 0
ids = all.map { |r| r.id }
lookups = [
- [:upload_references, :upload_id],
- [:users, :uploaded_avatar_id],
- [:user_avatars, :gravatar_upload_id],
- [:user_avatars, :custom_upload_id],
- [:site_settings, ["NULLIF(value, '')::integer", "data_type = #{SiteSettings::TypeSupervisor.types[:upload].to_i}"]],
- [:user_profiles, :profile_background_upload_id],
- [:user_profiles, :card_background_upload_id],
- [:categories, :uploaded_logo_id],
- [:categories, :uploaded_logo_dark_id],
- [:categories, :uploaded_background_id],
- [:custom_emojis, :upload_id],
- [:theme_fields, :upload_id],
- [:user_exports, :upload_id],
- [:groups, :flair_upload_id],
+ %i[upload_references upload_id],
+ %i[users uploaded_avatar_id],
+ %i[user_avatars gravatar_upload_id],
+ %i[user_avatars custom_upload_id],
+ [
+ :site_settings,
+ [
+ "NULLIF(value, '')::integer",
+ "data_type = #{SiteSettings::TypeSupervisor.types[:upload].to_i}",
+ ],
+ ],
+ %i[user_profiles profile_background_upload_id],
+ %i[user_profiles card_background_upload_id],
+ %i[categories uploaded_logo_id],
+ %i[categories uploaded_logo_dark_id],
+ %i[categories uploaded_background_id],
+ %i[custom_emojis upload_id],
+ %i[theme_fields upload_id],
+ %i[user_exports upload_id],
+ %i[groups flair_upload_id],
]
lookups.each do |table, (column, where)|
count = DB.query_single(<<~SQL, ids: ids).first
SELECT COUNT(*) FROM #{table} WHERE #{column} IN (:ids) #{"AND #{where}" if where}
SQL
- if count > 0
- puts "Found #{count} missing row#{"s" if count > 1} in #{table}(#{column})"
- end
+ puts "Found #{count} missing row#{"s" if count > 1} in #{table}(#{column})" if count > 0
end
-
end
-
end
def delete_missing_s3
- missing = Upload.where(
- verification_status: Upload.verification_statuses[:invalid_etag]
- ).order(:created_at)
+ missing =
+ Upload.where(verification_status: Upload.verification_statuses[:invalid_etag]).order(
+ :created_at,
+ )
count = missing.count
if count > 0
puts "The following uploads will be deleted from the database"
- missing.each do |upload|
- puts "#{upload.id} - #{upload.url} - #{upload.created_at}"
- end
+ missing.each { |upload| puts "#{upload.id} - #{upload.url} - #{upload.created_at}" }
puts "Please confirm you wish to delete #{count} upload records by typing YES"
confirm = STDIN.gets.strip
if confirm == "YES"
@@ -952,9 +985,7 @@ task "uploads:delete_missing_s3" => :environment do
if RailsMultisite::ConnectionManagement.current_db != "default"
delete_missing_s3
else
- RailsMultisite::ConnectionManagement.each_connection do
- delete_missing_s3
- end
+ RailsMultisite::ConnectionManagement.each_connection { delete_missing_s3 }
end
end
@@ -962,9 +993,7 @@ task "uploads:analyze_missing_s3" => :environment do
if RailsMultisite::ConnectionManagement.current_db != "default"
analyze_missing_s3
else
- RailsMultisite::ConnectionManagement.each_connection do
- analyze_missing_s3
- end
+ RailsMultisite::ConnectionManagement.each_connection { analyze_missing_s3 }
end
end
@@ -972,9 +1001,7 @@ def fix_missing_s3
Jobs.run_immediately!
puts "Attempting to download missing uploads and recreate"
- ids = Upload.where(
- verification_status: Upload.verification_statuses[:invalid_etag]
- ).pluck(:id)
+ ids = Upload.where(verification_status: Upload.verification_statuses[:invalid_etag]).pluck(:id)
ids.each do |id|
upload = Upload.find_by(id: id)
next if !upload
@@ -983,12 +1010,22 @@ def fix_missing_s3
downloaded_from = nil
begin
- tempfile = FileHelper.download(upload.url, max_file_size: 30.megabyte, tmp_file_name: "#{SecureRandom.hex}.#{upload.extension}")
+ tempfile =
+ FileHelper.download(
+ upload.url,
+ max_file_size: 30.megabyte,
+ tmp_file_name: "#{SecureRandom.hex}.#{upload.extension}",
+ )
downloaded_from = upload.url
rescue => e
if upload.origin.present?
begin
- tempfile = FileHelper.download(upload.origin, max_file_size: 30.megabyte, tmp_file_name: "#{SecureRandom.hex}.#{upload.extension}")
+ tempfile =
+ FileHelper.download(
+ upload.origin,
+ max_file_size: 30.megabyte,
+ tmp_file_name: "#{SecureRandom.hex}.#{upload.extension}",
+ )
downloaded_from = upload.origin
rescue => e
puts "Failed to download #{upload.origin} #{e}"
@@ -1006,7 +1043,12 @@ def fix_missing_s3
Upload.transaction do
begin
upload.update_column(:sha1, SecureRandom.hex)
- fixed_upload = UploadCreator.new(tempfile, "temp.#{upload.extension}", skip_validations: true).create_for(Discourse.system_user.id)
+ fixed_upload =
+ UploadCreator.new(
+ tempfile,
+ "temp.#{upload.extension}",
+ skip_validations: true,
+ ).create_for(Discourse.system_user.id)
rescue => fix_error
# invalid extension is the most common issue
end
@@ -1020,7 +1062,11 @@ def fix_missing_s3
# we may end up breaking posts
save_error = nil
begin
- upload.assign_attributes(etag: fixed_upload.etag, url: fixed_upload.url, verification_status: Upload.verification_statuses[:unchecked])
+ upload.assign_attributes(
+ etag: fixed_upload.etag,
+ url: fixed_upload.url,
+ verification_status: Upload.verification_statuses[:unchecked],
+ )
upload.save!(validate: false)
rescue => save_error
# url might be null
@@ -1030,13 +1076,16 @@ def fix_missing_s3
puts "Failed to save upload #{save_error}"
else
OptimizedImage.where(upload_id: upload.id).destroy_all
- rebake_ids = UploadReference.where(upload_id: upload.id).where(target_type: 'Post').pluck(:target_id)
+ rebake_ids =
+ UploadReference.where(upload_id: upload.id).where(target_type: "Post").pluck(:target_id)
if rebake_ids.present?
- Post.where(id: rebake_ids).each do |post|
- puts "rebake post #{post.id}"
- post.rebake!
- end
+ Post
+ .where(id: rebake_ids)
+ .each do |post|
+ puts "rebake post #{post.id}"
+ post.rebake!
+ end
end
end
end
@@ -1055,15 +1104,17 @@ def fix_missing_s3
ORDER BY ur.target_id DESC
SQL
- DB.query_single(sql, invalid_etag: Upload.verification_statuses[:invalid_etag]).each do |post_id|
- post = Post.find_by(id: post_id)
- if post
- post.rebake!
- print "."
- else
- puts "Skipping #{post_id} since it is deleted"
+ DB
+ .query_single(sql, invalid_etag: Upload.verification_statuses[:invalid_etag])
+ .each do |post_id|
+ post = Post.find_by(id: post_id)
+ if post
+ post.rebake!
+ print "."
+ else
+ puts "Skipping #{post_id} since it is deleted"
+ end
end
- end
puts
end
@@ -1071,9 +1122,7 @@ task "uploads:fix_missing_s3" => :environment do
if RailsMultisite::ConnectionManagement.current_db != "default"
fix_missing_s3
else
- RailsMultisite::ConnectionManagement.each_connection do
- fix_missing_s3
- end
+ RailsMultisite::ConnectionManagement.each_connection { fix_missing_s3 }
end
end
@@ -1096,10 +1145,7 @@ task "uploads:downsize" => :environment do
min_image_pixels = 500_000 # 0.5 megapixels
default_image_pixels = 1_000_000 # 1 megapixel
- max_image_pixels = [
- ARGV[0]&.to_i || default_image_pixels,
- min_image_pixels
- ].max
+ max_image_pixels = [ARGV[0]&.to_i || default_image_pixels, min_image_pixels].max
ENV["VERBOSE"] = "1" if ENV["INTERACTIVE"]
@@ -1112,10 +1158,10 @@ task "uploads:downsize" => :environment do
dimensions_count = 0
downsized_count = 0
- scope = Upload
- .by_users
- .with_no_non_post_relations
- .where("LOWER(extension) IN ('jpg', 'jpeg', 'gif', 'png')")
+ scope =
+ Upload.by_users.with_no_non_post_relations.where(
+ "LOWER(extension) IN ('jpg', 'jpeg', 'gif', 'png')",
+ )
scope = scope.where(<<-SQL, max_image_pixels)
COALESCE(width, 0) = 0 OR
@@ -1129,9 +1175,7 @@ task "uploads:downsize" => :environment do
scope = scope.where("uploads.id % ? = ?", ENV["WORKER_COUNT"], ENV["WORKER_ID"])
end
- if ENV["START_ID"]
- scope = scope.where("uploads.id >= ?", ENV["START_ID"])
- end
+ scope = scope.where("uploads.id >= ?", ENV["START_ID"]) if ENV["START_ID"]
skipped = 0
total_count = scope.count
@@ -1144,11 +1188,18 @@ task "uploads:downsize" => :environment do
print "\r#{progress}% Fixed dimensions: #{dimensions_count} Downsized: #{downsized_count} Skipped: #{skipped} (upload id: #{upload.id})"
log "\n"
- path = if upload.local?
- Discourse.store.path_for(upload)
- else
- (Discourse.store.download(upload, max_file_size_kb: 100.megabytes) rescue nil)&.path
- end
+ path =
+ if upload.local?
+ Discourse.store.path_for(upload)
+ else
+ (
+ begin
+ Discourse.store.download(upload, max_file_size_kb: 100.megabytes)
+ rescue StandardError
+ nil
+ end
+ )&.path
+ end
unless path
log "No image path"
@@ -1187,7 +1238,7 @@ task "uploads:downsize" => :environment do
height: h,
thumbnail_width: ww,
thumbnail_height: hh,
- filesize: File.size(path)
+ filesize: File.size(path),
}
if upload.changed?
@@ -1209,13 +1260,14 @@ task "uploads:downsize" => :environment do
next
end
- result = ShrinkUploadedImage.new(
- upload: upload,
- path: path,
- max_pixels: max_image_pixels,
- verbose: ENV["VERBOSE"],
- interactive: ENV["INTERACTIVE"]
- ).perform
+ result =
+ ShrinkUploadedImage.new(
+ upload: upload,
+ path: path,
+ max_pixels: max_image_pixels,
+ verbose: ENV["VERBOSE"],
+ interactive: ENV["INTERACTIVE"],
+ ).perform
if result
downsized_count += 1
diff --git a/lib/tasks/users.rake b/lib/tasks/users.rake
index b737405c5a4..a5c9c8103c4 100644
--- a/lib/tasks/users.rake
+++ b/lib/tasks/users.rake
@@ -1,7 +1,8 @@
# frozen_string_literal: true
desc "Change topic/post ownership of all the topics/posts by a specific user (without creating new revision)"
-task "users:change_post_ownership", [:old_username, :new_username, :archetype] => [:environment] do |_, args|
+task "users:change_post_ownership",
+ %i[old_username new_username archetype] => [:environment] do |_, args|
old_username = args[:old_username]
new_username = args[:new_username]
archetype = args[:archetype]
@@ -27,7 +28,13 @@ task "users:change_post_ownership", [:old_username, :new_username, :archetype] =
puts "Changing post ownership"
i = 0
posts.each do |p|
- PostOwnerChanger.new(post_ids: [p.id], topic_id: p.topic.id, new_owner: User.find_by(username_lower: new_user.username_lower), acting_user: User.find_by(username_lower: "system"), skip_revision: true).change_owner!
+ PostOwnerChanger.new(
+ post_ids: [p.id],
+ topic_id: p.topic.id,
+ new_owner: User.find_by(username_lower: new_user.username_lower),
+ acting_user: User.find_by(username_lower: "system"),
+ skip_revision: true,
+ ).change_owner!
putc "."
i += 1
end
@@ -35,7 +42,7 @@ task "users:change_post_ownership", [:old_username, :new_username, :archetype] =
end
desc "Merge the source user into the target user"
-task "users:merge", [:source_username, :target_username] => [:environment] do |_, args|
+task "users:merge", %i[source_username target_username] => [:environment] do |_, args|
source_username = args[:source_username]
target_username = args[:target_username]
@@ -52,7 +59,7 @@ task "users:merge", [:source_username, :target_username] => [:environment] do |_
end
desc "Rename a user"
-task "users:rename", [:old_username, :new_username] => [:environment] do |_, args|
+task "users:rename", %i[old_username new_username] => [:environment] do |_, args|
old_username = args[:old_username]
new_username = args[:new_username]
@@ -67,7 +74,7 @@ task "users:rename", [:old_username, :new_username] => [:environment] do |_, arg
end
desc "Update username in quotes and mentions. Use this if the user was renamed before proper renaming existed."
-task "users:update_posts", [:old_username, :current_username] => [:environment] do |_, args|
+task "users:update_posts", %i[old_username current_username] => [:environment] do |_, args|
old_username = args[:old_username]
current_username = args[:current_username]
@@ -77,18 +84,20 @@ task "users:update_posts", [:old_username, :current_username] => [:environment]
end
user = find_user(current_username)
- UsernameChanger.update_username(user_id: user.id,
- old_username: old_username,
- new_username: user.username,
- avatar_template: user.avatar_template,
- asynchronous: false)
+ UsernameChanger.update_username(
+ user_id: user.id,
+ old_username: old_username,
+ new_username: user.username,
+ avatar_template: user.avatar_template,
+ asynchronous: false,
+ )
puts "", "Username updated!", ""
end
-desc 'Recalculate post and topic counts in user stats'
-task 'users:recalculate_post_counts' => :environment do
- puts '', 'Updating user stats...'
+desc "Recalculate post and topic counts in user stats"
+task "users:recalculate_post_counts" => :environment do
+ puts "", "Updating user stats..."
filter_public_posts_and_topics = <<~SQL
p.deleted_at IS NULL
@@ -100,7 +109,7 @@ task 'users:recalculate_post_counts' => :environment do
AND p.user_id > 0
SQL
- puts 'post counts...'
+ puts "post counts..."
# all public replies
DB.exec <<~SQL
@@ -119,7 +128,7 @@ GROUP BY p.user_id
AND user_stats.post_count <> X.post_count
SQL
- puts 'topic counts...'
+ puts "topic counts..."
# public topics
DB.exec <<~SQL
@@ -138,7 +147,7 @@ GROUP BY p.user_id
AND user_stats.topic_count <> X.topic_count
SQL
- puts 'Done!', ''
+ puts "Done!", ""
end
desc "Disable 2FA for user with the given username"
@@ -151,21 +160,21 @@ end
desc "Anonymize all users except staff"
task "users:anonymize_all" => :environment do
- require 'highline/import'
+ require "highline/import"
- non_staff_users = User.where('NOT admin AND NOT moderator')
+ non_staff_users = User.where("NOT admin AND NOT moderator")
total = non_staff_users.count
anonymized = 0
confirm_anonymize = ask("Are you sure you want to anonymize #{total} users? (Y/n)")
- exit 1 unless (confirm_anonymize == "" || confirm_anonymize.downcase == 'y')
+ exit 1 unless (confirm_anonymize == "" || confirm_anonymize.downcase == "y")
system_user = Discourse.system_user
non_staff_users.each do |user|
begin
UserAnonymizer.new(user, system_user).make_anonymous
print_status(anonymized += 1, total)
- rescue
+ rescue StandardError
# skip
end
end
@@ -177,18 +186,18 @@ desc "List all users which have been staff in the last month"
task "users:list_recent_staff" => :environment do
current_staff_ids = User.human_users.where("admin OR moderator").pluck(:id)
recent_actions = UserHistory.where("created_at > ?", 1.month.ago)
- recent_admin_ids = recent_actions.where(action: UserHistory.actions[:revoke_admin]).pluck(:target_user_id)
- recent_moderator_ids = recent_actions.where(action: UserHistory.actions[:revoke_moderation]).pluck(:target_user_id)
+ recent_admin_ids =
+ recent_actions.where(action: UserHistory.actions[:revoke_admin]).pluck(:target_user_id)
+ recent_moderator_ids =
+ recent_actions.where(action: UserHistory.actions[:revoke_moderation]).pluck(:target_user_id)
all_ids = current_staff_ids + recent_admin_ids + recent_moderator_ids
users = User.where(id: all_ids.uniq)
puts "Users which have had staff privileges in the last month:"
- users.each do |user|
- puts "#{user.id}: #{user.username} (#{user.email})"
- end
+ users.each { |user| puts "#{user.id}: #{user.username} (#{user.email})" }
puts "----"
- puts "user_ids = [#{all_ids.uniq.join(',')}]"
+ puts "user_ids = [#{all_ids.uniq.join(",")}]"
end
def find_user(username)
diff --git a/lib/temporary_db.rb b/lib/temporary_db.rb
index 1bcffa570d8..96e2fe261f1 100644
--- a/lib/temporary_db.rb
+++ b/lib/temporary_db.rb
@@ -15,7 +15,7 @@ class TemporaryDb
def pg_bin_path
return @pg_bin_path if @pg_bin_path
- ["13", "12", "11", "10"].each do |v|
+ %w[13 12 11 10].each do |v|
bin_path = "/usr/lib/postgresql/#{v}/bin"
if File.exist?("#{bin_path}/pg_ctl")
@pg_bin_path = bin_path
@@ -24,9 +24,7 @@ class TemporaryDb
end
if !@pg_bin_path
bin_path = "/Applications/Postgres.app/Contents/Versions/latest/bin"
- if File.exist?("#{bin_path}/pg_ctl")
- @pg_bin_path = bin_path
- end
+ @pg_bin_path = bin_path if File.exist?("#{bin_path}/pg_ctl")
end
if !@pg_bin_path
puts "Can not find postgres bin path"
@@ -39,30 +37,24 @@ class TemporaryDb
return @initdb_path if @initdb_path
@initdb_path = `which initdb 2> /dev/null`.strip
- if @initdb_path.length == 0
- @initdb_path = "#{pg_bin_path}/initdb"
- end
+ @initdb_path = "#{pg_bin_path}/initdb" if @initdb_path.length == 0
@initdb_path
end
def find_free_port(range)
- range.each do |port|
- return port if port_available?(port)
- end
+ range.each { |port| return port if port_available?(port) }
end
def pg_port
- @pg_port ||= find_free_port(11000..11900)
+ @pg_port ||= find_free_port(11_000..11_900)
end
def pg_ctl_path
return @pg_ctl_path if @pg_ctl_path
@pg_ctl_path = `which pg_ctl 2> /dev/null`.strip
- if @pg_ctl_path.length == 0
- @pg_ctl_path = "#{pg_bin_path}/pg_ctl"
- end
+ @pg_ctl_path = "#{pg_bin_path}/pg_ctl" if @pg_ctl_path.length == 0
@pg_ctl_path
end
@@ -76,16 +68,12 @@ class TemporaryDb
File.write(PG_CONF, conf + "\nport = #{pg_port}\nunix_socket_directories = '#{PG_SOCK_PATH}'")
puts "Starting postgres on port: #{pg_port}"
- ENV['DISCOURSE_PG_PORT'] = pg_port.to_s
+ ENV["DISCOURSE_PG_PORT"] = pg_port.to_s
- Thread.new do
- `#{pg_ctl_path} -D '#{PG_TEMP_PATH}' start`
- end
+ Thread.new { `#{pg_ctl_path} -D '#{PG_TEMP_PATH}' start` }
puts "Waiting for PG server to start..."
- while !`#{pg_ctl_path} -D '#{PG_TEMP_PATH}' status`.include?('server is running')
- sleep 0.1
- end
+ sleep 0.1 while !`#{pg_ctl_path} -D '#{PG_TEMP_PATH}' status`.include?("server is running")
@started = true
`createuser -h localhost -p #{pg_port} -s -D -w discourse 2> /dev/null`
@@ -127,22 +115,20 @@ class TemporaryDb
end
def migrate
- if !@started
- raise "Error: the database must be started before it can be migrated."
- end
+ raise "Error: the database must be started before it can be migrated." if !@started
ActiveRecord::Base.establish_connection(
- adapter: 'postgresql',
- database: 'discourse',
+ adapter: "postgresql",
+ database: "discourse",
port: pg_port,
- host: 'localhost'
+ host: "localhost",
)
puts "Running migrations on blank database!"
old_stdout = $stdout.clone
old_stderr = $stderr.clone
- $stdout.reopen(File.new('/dev/null', 'w'))
- $stderr.reopen(File.new('/dev/null', 'w'))
+ $stdout.reopen(File.new("/dev/null", "w"))
+ $stderr.reopen(File.new("/dev/null", "w"))
SeedFu.quiet = true
Rake::Task["db:migrate"].invoke
diff --git a/lib/temporary_redis.rb b/lib/temporary_redis.rb
index fb2a7994017..c567ecab083 100644
--- a/lib/temporary_redis.rb
+++ b/lib/temporary_redis.rb
@@ -12,7 +12,7 @@ class TemporaryRedis
end
def port
- @port ||= find_free_port(11000..11900)
+ @port ||= find_free_port(11_000..11_900)
end
def start
@@ -22,29 +22,35 @@ class TemporaryRedis
FileUtils.touch(REDIS_LOG_PATH)
puts "Starting redis on port: #{port}"
- @thread = Thread.new do
- system(
- @redis_server_bin,
- "--port", port.to_s,
- "--pidfile", REDIS_PID_PATH,
- "--logfile", REDIS_LOG_PATH,
- "--databases", "1",
- "--save", '""',
- "--appendonly", "no",
- "--daemonize", "no",
- "--maxclients", "100",
- "--dir", REDIS_TEMP_DIR
- )
- end
+ @thread =
+ Thread.new do
+ system(
+ @redis_server_bin,
+ "--port",
+ port.to_s,
+ "--pidfile",
+ REDIS_PID_PATH,
+ "--logfile",
+ REDIS_LOG_PATH,
+ "--databases",
+ "1",
+ "--save",
+ '""',
+ "--appendonly",
+ "no",
+ "--daemonize",
+ "no",
+ "--maxclients",
+ "100",
+ "--dir",
+ REDIS_TEMP_DIR,
+ )
+ end
puts "Waiting for redis server to start..."
success = false
instance = nil
- config = {
- port: port,
- host: "127.0.0.1",
- db: 0
- }
+ config = { port: port, host: "127.0.0.1", db: 0 }
start = Time.now
while !success
begin
@@ -82,20 +88,18 @@ class TemporaryRedis
def set_redis_server_bin
path = `which redis-server 2> /dev/null`.strip
if path.size < 1
- STDERR.puts 'ERROR: redis-server is not installed on this machine. Please install it'
+ STDERR.puts "ERROR: redis-server is not installed on this machine. Please install it"
exit(1)
end
@redis_server_bin = path
rescue => ex
- STDERR.puts 'ERROR: Failed to find redis-server binary:'
+ STDERR.puts "ERROR: Failed to find redis-server binary:"
STDERR.puts ex.inspect
exit(1)
end
def find_free_port(range)
- range.each do |port|
- return port if port_available?(port)
- end
+ range.each { |port| return port if port_available?(port) }
end
def port_available?(port)
diff --git a/lib/text_cleaner.rb b/lib/text_cleaner.rb
index 0000d0b971f..aeb8ab20fa9 100644
--- a/lib/text_cleaner.rb
+++ b/lib/text_cleaner.rb
@@ -5,10 +5,9 @@
#
# We use ActiveSupport mb_chars from here to properly support non ascii downcase
-require 'active_support/core_ext/string/multibyte'
+require "active_support/core_ext/string/multibyte"
class TextCleaner
-
def self.title_options
# cf. http://meta.discourse.org/t/should-we-have-auto-replace-rules-in-titles/5687
{
@@ -17,11 +16,12 @@ class TextCleaner
replace_all_upper_case: SiteSetting.title_prettify && !SiteSetting.allow_uppercase_posts,
capitalize_first_letter: SiteSetting.title_prettify,
remove_all_periods_from_the_end: SiteSetting.title_prettify,
- remove_extraneous_space: SiteSetting.title_prettify && SiteSetting.title_remove_extraneous_space,
+ remove_extraneous_space:
+ SiteSetting.title_prettify && SiteSetting.title_remove_extraneous_space,
fixes_interior_spaces: true,
strip_whitespaces: true,
strip_zero_width_spaces: true,
- case_option: SiteSetting.default_locale == "tr_TR" ? :turkic : nil
+ case_option: SiteSetting.default_locale == "tr_TR" ? :turkic : nil,
}
end
@@ -36,18 +36,19 @@ class TextCleaner
text.scrub!("")
# Replace !!!!! with a single !
- text.gsub!(/!+/, '!') if opts[:deduplicate_exclamation_marks]
+ text.gsub!(/!+/, "!") if opts[:deduplicate_exclamation_marks]
# Replace ????? with a single ?
- text.gsub!(/\?+/, '?') if opts[:deduplicate_question_marks]
+ text.gsub!(/\?+/, "?") if opts[:deduplicate_question_marks]
# Replace all-caps text with regular case letters
- text = downcase(text.mb_chars, opts).to_s if opts[:replace_all_upper_case] && (text == upcase(text.mb_chars, opts))
+ text = downcase(text.mb_chars, opts).to_s if opts[:replace_all_upper_case] &&
+ (text == upcase(text.mb_chars, opts))
# Capitalize first letter, but only when entire first word is lowercase
- first, rest = text.split(' ', 2)
+ first, rest = text.split(" ", 2)
if first && opts[:capitalize_first_letter] && first == downcase(first.mb_chars, opts)
- text = +"#{capitalize(first.mb_chars, opts)}#{rest ? ' ' + rest : ''}"
+ text = +"#{capitalize(first.mb_chars, opts)}#{rest ? " " + rest : ""}"
end
# Remove unnecessary periods at the end
@@ -57,7 +58,7 @@ class TextCleaner
text.sub!(/\s+([!?]\s*)\z/, '\1') if opts[:remove_extraneous_space]
# Fixes interior spaces
- text.gsub!(/ +/, ' ') if opts[:fixes_interior_spaces]
+ text.gsub!(/ +/, " ") if opts[:fixes_interior_spaces]
# Normalize whitespaces
text = normalize_whitespaces(text)
@@ -66,15 +67,19 @@ class TextCleaner
text.strip! if opts[:strip_whitespaces]
# Strip zero width spaces
- text.gsub!(/\u200b/, '') if opts[:strip_zero_width_spaces]
+ text.gsub!(/\u200b/, "") if opts[:strip_zero_width_spaces]
text
end
- @@whitespaces_regexp = Regexp.new("(\u00A0|\u1680|\u180E|[\u2000-\u200A]|\u2028|\u2029|\u202F|\u205F|\u3000)", Regexp::IGNORECASE).freeze
+ @@whitespaces_regexp =
+ Regexp.new(
+ "(\u00A0|\u1680|\u180E|[\u2000-\u200A]|\u2028|\u2029|\u202F|\u205F|\u3000)",
+ Regexp::IGNORECASE,
+ ).freeze
def self.normalize_whitespaces(text)
- text&.gsub(@@whitespaces_regexp, ' ')
+ text&.gsub(@@whitespaces_regexp, " ")
end
def self.downcase(text, opts)
diff --git a/lib/text_sentinel.rb b/lib/text_sentinel.rb
index 1cd7e8d5913..1a400712f79 100644
--- a/lib/text_sentinel.rb
+++ b/lib/text_sentinel.rb
@@ -2,56 +2,57 @@
# We use ActiveSupport mb_chars from here to properly support non ascii downcase
# TODO remove when ruby 2.4 lands
-require 'active_support/core_ext/string/multibyte'
+require "active_support/core_ext/string/multibyte"
#
# Given a string, tell us whether or not is acceptable.
#
class TextSentinel
-
attr_accessor :text
ENTROPY_SCALE ||= 0.7
def initialize(text, opts = nil)
@opts = opts || {}
- @text = text.to_s.encode('UTF-8', invalid: :replace, undef: :replace, replace: '')
+ @text = text.to_s.encode("UTF-8", invalid: :replace, undef: :replace, replace: "")
end
def self.body_sentinel(text, opts = {})
entropy = SiteSetting.body_min_entropy
if opts[:private_message]
- scale_entropy = SiteSetting.min_personal_message_post_length.to_f / SiteSetting.min_post_length.to_f
+ scale_entropy =
+ SiteSetting.min_personal_message_post_length.to_f / SiteSetting.min_post_length.to_f
entropy = (entropy * scale_entropy).to_i
- entropy = (SiteSetting.min_personal_message_post_length.to_f * ENTROPY_SCALE).to_i if entropy > SiteSetting.min_personal_message_post_length
+ entropy =
+ (SiteSetting.min_personal_message_post_length.to_f * ENTROPY_SCALE).to_i if entropy >
+ SiteSetting.min_personal_message_post_length
else
- entropy = (SiteSetting.min_post_length.to_f * ENTROPY_SCALE).to_i if entropy > SiteSetting.min_post_length
+ entropy = (SiteSetting.min_post_length.to_f * ENTROPY_SCALE).to_i if entropy >
+ SiteSetting.min_post_length
end
TextSentinel.new(text, min_entropy: entropy)
end
def self.title_sentinel(text)
- entropy = if SiteSetting.min_topic_title_length > SiteSetting.title_min_entropy
- SiteSetting.title_min_entropy
- else
- (SiteSetting.min_topic_title_length.to_f * ENTROPY_SCALE).to_i
- end
+ entropy =
+ if SiteSetting.min_topic_title_length > SiteSetting.title_min_entropy
+ SiteSetting.title_min_entropy
+ else
+ (SiteSetting.min_topic_title_length.to_f * ENTROPY_SCALE).to_i
+ end
TextSentinel.new(text, min_entropy: entropy, max_word_length: SiteSetting.title_max_word_length)
end
# Entropy is a number of how many unique characters the string needs.
# Non-ASCII characters are weighted heavier since they contain more "information"
def entropy
- chars = @text.to_s.strip.split('')
- @entropy ||= chars.pack('M*' * chars.size).gsub("\n", '').split('=').uniq.size
+ chars = @text.to_s.strip.split("")
+ @entropy ||= chars.pack("M*" * chars.size).gsub("\n", "").split("=").uniq.size
end
def valid?
- @text.present? &&
- seems_meaningful? &&
- seems_pronounceable? &&
- seems_unpretentious? &&
- seems_quiet?
+ @text.present? && seems_meaningful? && seems_pronounceable? && seems_unpretentious? &&
+ seems_quiet?
end
def seems_meaningful?
@@ -62,7 +63,7 @@ class TextSentinel
def seems_pronounceable?
# At least some non-symbol characters
# (We don't have a comprehensive list of symbols, but this will eliminate some noise)
- @text.gsub(symbols_regex, '').size > 0
+ @text.gsub(symbols_regex, "").size > 0
end
def seems_unpretentious?
@@ -70,13 +71,14 @@ class TextSentinel
# Don't allow super long words if there is a word length maximum
@opts[:max_word_length].blank? ||
- (@text.split(/\s|\/|-|\.|:/).map(&:size).max || 0) <= @opts[:max_word_length]
+ (@text.split(%r{\s|/|-|\.|:}).map(&:size).max || 0) <= @opts[:max_word_length]
end
def seems_quiet?
return true if skipped_locale.include?(SiteSetting.default_locale)
# We don't allow all upper case content
- SiteSetting.allow_uppercase_posts || @text == @text.mb_chars.downcase.to_s || @text != @text.mb_chars.upcase.to_s
+ SiteSetting.allow_uppercase_posts || @text == @text.mb_chars.downcase.to_s ||
+ @text != @text.mb_chars.upcase.to_s
end
private
@@ -86,7 +88,6 @@ class TextSentinel
end
def skipped_locale
- %w(zh_CN zh_TW ko ja).freeze
+ %w[zh_CN zh_TW ko ja].freeze
end
-
end
diff --git a/lib/theme_javascript_compiler.rb b/lib/theme_javascript_compiler.rb
index b8c9458a5ad..65d10d96fe6 100644
--- a/lib/theme_javascript_compiler.rb
+++ b/lib/theme_javascript_compiler.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
class ThemeJavascriptCompiler
-
- COLOCATED_CONNECTOR_REGEX = /\A(?<prefix>.*\/?)connectors\/(?<outlet>[^\/]+)\/(?<name>[^\/\.]+)\.(?<extension>.+)\z/
+ COLOCATED_CONNECTOR_REGEX =
+ %r{\A(?<prefix>.*/?)connectors/(?<outlet>[^/]+)/(?<name>[^/\.]+)\.(?<extension>.+)\z}
class CompileError < StandardError
end
@@ -28,13 +28,14 @@ class ThemeJavascriptCompiler
if !@compiled
@compiled = true
@output_tree.freeze
- output = if !has_content?
- { "code" => "" }
- elsif @@terser_disabled
- { "code" => raw_content }
- else
- DiscourseJsProcessor::Transpiler.new.terser(@output_tree.to_h, terser_config)
- end
+ output =
+ if !has_content?
+ { "code" => "" }
+ elsif @@terser_disabled
+ { "code" => raw_content }
+ else
+ DiscourseJsProcessor::Transpiler.new.terser(@output_tree.to_h, terser_config)
+ end
@content = output["code"]
@source_map = output["map"]
end
@@ -48,7 +49,10 @@ class ThemeJavascriptCompiler
def terser_config
# Based on https://github.com/ember-cli/ember-cli-terser/blob/28df3d90a5/index.js#L12-L26
{
- sourceMap: { includeSources: true, root: "theme-#{@theme_id}/" },
+ sourceMap: {
+ includeSources: true,
+ root: "theme-#{@theme_id}/",
+ },
compress: {
negate_iife: false,
sequences: 30,
@@ -79,7 +83,7 @@ class ThemeJavascriptCompiler
end
def prepend_settings(settings_hash)
- @output_tree.prepend ['settings.js', <<~JS]
+ @output_tree.prepend ["settings.js", <<~JS]
(function() {
if ('require' in window) {
require("discourse/lib/theme-settings-store").registerSettings(#{@theme_id}, #{settings_hash.to_json});
@@ -111,7 +115,7 @@ class ThemeJavascriptCompiler
if is_template && !is_in_templates_directory
"#{match[:prefix]}templates/connectors/#{match[:outlet]}/#{match[:name]}.#{match[:extension]}"
elsif !is_template && is_in_templates_directory
- "#{match[:prefix].chomp('templates/')}connectors/#{match[:outlet]}/#{match[:name]}.#{match[:extension]}"
+ "#{match[:prefix].chomp("templates/")}connectors/#{match[:outlet]}/#{match[:name]}.#{match[:extension]}"
else
filename
end
@@ -119,16 +123,13 @@ class ThemeJavascriptCompiler
# Handle colocated components
tree.dup.each_pair do |filename, content|
- is_component_template = filename.end_with?(".hbs") && filename.start_with?("discourse/components/", "admin/components/")
+ is_component_template =
+ filename.end_with?(".hbs") &&
+ filename.start_with?("discourse/components/", "admin/components/")
next if !is_component_template
template_contents = content
- hbs_invocation_options = {
- moduleName: filename,
- parseOptions: {
- srcName: filename
- }
- }
+ hbs_invocation_options = { moduleName: filename, parseOptions: { srcName: filename } }
hbs_invocation = "hbs(#{template_contents.to_json}, #{hbs_invocation_options.to_json})"
prefix = <<~JS
@@ -139,7 +140,8 @@ class ThemeJavascriptCompiler
js_filename = filename.sub(/\.hbs\z/, ".js")
js_contents = tree[js_filename] # May be nil for template-only component
if js_contents && !js_contents.include?("export default")
- message = "#{filename} does not contain a `default export`. Did you forget to export the component class?"
+ message =
+ "#{filename} does not contain a `default export`. Did you forget to export the component class?"
js_contents += "throw new Error(#{message.to_json});"
end
@@ -198,13 +200,14 @@ class ThemeJavascriptCompiler
end
def raw_template_name(name)
- name = name.sub(/\.(raw|hbr)$/, '')
+ name = name.sub(/\.(raw|hbr)$/, "")
name.inspect
end
def append_raw_template(name, hbs_template)
- compiled = DiscourseJsProcessor::Transpiler.new.compile_raw_template(hbs_template, theme_id: @theme_id)
- source_for_comment = hbs_template.gsub("*/", '*\/').indent(4, ' ')
+ compiled =
+ DiscourseJsProcessor::Transpiler.new.compile_raw_template(hbs_template, theme_id: @theme_id)
+ source_for_comment = hbs_template.gsub("*/", '*\/').indent(4, " ")
@output_tree << ["#{name}.js", <<~JS]
(function() {
/*
@@ -225,7 +228,7 @@ class ThemeJavascriptCompiler
def append_module(script, name, include_variables: true)
original_filename = name
- name = "discourse/theme-#{@theme_id}/#{name.gsub(/^discourse\//, '')}"
+ name = "discourse/theme-#{@theme_id}/#{name.gsub(%r{^discourse/}, "")}"
script = "#{theme_settings}#{script}" if include_variables
transpiler = DiscourseJsProcessor::Transpiler.new
diff --git a/lib/theme_modifier_helper.rb b/lib/theme_modifier_helper.rb
index 8f6be146916..7b07330d714 100644
--- a/lib/theme_modifier_helper.rb
+++ b/lib/theme_modifier_helper.rb
@@ -5,8 +5,6 @@ class ThemeModifierHelper
end
ThemeModifierSet.modifiers.keys.each do |modifier|
- define_method(modifier) do
- Theme.lookup_modifier(@theme_ids, modifier)
- end
+ define_method(modifier) { Theme.lookup_modifier(@theme_ids, modifier) }
end
end
diff --git a/lib/theme_settings_manager.rb b/lib/theme_settings_manager.rb
index c520da5650a..1c353059f64 100644
--- a/lib/theme_settings_manager.rb
+++ b/lib/theme_settings_manager.rb
@@ -53,7 +53,9 @@ class ThemeSettingsManager
def db_record
# theme.theme_settings will already be preloaded, so it is better to use
# `find` on an array, rather than make a round trip to the database
- theme.theme_settings.to_a.find { |i| i.name.to_s == @name.to_s && i.data_type.to_s == type.to_s }
+ theme.theme_settings.to_a.find do |i|
+ i.name.to_s == @name.to_s && i.data_type.to_s == type.to_s
+ end
end
def has_record?
@@ -117,7 +119,11 @@ class ThemeSettingsManager
end
def json_schema
- JSON.parse(@opts[:json_schema]) rescue false
+ begin
+ JSON.parse(@opts[:json_schema])
+ rescue StandardError
+ false
+ end
end
end
@@ -213,10 +219,8 @@ class ThemeSettingsManager
end
def default_upload_id
- theme_field = theme.theme_fields.find_by(
- name: @default,
- type_id: ThemeField.types[:theme_upload_var]
- )
+ theme_field =
+ theme.theme_fields.find_by(name: @default, type_id: ThemeField.types[:theme_upload_var])
return if theme_field.blank?
theme_field.upload_id
diff --git a/lib/theme_settings_parser.rb b/lib/theme_settings_parser.rb
index b7b14b81c2e..52f95a2a41e 100644
--- a/lib/theme_settings_parser.rb
+++ b/lib/theme_settings_parser.rb
@@ -1,7 +1,8 @@
# frozen_string_literal: true
class ThemeSettingsParser
- class InvalidYaml < StandardError; end
+ class InvalidYaml < StandardError
+ end
def initialize(setting_field)
@setting_field = setting_field
@@ -36,9 +37,7 @@ class ThemeSettingsParser
opts[:min] = raw_opts[:min].is_a?(Numeric) ? raw_opts[:min] : -Float::INFINITY
end
- if raw_opts[:list_type]
- opts[:list_type] = raw_opts[:list_type]
- end
+ opts[:list_type] = raw_opts[:list_type] if raw_opts[:list_type]
opts[:textarea] = !!raw_opts[:textarea]
opts[:json_schema] = raw_opts[:json_schema]
diff --git a/lib/theme_store/git_importer.rb b/lib/theme_store/git_importer.rb
index 3c54b84e13e..f23127a02c2 100644
--- a/lib/theme_store/git_importer.rb
+++ b/lib/theme_store/git_importer.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
-module ThemeStore; end
+module ThemeStore
+end
class ThemeStore::GitImporter
COMMAND_TIMEOUT_SECONDS = 20
@@ -21,7 +22,8 @@ class ThemeStore::GitImporter
begin
execute "git", "cat-file", "-e", version
rescue RuntimeError => e
- tracking_ref = execute "git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"
+ tracking_ref =
+ execute "git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"
remote_name = tracking_ref.split("/", 2)[0]
execute "git", "fetch", remote_name, "#{version}:#{version}"
end
@@ -29,7 +31,9 @@ class ThemeStore::GitImporter
begin
execute "git", "reset", "--hard", version
rescue RuntimeError
- raise RemoteTheme::ImportError.new(I18n.t("themes.import_error.git_ref_not_found", ref: version))
+ raise RemoteTheme::ImportError.new(
+ I18n.t("themes.import_error.git_ref_not_found", ref: version),
+ )
end
end
end
@@ -38,7 +42,12 @@ class ThemeStore::GitImporter
commit_hash, commits_behind = nil
commit_hash = execute("git", "rev-parse", "HEAD").strip
- commits_behind = execute("git", "rev-list", "#{hash}..HEAD", "--count").strip rescue -1
+ commits_behind =
+ begin
+ execute("git", "rev-list", "#{hash}..HEAD", "--count").strip
+ rescue StandardError
+ -1
+ end
[commit_hash, commits_behind]
end
@@ -79,20 +88,20 @@ class ThemeStore::GitImporter
def redirected_uri
first_clone_uri = @uri.dup
- first_clone_uri.path.gsub!(/\/\z/, "")
+ first_clone_uri.path.gsub!(%r{/\z}, "")
first_clone_uri.path += "/info/refs"
first_clone_uri.query = "service=git-upload-pack"
redirected_uri = FinalDestination.resolve(first_clone_uri.to_s, http_verb: :get)
if redirected_uri&.path.ends_with?("/info/refs")
- redirected_uri.path.gsub!(/\/info\/refs\z/, "")
+ redirected_uri.path.gsub!(%r{/info/refs\z}, "")
redirected_uri.query = nil
redirected_uri
else
@uri
end
- rescue
+ rescue StandardError
@uri
end
@@ -120,15 +129,11 @@ class ThemeStore::GitImporter
def clone_args(url, config = {})
args = ["git"]
- config.each do |key, value|
- args.concat(['-c', "#{key}=#{value}"])
- end
+ config.each { |key, value| args.concat(["-c", "#{key}=#{value}"]) }
args << "clone"
- if @branch.present?
- args.concat(['--single-branch', "-b", @branch])
- end
+ args.concat(["--single-branch", "-b", @branch]) if @branch.present?
args.concat([url, @temp_folder])
@@ -138,20 +143,19 @@ class ThemeStore::GitImporter
def clone_http!
uri = redirected_uri
- unless ["http", "https"].include?(@uri.scheme)
- raise_import_error!
- end
+ raise_import_error! unless %w[http https].include?(@uri.scheme)
addresses = FinalDestination::SSRFDetector.lookup_and_filter_ips(uri.host)
unless addresses.empty?
env = { "GIT_TERMINAL_PROMPT" => "0" }
- args = clone_args(
- uri.to_s,
- "http.followRedirects" => "false",
- "http.curloptResolve" => "#{uri.host}:#{uri.port}:#{addresses.join(',')}",
- )
+ args =
+ clone_args(
+ uri.to_s,
+ "http.followRedirects" => "false",
+ "http.curloptResolve" => "#{uri.host}:#{uri.port}:#{addresses.join(",")}",
+ )
begin
Discourse::Utils.execute_command(env, *args, timeout: COMMAND_TIMEOUT_SECONDS)
@@ -161,13 +165,14 @@ class ThemeStore::GitImporter
end
def clone_ssh!
- unless @private_key.present?
- raise_import_error!
- end
+ raise_import_error! unless @private_key.present?
with_ssh_private_key do |ssh_folder|
# Use only the specified SSH key
- env = { 'GIT_SSH_COMMAND' => "ssh -i #{ssh_folder}/id_rsa -o IdentitiesOnly=yes -o IdentityFile=#{ssh_folder}/id_rsa -o StrictHostKeyChecking=no" }
+ env = {
+ "GIT_SSH_COMMAND" =>
+ "ssh -i #{ssh_folder}/id_rsa -o IdentitiesOnly=yes -o IdentityFile=#{ssh_folder}/id_rsa -o StrictHostKeyChecking=no",
+ }
args = clone_args(@url)
begin
diff --git a/lib/theme_store/zip_exporter.rb b/lib/theme_store/zip_exporter.rb
index 87a9c8bd066..f74c4b2cd7c 100644
--- a/lib/theme_store/zip_exporter.rb
+++ b/lib/theme_store/zip_exporter.rb
@@ -1,15 +1,15 @@
# frozen_string_literal: true
-require 'compression/zip'
+require "compression/zip"
-module ThemeStore; end
+module ThemeStore
+end
class ThemeStore::ZipExporter
-
def initialize(theme)
@theme = theme
@temp_folder = "#{Pathname.new(Dir.tmpdir).realpath}/discourse_theme_#{SecureRandom.hex}"
- @export_name = @theme.name.downcase.gsub(/[^0-9a-z.\-]/, '-')
+ @export_name = @theme.name.downcase.gsub(/[^0-9a-z.\-]/, "-")
@export_name = "discourse-#{@export_name}" unless @export_name.starts_with?("discourse")
end
@@ -47,10 +47,14 @@ class ThemeStore::ZipExporter
# sanitized, but check for attempts to leave the temp directory anyway
pathname = Pathname.new(File.join(destination_folder, path))
folder_path = pathname.parent.cleanpath
- raise RuntimeError.new("Theme exporter tried to leave directory") unless folder_path.to_s.starts_with?(destination_folder)
+ unless folder_path.to_s.starts_with?(destination_folder)
+ raise RuntimeError.new("Theme exporter tried to leave directory")
+ end
pathname.parent.mkpath
path = pathname.realdirpath
- raise RuntimeError.new("Theme exporter tried to leave directory") unless path.to_s.starts_with?(destination_folder)
+ unless path.to_s.starts_with?(destination_folder)
+ raise RuntimeError.new("Theme exporter tried to leave directory")
+ end
if ThemeField.types[field.type_id] == :theme_upload_var
content = field.upload.content
@@ -63,7 +67,7 @@ class ThemeStore::ZipExporter
if !extra_scss_only
File.write(
File.join(destination_folder, "about.json"),
- JSON.pretty_generate(@theme.generate_metadata_hash)
+ JSON.pretty_generate(@theme.generate_metadata_hash),
)
end
diff --git a/lib/theme_store/zip_importer.rb b/lib/theme_store/zip_importer.rb
index f8bed2349bf..aed20bb83e2 100644
--- a/lib/theme_store/zip_importer.rb
+++ b/lib/theme_store/zip_importer.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-require 'compression/engine'
+require "compression/engine"
-module ThemeStore; end
+module ThemeStore
+end
class ThemeStore::ZipImporter
-
attr_reader :url
def initialize(filename, original_filename)
@@ -18,10 +18,12 @@ class ThemeStore::ZipImporter
FileUtils.mkdir(@temp_folder)
available_size = SiteSetting.decompressed_theme_max_file_size_mb
- Compression::Engine.engine_for(@original_filename).tap do |engine|
- engine.decompress(@temp_folder, @filename, available_size)
- strip_root_directory
- end
+ Compression::Engine
+ .engine_for(@original_filename)
+ .tap do |engine|
+ engine.decompress(@temp_folder, @filename, available_size)
+ strip_root_directory
+ end
rescue RuntimeError
raise RemoteTheme::ImportError, I18n.t("themes.import_error.unpack_failed")
rescue Compression::Zip::ExtractFailed
@@ -66,5 +68,4 @@ class ThemeStore::ZipImporter
return nil unless fullpath
File.read(fullpath)
end
-
end
diff --git a/lib/theme_translation_manager.rb b/lib/theme_translation_manager.rb
index 2fd7a9644cc..e9b354ddd03 100644
--- a/lib/theme_translation_manager.rb
+++ b/lib/theme_translation_manager.rb
@@ -6,14 +6,21 @@ class ThemeTranslationManager
def self.list_from_hash(locale:, hash:, theme:, parent_keys: [])
list = []
- hash.map do |key, value|
- this_key_array = parent_keys + [key]
- if value.is_a?(Hash)
- self.list_from_hash(locale: locale, hash: value, theme: theme, parent_keys: this_key_array)
- else
- self.new(locale: locale, theme: theme, key: this_key_array.join("."), default: value)
+ hash
+ .map do |key, value|
+ this_key_array = parent_keys + [key]
+ if value.is_a?(Hash)
+ self.list_from_hash(
+ locale: locale,
+ hash: value,
+ theme: theme,
+ parent_keys: this_key_array,
+ )
+ else
+ self.new(locale: locale, theme: theme, key: this_key_array.join("."), default: value)
+ end
end
- end.flatten
+ .flatten
end
def initialize(locale:, key:, default:, theme:)
@@ -54,6 +61,12 @@ class ThemeTranslationManager
end
def create_record!(value)
- record = ThemeTranslationOverride.create!(locale: @locale, translation_key: @key, theme: @theme, value: value)
+ record =
+ ThemeTranslationOverride.create!(
+ locale: @locale,
+ translation_key: @key,
+ theme: @theme,
+ value: value,
+ )
end
end
diff --git a/lib/theme_translation_parser.rb b/lib/theme_translation_parser.rb
index 76941fbca5e..2f05e8d8bdb 100644
--- a/lib/theme_translation_parser.rb
+++ b/lib/theme_translation_parser.rb
@@ -2,7 +2,8 @@
class ThemeTranslationParser
INTERNAL_KEYS = [:theme_metadata]
- class InvalidYaml < StandardError; end
+ class InvalidYaml < StandardError
+ end
def initialize(setting_field, internal: false)
@setting_field = setting_field
@@ -10,7 +11,9 @@ class ThemeTranslationParser
end
def self.check_contains_hashes(hash)
- hash.all? { |_key, value| value.is_a?(String) || (value.is_a?(Hash) && self.check_contains_hashes(value)) }
+ hash.all? do |_key, value|
+ value.is_a?(String) || (value.is_a?(Hash) && self.check_contains_hashes(value))
+ end
end
def load
@@ -23,13 +26,17 @@ class ThemeTranslationParser
end
raise InvalidYaml.new(I18n.t("themes.locale_errors.invalid_yaml")) if !parsed.is_a?(Hash)
- raise InvalidYaml.new(I18n.t("themes.locale_errors.top_level_locale")) if parsed.keys.length != 1 || parsed.keys.first != @setting_field.name
+ if parsed.keys.length != 1 || parsed.keys.first != @setting_field.name
+ raise InvalidYaml.new(I18n.t("themes.locale_errors.top_level_locale"))
+ end
key = @setting_field.name.to_sym
parsed.deep_symbolize_keys!
parsed[key] ||= {}
- raise InvalidYaml.new(I18n.t("themes.locale_errors.invalid_yaml")) if !ThemeTranslationParser.check_contains_hashes(parsed)
+ if !ThemeTranslationParser.check_contains_hashes(parsed)
+ raise InvalidYaml.new(I18n.t("themes.locale_errors.invalid_yaml"))
+ end
parsed[key].slice!(*INTERNAL_KEYS) if @internal
parsed[key].except!(*INTERNAL_KEYS) if !@internal
diff --git a/lib/timeline_lookup.rb b/lib/timeline_lookup.rb
index f477153f947..4dc6b8879f5 100644
--- a/lib/timeline_lookup.rb
+++ b/lib/timeline_lookup.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
module TimelineLookup
-
# Given an array of tuples containing (id, days_ago), return at most `max_values` worth of a
# lookup table to help the front end timeline display dates associated with posts
def self.build(tuples, max_values = 300)
@@ -23,10 +22,8 @@ module TimelineLookup
result << [idx + 1, days_ago]
last_days_ago = days_ago
end
-
end
result
end
-
end
diff --git a/lib/tiny_japanese_segmenter.rb b/lib/tiny_japanese_segmenter.rb
index 5da3175a36f..23f99c61b04 100644
--- a/lib/tiny_japanese_segmenter.rb
+++ b/lib/tiny_japanese_segmenter.rb
@@ -4,60 +4,1382 @@
# This is esstentially a trained machine learning model used to segment words in Japanese.
# Discourse core uses it for "best effort" segmentation of Japanese text for search.
class TinyJapaneseSegmenter
- CHARTYPE = {
- "[一二三四五六七八九十百千万億兆]" => "M",
- "[一-龠々〆ヵヶ]" => "H",
- "[ぁ-ん]" => "I",
- "[ァ-ヴーア-ン゙ー]" => "K",
- "[a-zA-Za-zA-Z]" => "A",
- "[0-90-9]" => "N"
- }.map do |pattern, value|
- [Regexp.compile(pattern), value]
- end
+ CHARTYPE =
+ {
+ "[一二三四五六七八九十百千万億兆]" => "M",
+ "[一-龠々〆ヵヶ]" => "H",
+ "[ぁ-ん]" => "I",
+ "[ァ-ヴーア-ン゙ー]" => "K",
+ "[a-zA-Za-zA-Z]" => "A",
+ "[0-90-9]" => "N",
+ }.map { |pattern, value| [Regexp.compile(pattern), value] }
BIAS = -322
BC1 = { "HH" => 6, "II" => 2461, "KH" => 406, "OH" => -1378 }
- BC2 = { "AA" => -3267, "AI" => 2744, "AN" => -878, "HH" => -4070, "HM" => -1711, "HN" => 4012, "HO" => 3761, "IA" => 1327, "IH" => -1184, "II" => -1332, "IK" => 1721, "IO" => 5492, "KI" => 3831, "KK" => -8741, "MH" => -3132, "MK" => 3334, "OO" => -2920 }
- BC3 = { "HH" => 996, "HI" => 626, "HK" => -721, "HN" => -1307, "HO" => -836, "IH" => -301, "KK" => 2762, "MK" => 1079, "MM" => 4034, "OA" => -1652, "OH" => 266 }
+ BC2 = {
+ "AA" => -3267,
+ "AI" => 2744,
+ "AN" => -878,
+ "HH" => -4070,
+ "HM" => -1711,
+ "HN" => 4012,
+ "HO" => 3761,
+ "IA" => 1327,
+ "IH" => -1184,
+ "II" => -1332,
+ "IK" => 1721,
+ "IO" => 5492,
+ "KI" => 3831,
+ "KK" => -8741,
+ "MH" => -3132,
+ "MK" => 3334,
+ "OO" => -2920,
+ }
+ BC3 = {
+ "HH" => 996,
+ "HI" => 626,
+ "HK" => -721,
+ "HN" => -1307,
+ "HO" => -836,
+ "IH" => -301,
+ "KK" => 2762,
+ "MK" => 1079,
+ "MM" => 4034,
+ "OA" => -1652,
+ "OH" => 266,
+ }
BP1 = { "BB" => 295, "OB" => 304, "OO" => -125, "UB" => 352 }
BP2 = { "BO" => 60, "OO" => -1762 }
- BQ1 = { "BHH" => 1150, "BHM" => 1521, "BII" => -1158, "BIM" => 886, "BMH" => 1208, "BNH" => 449, "BOH" => -91, "BOO" => -2597, "OHI" => 451, "OIH" => -296, "OKA" => 1851, "OKH" => -1020, "OKK" => 904, "OOO" => 2965 }
- BQ2 = { "BHH" => 118, "BHI" => -1159, "BHM" => 466, "BIH" => -919, "BKK" => -1720, "BKO" => 864, "OHH" => -1139, "OHM" => -181, "OIH" => 153, "UHI" => -1146 }
- BQ3 = { "BHH" => -792, "BHI" => 2664, "BII" => -299, "BKI" => 419, "BMH" => 937, "BMM" => 8335, "BNN" => 998, "BOH" => 775, "OHH" => 2174, "OHM" => 439, "OII" => 280, "OKH" => 1798, "OKI" => -793, "OKO" => -2242, "OMH" => -2402, "OOO" => 11699 }
- BQ4 = { "BHH" => -3895, "BIH" => 3761, "BII" => -4654, "BIK" => 1348, "BKK" => -1806, "BMI" => -3385, "BOO" => -12396, "OAH" => 926, "OHH" => 266, "OHK" => -2036, "ONN" => -973 }
- BW1 = { ",と" => 660, ",同" => 727, "B1あ" => 1404, "B1同" => 542, "、と" => 660, "、同" => 727, "」と" => 1682, "あっ" => 1505, "いう" => 1743, "いっ" => -2055, "いる" => 672, "うし" => -4817, "うん" => 665, "から" => 3472, "がら" => 600, "こう" => -790, "こと" => 2083, "こん" => -1262, "さら" => -4143, "さん" => 4573, "した" => 2641, "して" => 1104, "すで" => -3399, "そこ" => 1977, "それ" => -871, "たち" => 1122, "ため" => 601, "った" => 3463, "つい" => -802, "てい" => 805, "てき" => 1249, "でき" => 1127, "です" => 3445, "では" => 844, "とい" => -4915, "とみ" => 1922, "どこ" => 3887, "ない" => 5713, "なっ" => 3015, "など" => 7379, "なん" => -1113, "にし" => 2468, "には" => 1498, "にも" => 1671, "に対" => -912, "の一" => -501, "の中" => 741, "ませ" => 2448, "まで" => 1711, "まま" => 2600, "まる" => -2155, "やむ" => -1947, "よっ" => -2565, "れた" => 2369, "れで" => -913, "をし" => 1860, "を見" => 731, "亡く" => -1886, "京都" => 2558, "取り" => -2784, "大き" => -2604, "大阪" => 1497, "平方" => -2314, "引き" => -1336, "日本" => -195, "本当" => -2423, "毎日" => -2113, "目指" => -724, "B1あ" => 1404, "B1同" => 542, "」と" => 1682 }
- BW2 = { ".." => -11822, "11" => -669, "――" => -5730, "−−" => -13175, "いう" => -1609, "うか" => 2490, "かし" => -1350, "かも" => -602, "から" => -7194, "かれ" => 4612, "がい" => 853, "がら" => -3198, "きた" => 1941, "くな" => -1597, "こと" => -8392, "この" => -4193, "させ" => 4533, "され" => 13168, "さん" => -3977, "しい" => -1819, "しか" => -545, "した" => 5078, "して" => 972, "しな" => 939, "その" => -3744, "たい" => -1253, "たた" => -662, "ただ" => -3857, "たち" => -786, "たと" => 1224, "たは" => -939, "った" => 4589, "って" => 1647, "っと" => -2094, "てい" => 6144, "てき" => 3640, "てく" => 2551, "ては" => -3110, "ても" => -3065, "でい" => 2666, "でき" => -1528, "でし" => -3828, "です" => -4761, "でも" => -4203, "とい" => 1890, "とこ" => -1746, "とと" => -2279, "との" => 720, "とみ" => 5168, "とも" => -3941, "ない" => -2488, "なが" => -1313, "など" => -6509, "なの" => 2614, "なん" => 3099, "にお" => -1615, "にし" => 2748, "にな" => 2454, "によ" => -7236, "に対" => -14943, "に従" => -4688, "に関" => -11388, "のか" => 2093, "ので" => -7059, "のに" => -6041, "のの" => -6125, "はい" => 1073, "はが" => -1033, "はず" => -2532, "ばれ" => 1813, "まし" => -1316, "まで" => -6621, "まれ" => 5409, "めて" => -3153, "もい" => 2230, "もの" => -10713, "らか" => -944, "らし" => -1611, "らに" => -1897, "りし" => 651, "りま" => 1620, "れた" => 4270, "れて" => 849, "れば" => 4114, "ろう" => 6067, "われ" => 7901, "を通" => -11877, "んだ" => 728, "んな" => -4115, "一人" => 602, "一方" => -1375, "一日" => 970, "一部" => -1051, "上が" => -4479, "会社" => -1116, "出て" => 2163, "分の" => -7758, "同党" => 970, "同日" => -913, "大阪" => -2471, "委員" => -1250, "少な" => -1050, "年度" => -8669, "年間" => -1626, "府県" => -2363, "手権" => -1982, "新聞" => -4066, "日新" => -722, "日本" => -7068, "日米" => 3372, "曜日" => -601, "朝鮮" => -2355, "本人" => -2697, "東京" => -1543, "然と" => -1384, "社会" => -1276, "立て" => -990, "第に" => -1612, "米国" => -4268, "11" => -669 }
- BW3 = { "あた" => -2194, "あり" => 719, "ある" => 3846, "い." => -1185, "い。" => -1185, "いい" => 5308, "いえ" => 2079, "いく" => 3029, "いた" => 2056, "いっ" => 1883, "いる" => 5600, "いわ" => 1527, "うち" => 1117, "うと" => 4798, "えと" => 1454, "か." => 2857, "か。" => 2857, "かけ" => -743, "かっ" => -4098, "かに" => -669, "から" => 6520, "かり" => -2670, "が," => 1816, "が、" => 1816, "がき" => -4855, "がけ" => -1127, "がっ" => -913, "がら" => -4977, "がり" => -2064, "きた" => 1645, "けど" => 1374, "こと" => 7397, "この" => 1542, "ころ" => -2757, "さい" => -714, "さを" => 976, "し," => 1557, "し、" => 1557, "しい" => -3714, "した" => 3562, "して" => 1449, "しな" => 2608, "しま" => 1200, "す." => -1310, "す。" => -1310, "する" => 6521, "ず," => 3426, "ず、" => 3426, "ずに" => 841, "そう" => 428, "た." => 8875, "た。" => 8875, "たい" => -594, "たの" => 812, "たり" => -1183, "たる" => -853, "だ." => 4098, "だ。" => 4098, "だっ" => 1004, "った" => -4748, "って" => 300, "てい" => 6240, "てお" => 855, "ても" => 302, "です" => 1437, "でに" => -1482, "では" => 2295, "とう" => -1387, "とし" => 2266, "との" => 541, "とも" => -3543, "どう" => 4664, "ない" => 1796, "なく" => -903, "など" => 2135, "に," => -1021, "に、" => -1021, "にし" => 1771, "にな" => 1906, "には" => 2644, "の," => -724, "の、" => -724, "の子" => -1000, "は," => 1337, "は、" => 1337, "べき" => 2181, "まし" => 1113, "ます" => 6943, "まっ" => -1549, "まで" => 6154, "まれ" => -793, "らし" => 1479, "られ" => 6820, "るる" => 3818, "れ," => 854, "れ、" => 854, "れた" => 1850, "れて" => 1375, "れば" => -3246, "れる" => 1091, "われ" => -605, "んだ" => 606, "んで" => 798, "カ月" => 990, "会議" => 860, "入り" => 1232, "大会" => 2217, "始め" => 1681, "市" => 965, "新聞" => -5055, "日," => 974, "日、" => 974, "社会" => 2024, "カ月" => 990 }
- TC1 = { "AAA" => 1093, "HHH" => 1029, "HHM" => 580, "HII" => 998, "HOH" => -390, "HOM" => -331, "IHI" => 1169, "IOH" => -142, "IOI" => -1015, "IOM" => 467, "MMH" => 187, "OOI" => -1832 }
- TC2 = { "HHO" => 2088, "HII" => -1023, "HMM" => -1154, "IHI" => -1965, "KKH" => 703, "OII" => -2649 }
- TC3 = { "AAA" => -294, "HHH" => 346, "HHI" => -341, "HII" => -1088, "HIK" => 731, "HOH" => -1486, "IHH" => 128, "IHI" => -3041, "IHO" => -1935, "IIH" => -825, "IIM" => -1035, "IOI" => -542, "KHH" => -1216, "KKA" => 491, "KKH" => -1217, "KOK" => -1009, "MHH" => -2694, "MHM" => -457, "MHO" => 123, "MMH" => -471, "NNH" => -1689, "NNO" => 662, "OHO" => -3393 }
- TC4 = { "HHH" => -203, "HHI" => 1344, "HHK" => 365, "HHM" => -122, "HHN" => 182, "HHO" => 669, "HIH" => 804, "HII" => 679, "HOH" => 446, "IHH" => 695, "IHO" => -2324, "IIH" => 321, "III" => 1497, "IIO" => 656, "IOO" => 54, "KAK" => 4845, "KKA" => 3386, "KKK" => 3065, "MHH" => -405, "MHI" => 201, "MMH" => -241, "MMM" => 661, "MOM" => 841 }
- TQ1 = { "BHHH" => -227, "BHHI" => 316, "BHIH" => -132, "BIHH" => 60, "BIII" => 1595, "BNHH" => -744, "BOHH" => 225, "BOOO" => -908, "OAKK" => 482, "OHHH" => 281, "OHIH" => 249, "OIHI" => 200, "OIIH" => -68 }
+ BQ1 = {
+ "BHH" => 1150,
+ "BHM" => 1521,
+ "BII" => -1158,
+ "BIM" => 886,
+ "BMH" => 1208,
+ "BNH" => 449,
+ "BOH" => -91,
+ "BOO" => -2597,
+ "OHI" => 451,
+ "OIH" => -296,
+ "OKA" => 1851,
+ "OKH" => -1020,
+ "OKK" => 904,
+ "OOO" => 2965,
+ }
+ BQ2 = {
+ "BHH" => 118,
+ "BHI" => -1159,
+ "BHM" => 466,
+ "BIH" => -919,
+ "BKK" => -1720,
+ "BKO" => 864,
+ "OHH" => -1139,
+ "OHM" => -181,
+ "OIH" => 153,
+ "UHI" => -1146,
+ }
+ BQ3 = {
+ "BHH" => -792,
+ "BHI" => 2664,
+ "BII" => -299,
+ "BKI" => 419,
+ "BMH" => 937,
+ "BMM" => 8335,
+ "BNN" => 998,
+ "BOH" => 775,
+ "OHH" => 2174,
+ "OHM" => 439,
+ "OII" => 280,
+ "OKH" => 1798,
+ "OKI" => -793,
+ "OKO" => -2242,
+ "OMH" => -2402,
+ "OOO" => 11_699,
+ }
+ BQ4 = {
+ "BHH" => -3895,
+ "BIH" => 3761,
+ "BII" => -4654,
+ "BIK" => 1348,
+ "BKK" => -1806,
+ "BMI" => -3385,
+ "BOO" => -12_396,
+ "OAH" => 926,
+ "OHH" => 266,
+ "OHK" => -2036,
+ "ONN" => -973,
+ }
+ BW1 = {
+ ",と" => 660,
+ ",同" => 727,
+ "B1あ" => 1404,
+ "B1同" => 542,
+ "、と" => 660,
+ "、同" => 727,
+ "」と" => 1682,
+ "あっ" => 1505,
+ "いう" => 1743,
+ "いっ" => -2055,
+ "いる" => 672,
+ "うし" => -4817,
+ "うん" => 665,
+ "から" => 3472,
+ "がら" => 600,
+ "こう" => -790,
+ "こと" => 2083,
+ "こん" => -1262,
+ "さら" => -4143,
+ "さん" => 4573,
+ "した" => 2641,
+ "して" => 1104,
+ "すで" => -3399,
+ "そこ" => 1977,
+ "それ" => -871,
+ "たち" => 1122,
+ "ため" => 601,
+ "った" => 3463,
+ "つい" => -802,
+ "てい" => 805,
+ "てき" => 1249,
+ "でき" => 1127,
+ "です" => 3445,
+ "では" => 844,
+ "とい" => -4915,
+ "とみ" => 1922,
+ "どこ" => 3887,
+ "ない" => 5713,
+ "なっ" => 3015,
+ "など" => 7379,
+ "なん" => -1113,
+ "にし" => 2468,
+ "には" => 1498,
+ "にも" => 1671,
+ "に対" => -912,
+ "の一" => -501,
+ "の中" => 741,
+ "ませ" => 2448,
+ "まで" => 1711,
+ "まま" => 2600,
+ "まる" => -2155,
+ "やむ" => -1947,
+ "よっ" => -2565,
+ "れた" => 2369,
+ "れで" => -913,
+ "をし" => 1860,
+ "を見" => 731,
+ "亡く" => -1886,
+ "京都" => 2558,
+ "取り" => -2784,
+ "大き" => -2604,
+ "大阪" => 1497,
+ "平方" => -2314,
+ "引き" => -1336,
+ "日本" => -195,
+ "本当" => -2423,
+ "毎日" => -2113,
+ "目指" => -724,
+ "B1あ" => 1404,
+ "B1同" => 542,
+ "」と" => 1682,
+ }
+ BW2 = {
+ ".." => -11_822,
+ "11" => -669,
+ "――" => -5730,
+ "−−" => -13_175,
+ "いう" => -1609,
+ "うか" => 2490,
+ "かし" => -1350,
+ "かも" => -602,
+ "から" => -7194,
+ "かれ" => 4612,
+ "がい" => 853,
+ "がら" => -3198,
+ "きた" => 1941,
+ "くな" => -1597,
+ "こと" => -8392,
+ "この" => -4193,
+ "させ" => 4533,
+ "され" => 13_168,
+ "さん" => -3977,
+ "しい" => -1819,
+ "しか" => -545,
+ "した" => 5078,
+ "して" => 972,
+ "しな" => 939,
+ "その" => -3744,
+ "たい" => -1253,
+ "たた" => -662,
+ "ただ" => -3857,
+ "たち" => -786,
+ "たと" => 1224,
+ "たは" => -939,
+ "った" => 4589,
+ "って" => 1647,
+ "っと" => -2094,
+ "てい" => 6144,
+ "てき" => 3640,
+ "てく" => 2551,
+ "ては" => -3110,
+ "ても" => -3065,
+ "でい" => 2666,
+ "でき" => -1528,
+ "でし" => -3828,
+ "です" => -4761,
+ "でも" => -4203,
+ "とい" => 1890,
+ "とこ" => -1746,
+ "とと" => -2279,
+ "との" => 720,
+ "とみ" => 5168,
+ "とも" => -3941,
+ "ない" => -2488,
+ "なが" => -1313,
+ "など" => -6509,
+ "なの" => 2614,
+ "なん" => 3099,
+ "にお" => -1615,
+ "にし" => 2748,
+ "にな" => 2454,
+ "によ" => -7236,
+ "に対" => -14_943,
+ "に従" => -4688,
+ "に関" => -11_388,
+ "のか" => 2093,
+ "ので" => -7059,
+ "のに" => -6041,
+ "のの" => -6125,
+ "はい" => 1073,
+ "はが" => -1033,
+ "はず" => -2532,
+ "ばれ" => 1813,
+ "まし" => -1316,
+ "まで" => -6621,
+ "まれ" => 5409,
+ "めて" => -3153,
+ "もい" => 2230,
+ "もの" => -10_713,
+ "らか" => -944,
+ "らし" => -1611,
+ "らに" => -1897,
+ "りし" => 651,
+ "りま" => 1620,
+ "れた" => 4270,
+ "れて" => 849,
+ "れば" => 4114,
+ "ろう" => 6067,
+ "われ" => 7901,
+ "を通" => -11_877,
+ "んだ" => 728,
+ "んな" => -4115,
+ "一人" => 602,
+ "一方" => -1375,
+ "一日" => 970,
+ "一部" => -1051,
+ "上が" => -4479,
+ "会社" => -1116,
+ "出て" => 2163,
+ "分の" => -7758,
+ "同党" => 970,
+ "同日" => -913,
+ "大阪" => -2471,
+ "委員" => -1250,
+ "少な" => -1050,
+ "年度" => -8669,
+ "年間" => -1626,
+ "府県" => -2363,
+ "手権" => -1982,
+ "新聞" => -4066,
+ "日新" => -722,
+ "日本" => -7068,
+ "日米" => 3372,
+ "曜日" => -601,
+ "朝鮮" => -2355,
+ "本人" => -2697,
+ "東京" => -1543,
+ "然と" => -1384,
+ "社会" => -1276,
+ "立て" => -990,
+ "第に" => -1612,
+ "米国" => -4268,
+ "11" => -669,
+ }
+ BW3 = {
+ "あた" => -2194,
+ "あり" => 719,
+ "ある" => 3846,
+ "い." => -1185,
+ "い。" => -1185,
+ "いい" => 5308,
+ "いえ" => 2079,
+ "いく" => 3029,
+ "いた" => 2056,
+ "いっ" => 1883,
+ "いる" => 5600,
+ "いわ" => 1527,
+ "うち" => 1117,
+ "うと" => 4798,
+ "えと" => 1454,
+ "か." => 2857,
+ "か。" => 2857,
+ "かけ" => -743,
+ "かっ" => -4098,
+ "かに" => -669,
+ "から" => 6520,
+ "かり" => -2670,
+ "が," => 1816,
+ "が、" => 1816,
+ "がき" => -4855,
+ "がけ" => -1127,
+ "がっ" => -913,
+ "がら" => -4977,
+ "がり" => -2064,
+ "きた" => 1645,
+ "けど" => 1374,
+ "こと" => 7397,
+ "この" => 1542,
+ "ころ" => -2757,
+ "さい" => -714,
+ "さを" => 976,
+ "し," => 1557,
+ "し、" => 1557,
+ "しい" => -3714,
+ "した" => 3562,
+ "して" => 1449,
+ "しな" => 2608,
+ "しま" => 1200,
+ "す." => -1310,
+ "す。" => -1310,
+ "する" => 6521,
+ "ず," => 3426,
+ "ず、" => 3426,
+ "ずに" => 841,
+ "そう" => 428,
+ "た." => 8875,
+ "た。" => 8875,
+ "たい" => -594,
+ "たの" => 812,
+ "たり" => -1183,
+ "たる" => -853,
+ "だ." => 4098,
+ "だ。" => 4098,
+ "だっ" => 1004,
+ "った" => -4748,
+ "って" => 300,
+ "てい" => 6240,
+ "てお" => 855,
+ "ても" => 302,
+ "です" => 1437,
+ "でに" => -1482,
+ "では" => 2295,
+ "とう" => -1387,
+ "とし" => 2266,
+ "との" => 541,
+ "とも" => -3543,
+ "どう" => 4664,
+ "ない" => 1796,
+ "なく" => -903,
+ "など" => 2135,
+ "に," => -1021,
+ "に、" => -1021,
+ "にし" => 1771,
+ "にな" => 1906,
+ "には" => 2644,
+ "の," => -724,
+ "の、" => -724,
+ "の子" => -1000,
+ "は," => 1337,
+ "は、" => 1337,
+ "べき" => 2181,
+ "まし" => 1113,
+ "ます" => 6943,
+ "まっ" => -1549,
+ "まで" => 6154,
+ "まれ" => -793,
+ "らし" => 1479,
+ "られ" => 6820,
+ "るる" => 3818,
+ "れ," => 854,
+ "れ、" => 854,
+ "れた" => 1850,
+ "れて" => 1375,
+ "れば" => -3246,
+ "れる" => 1091,
+ "われ" => -605,
+ "んだ" => 606,
+ "んで" => 798,
+ "カ月" => 990,
+ "会議" => 860,
+ "入り" => 1232,
+ "大会" => 2217,
+ "始め" => 1681,
+ "市" => 965,
+ "新聞" => -5055,
+ "日," => 974,
+ "日、" => 974,
+ "社会" => 2024,
+ "カ月" => 990,
+ }
+ TC1 = {
+ "AAA" => 1093,
+ "HHH" => 1029,
+ "HHM" => 580,
+ "HII" => 998,
+ "HOH" => -390,
+ "HOM" => -331,
+ "IHI" => 1169,
+ "IOH" => -142,
+ "IOI" => -1015,
+ "IOM" => 467,
+ "MMH" => 187,
+ "OOI" => -1832,
+ }
+ TC2 = {
+ "HHO" => 2088,
+ "HII" => -1023,
+ "HMM" => -1154,
+ "IHI" => -1965,
+ "KKH" => 703,
+ "OII" => -2649,
+ }
+ TC3 = {
+ "AAA" => -294,
+ "HHH" => 346,
+ "HHI" => -341,
+ "HII" => -1088,
+ "HIK" => 731,
+ "HOH" => -1486,
+ "IHH" => 128,
+ "IHI" => -3041,
+ "IHO" => -1935,
+ "IIH" => -825,
+ "IIM" => -1035,
+ "IOI" => -542,
+ "KHH" => -1216,
+ "KKA" => 491,
+ "KKH" => -1217,
+ "KOK" => -1009,
+ "MHH" => -2694,
+ "MHM" => -457,
+ "MHO" => 123,
+ "MMH" => -471,
+ "NNH" => -1689,
+ "NNO" => 662,
+ "OHO" => -3393,
+ }
+ TC4 = {
+ "HHH" => -203,
+ "HHI" => 1344,
+ "HHK" => 365,
+ "HHM" => -122,
+ "HHN" => 182,
+ "HHO" => 669,
+ "HIH" => 804,
+ "HII" => 679,
+ "HOH" => 446,
+ "IHH" => 695,
+ "IHO" => -2324,
+ "IIH" => 321,
+ "III" => 1497,
+ "IIO" => 656,
+ "IOO" => 54,
+ "KAK" => 4845,
+ "KKA" => 3386,
+ "KKK" => 3065,
+ "MHH" => -405,
+ "MHI" => 201,
+ "MMH" => -241,
+ "MMM" => 661,
+ "MOM" => 841,
+ }
+ TQ1 = {
+ "BHHH" => -227,
+ "BHHI" => 316,
+ "BHIH" => -132,
+ "BIHH" => 60,
+ "BIII" => 1595,
+ "BNHH" => -744,
+ "BOHH" => 225,
+ "BOOO" => -908,
+ "OAKK" => 482,
+ "OHHH" => 281,
+ "OHIH" => 249,
+ "OIHI" => 200,
+ "OIIH" => -68,
+ }
TQ2 = { "BIHH" => -1401, "BIII" => -1033, "BKAK" => -543, "BOOO" => -5591 }
- TQ3 = { "BHHH" => 478, "BHHM" => -1073, "BHIH" => 222, "BHII" => -504, "BIIH" => -116, "BIII" => -105, "BMHI" => -863, "BMHM" => -464, "BOMH" => 620, "OHHH" => 346, "OHHI" => 1729, "OHII" => 997, "OHMH" => 481, "OIHH" => 623, "OIIH" => 1344, "OKAK" => 2792, "OKHH" => 587, "OKKA" => 679, "OOHH" => 110, "OOII" => -685 }
- TQ4 = { "BHHH" => -721, "BHHM" => -3604, "BHII" => -966, "BIIH" => -607, "BIII" => -2181, "OAAA" => -2763, "OAKK" => 180, "OHHH" => -294, "OHHI" => 2446, "OHHO" => 480, "OHIH" => -1573, "OIHH" => 1935, "OIHI" => -493, "OIIH" => 626, "OIII" => -4007, "OKAK" => -8156 }
+ TQ3 = {
+ "BHHH" => 478,
+ "BHHM" => -1073,
+ "BHIH" => 222,
+ "BHII" => -504,
+ "BIIH" => -116,
+ "BIII" => -105,
+ "BMHI" => -863,
+ "BMHM" => -464,
+ "BOMH" => 620,
+ "OHHH" => 346,
+ "OHHI" => 1729,
+ "OHII" => 997,
+ "OHMH" => 481,
+ "OIHH" => 623,
+ "OIIH" => 1344,
+ "OKAK" => 2792,
+ "OKHH" => 587,
+ "OKKA" => 679,
+ "OOHH" => 110,
+ "OOII" => -685,
+ }
+ TQ4 = {
+ "BHHH" => -721,
+ "BHHM" => -3604,
+ "BHII" => -966,
+ "BIIH" => -607,
+ "BIII" => -2181,
+ "OAAA" => -2763,
+ "OAKK" => 180,
+ "OHHH" => -294,
+ "OHHI" => 2446,
+ "OHHO" => 480,
+ "OHIH" => -1573,
+ "OIHH" => 1935,
+ "OIHI" => -493,
+ "OIIH" => 626,
+ "OIII" => -4007,
+ "OKAK" => -8156,
+ }
TW1 = { "につい" => -4681, "東京都" => 2026 }
- TW2 = { "ある程" => -2049, "いった" => -1256, "ころが" => -2434, "しょう" => 3873, "その後" => -4430, "だって" => -1049, "ていた" => 1833, "として" => -4657, "ともに" => -4517, "もので" => 1882, "一気に" => -792, "初めて" => -1512, "同時に" => -8097, "大きな" => -1255, "対して" => -2721, "社会党" => -3216 }
- TW3 = { "いただ" => -1734, "してい" => 1314, "として" => -4314, "につい" => -5483, "にとっ" => -5989, "に当た" => -6247, "ので," => -727, "ので、" => -727, "のもの" => -600, "れから" => -3752, "十二月" => -2287 }
- TW4 = { "いう." => 8576, "いう。" => 8576, "からな" => -2348, "してい" => 2958, "たが," => 1516, "たが、" => 1516, "ている" => 1538, "という" => 1349, "ました" => 5543, "ません" => 1097, "ようと" => -4258, "よると" => 5865 }
+ TW2 = {
+ "ある程" => -2049,
+ "いった" => -1256,
+ "ころが" => -2434,
+ "しょう" => 3873,
+ "その後" => -4430,
+ "だって" => -1049,
+ "ていた" => 1833,
+ "として" => -4657,
+ "ともに" => -4517,
+ "もので" => 1882,
+ "一気に" => -792,
+ "初めて" => -1512,
+ "同時に" => -8097,
+ "大きな" => -1255,
+ "対して" => -2721,
+ "社会党" => -3216,
+ }
+ TW3 = {
+ "いただ" => -1734,
+ "してい" => 1314,
+ "として" => -4314,
+ "につい" => -5483,
+ "にとっ" => -5989,
+ "に当た" => -6247,
+ "ので," => -727,
+ "ので、" => -727,
+ "のもの" => -600,
+ "れから" => -3752,
+ "十二月" => -2287,
+ }
+ TW4 = {
+ "いう." => 8576,
+ "いう。" => 8576,
+ "からな" => -2348,
+ "してい" => 2958,
+ "たが," => 1516,
+ "たが、" => 1516,
+ "ている" => 1538,
+ "という" => 1349,
+ "ました" => 5543,
+ "ません" => 1097,
+ "ようと" => -4258,
+ "よると" => 5865,
+ }
UC1 = { "A" => 484, "K" => 93, "M" => 645, "O" => -505 }
UC2 = { "A" => 819, "H" => 1059, "I" => 409, "M" => 3987, "N" => 5775, "O" => 646 }
UC3 = { "A" => -1370, "I" => 2311 }
- UC4 = { "A" => -2643, "H" => 1809, "I" => -1032, "K" => -3450, "M" => 3565, "N" => 3876, "O" => 6646 }
+ UC4 = {
+ "A" => -2643,
+ "H" => 1809,
+ "I" => -1032,
+ "K" => -3450,
+ "M" => 3565,
+ "N" => 3876,
+ "O" => 6646,
+ }
UC5 = { "H" => 313, "I" => -1238, "K" => -799, "M" => 539, "O" => -831 }
UC6 = { "H" => -506, "I" => -253, "K" => 87, "M" => 247, "O" => -387 }
UP1 = { "O" => -214 }
UP2 = { "B" => 69, "O" => 935 }
UP3 = { "B" => 189 }
- UQ1 = { "BH" => 21, "BI" => -12, "BK" => -99, "BN" => 142, "BO" => -56, "OH" => -95, "OI" => 477, "OK" => 410, "OO" => -2422 }
+ UQ1 = {
+ "BH" => 21,
+ "BI" => -12,
+ "BK" => -99,
+ "BN" => 142,
+ "BO" => -56,
+ "OH" => -95,
+ "OI" => 477,
+ "OK" => 410,
+ "OO" => -2422,
+ }
UQ2 = { "BH" => 216, "BI" => 113, "OK" => 1759 }
- UQ3 = { "BA" => -479, "BH" => 42, "BI" => 1913, "BK" => -7198, "BM" => 3160, "BN" => 6427, "BO" => 14761, "OI" => -827, "ON" => -3212 }
- UW1 = { "," => 156, "、" => 156, "「" => -463, "あ" => -941, "う" => -127, "が" => -553, "き" => 121, "こ" => 505, "で" => -201, "と" => -547, "ど" => -123, "に" => -789, "の" => -185, "は" => -847, "も" => -466, "や" => -470, "よ" => 182, "ら" => -292, "り" => 208, "れ" => 169, "を" => -446, "ん" => -137, "・" => -135, "主" => -402, "京" => -268, "区" => -912, "午" => 871, "国" => -460, "大" => 561, "委" => 729, "市" => -411, "日" => -141, "理" => 361, "生" => -408, "県" => -386, "都" => -718, "「" => -463, "・" => -135 }
- UW2 = { "," => -829, "、" => -829, "〇" => 892, "「" => -645, "」" => 3145, "あ" => -538, "い" => 505, "う" => 134, "お" => -502, "か" => 1454, "が" => -856, "く" => -412, "こ" => 1141, "さ" => 878, "ざ" => 540, "し" => 1529, "す" => -675, "せ" => 300, "そ" => -1011, "た" => 188, "だ" => 1837, "つ" => -949, "て" => -291, "で" => -268, "と" => -981, "ど" => 1273, "な" => 1063, "に" => -1764, "の" => 130, "は" => -409, "ひ" => -1273, "べ" => 1261, "ま" => 600, "も" => -1263, "や" => -402, "よ" => 1639, "り" => -579, "る" => -694, "れ" => 571, "を" => -2516, "ん" => 2095, "ア" => -587, "カ" => 306, "キ" => 568, "ッ" => 831, "三" => -758, "不" => -2150, "世" => -302, "中" => -968, "主" => -861, "事" => 492, "人" => -123, "会" => 978, "保" => 362, "入" => 548, "初" => -3025, "副" => -1566, "北" => -3414, "区" => -422, "大" => -1769, "天" => -865, "太" => -483, "子" => -1519, "学" => 760, "実" => 1023, "小" => -2009, "市" => -813, "年" => -1060, "強" => 1067, "手" => -1519, "揺" => -1033, "政" => 1522, "文" => -1355, "新" => -1682, "日" => -1815, "明" => -1462, "最" => -630, "朝" => -1843, "本" => -1650, "東" => -931, "果" => -665, "次" => -2378, "民" => -180, "気" => -1740, "理" => 752, "発" => 529, "目" => -1584, "相" => -242, "県" => -1165, "立" => -763, "第" => 810, "米" => 509, "自" => -1353, "行" => 838, "西" => -744, "見" => -3874, "調" => 1010, "議" => 1198, "込" => 3041, "開" => 1758, "間" => -1257, "「" => -645, "」" => 3145, "ッ" => 831, "ア" => -587, "カ" => 306, "キ" => 568 }
- UW3 = { "," => 4889, "1" => -800, "−" => -1723, "、" => 4889, "々" => -2311, "〇" => 5827, "」" => 2670, "〓" => -3573, "あ" => -2696, "い" => 1006, "う" => 2342, "え" => 1983, "お" => -4864, "か" => -1163, "が" => 3271, "く" => 1004, "け" => 388, "げ" => 401, "こ" => -3552, "ご" => -3116, "さ" => -1058, "し" => -395, "す" => 584, "せ" => 3685, "そ" => -5228, "た" => 842, "ち" => -521, "っ" => -1444, "つ" => -1081, "て" => 6167, "で" => 2318, "と" => 1691, "ど" => -899, "な" => -2788, "に" => 2745, "の" => 4056, "は" => 4555, "ひ" => -2171, "ふ" => -1798, "へ" => 1199, "ほ" => -5516, "ま" => -4384, "み" => -120, "め" => 1205, "も" => 2323, "や" => -788, "よ" => -202, "ら" => 727, "り" => 649, "る" => 5905, "れ" => 2773, "わ" => -1207, "を" => 6620, "ん" => -518, "ア" => 551, "グ" => 1319, "ス" => 874, "ッ" => -1350, "ト" => 521, "ム" => 1109, "ル" => 1591, "ロ" => 2201, "ン" => 278, "・" => -3794, "一" => -1619, "下" => -1759, "世" => -2087, "両" => 3815, "中" => 653, "主" => -758, "予" => -1193, "二" => 974, "人" => 2742, "今" => 792, "他" => 1889, "以" => -1368, "低" => 811, "何" => 4265, "作" => -361, "保" => -2439, "元" => 4858, "党" => 3593, "全" => 1574, "公" => -3030, "六" => 755, "共" => -1880, "円" => 5807, "再" => 3095, "分" => 457, "初" => 2475, "別" => 1129, "前" => 2286, "副" => 4437, "力" => 365, "動" => -949, "務" => -1872, "化" => 1327, "北" => -1038, "区" => 4646, "千" => -2309, "午" => -783, "協" => -1006, "口" => 483, "右" => 1233, "各" => 3588, "合" => -241, "同" => 3906, "和" => -837, "員" => 4513, "国" => 642, "型" => 1389, "場" => 1219, "外" => -241, "妻" => 2016, "学" => -1356, "安" => -423, "実" => -1008, "家" => 1078, "小" => -513, "少" => -3102, "州" => 1155, "市" => 3197, "平" => -1804, "年" => 2416, "広" => -1030, "府" => 1605, "度" => 1452, "建" => -2352, "当" => -3885, "得" => 1905, "思" => -1291, "性" => 1822, "戸" => -488, "指" => -3973, "政" => -2013, "教" => -1479, "数" => 3222, "文" => -1489, "新" => 1764, "日" => 2099, "旧" => 5792, "昨" => -661, "時" => -1248, "曜" => -951, "最" => -937, "月" => 4125, "期" => 360, "李" => 3094, "村" => 364, "東" => -805, "核" => 5156, "森" => 2438, "業" => 484, "氏" => 2613, "民" => -1694, "決" => -1073, "法" => 1868, "海" => -495, "無" => 979, "物" => 461, "特" => -3850, "生" => -273, "用" => 914, "町" => 1215, "的" => 7313, "直" => -1835, "省" => 792, "県" => 6293, "知" => -1528, "私" => 4231, "税" => 401, "立" => -960, "第" => 1201, "米" => 7767, "系" => 3066, "約" => 3663, "級" => 1384, "統" => -4229, "総" => 1163, "線" => 1255, "者" => 6457, "能" => 725, "自" => -2869, "英" => 785, "見" => 1044, "調" => -562, "財" => -733, "費" => 1777, "車" => 1835, "軍" => 1375, "込" => -1504, "通" => -1136, "選" => -681, "郎" => 1026, "郡" => 4404, "部" => 1200, "金" => 2163, "長" => 421, "開" => -1432, "間" => 1302, "関" => -1282, "雨" => 2009, "電" => -1045, "非" => 2066, "駅" => 1620, "1" => -800, "」" => 2670, "・" => -3794, "ッ" => -1350, "ア" => 551, "グ" => 1319, "ス" => 874, "ト" => 521, "ム" => 1109, "ル" => 1591, "ロ" => 2201, "ン" => 278 }
- UW4 = { "," => 3930, "." => 3508, "―" => -4841, "、" => 3930, "。" => 3508, "〇" => 4999, "「" => 1895, "」" => 3798, "〓" => -5156, "あ" => 4752, "い" => -3435, "う" => -640, "え" => -2514, "お" => 2405, "か" => 530, "が" => 6006, "き" => -4482, "ぎ" => -3821, "く" => -3788, "け" => -4376, "げ" => -4734, "こ" => 2255, "ご" => 1979, "さ" => 2864, "し" => -843, "じ" => -2506, "す" => -731, "ず" => 1251, "せ" => 181, "そ" => 4091, "た" => 5034, "だ" => 5408, "ち" => -3654, "っ" => -5882, "つ" => -1659, "て" => 3994, "で" => 7410, "と" => 4547, "な" => 5433, "に" => 6499, "ぬ" => 1853, "ね" => 1413, "の" => 7396, "は" => 8578, "ば" => 1940, "ひ" => 4249, "び" => -4134, "ふ" => 1345, "へ" => 6665, "べ" => -744, "ほ" => 1464, "ま" => 1051, "み" => -2082, "む" => -882, "め" => -5046, "も" => 4169, "ゃ" => -2666, "や" => 2795, "ょ" => -1544, "よ" => 3351, "ら" => -2922, "り" => -9726, "る" => -14896, "れ" => -2613, "ろ" => -4570, "わ" => -1783, "を" => 13150, "ん" => -2352, "カ" => 2145, "コ" => 1789, "セ" => 1287, "ッ" => -724, "ト" => -403, "メ" => -1635, "ラ" => -881, "リ" => -541, "ル" => -856, "ン" => -3637, "・" => -4371, "ー" => -11870, "一" => -2069, "中" => 2210, "予" => 782, "事" => -190, "井" => -1768, "人" => 1036, "以" => 544, "会" => 950, "体" => -1286, "作" => 530, "側" => 4292, "先" => 601, "党" => -2006, "共" => -1212, "内" => 584, "円" => 788, "初" => 1347, "前" => 1623, "副" => 3879, "力" => -302, "動" => -740, "務" => -2715, "化" => 776, "区" => 4517, "協" => 1013, "参" => 1555, "合" => -1834, "和" => -681, "員" => -910, "器" => -851, "回" => 1500, "国" => -619, "園" => -1200, "地" => 866, "場" => -1410, "塁" => -2094, "士" => -1413, "多" => 1067, "大" => 571, "子" => -4802, "学" => -1397, "定" => -1057, "寺" => -809, "小" => 1910, "屋" => -1328, "山" => -1500, "島" => -2056, "川" => -2667, "市" => 2771, "年" => 374, "庁" => -4556, "後" => 456, "性" => 553, "感" => 916, "所" => -1566, "支" => 856, "改" => 787, "政" => 2182, "教" => 704, "文" => 522, "方" => -856, "日" => 1798, "時" => 1829, "最" => 845, "月" => -9066, "木" => -485, "来" => -442, "校" => -360, "業" => -1043, "氏" => 5388, "民" => -2716, "気" => -910, "沢" => -939, "済" => -543, "物" => -735, "率" => 672, "球" => -1267, "生" => -1286, "産" => -1101, "田" => -2900, "町" => 1826, "的" => 2586, "目" => 922, "省" => -3485, "県" => 2997, "空" => -867, "立" => -2112, "第" => 788, "米" => 2937, "系" => 786, "約" => 2171, "経" => 1146, "統" => -1169, "総" => 940, "線" => -994, "署" => 749, "者" => 2145, "能" => -730, "般" => -852, "行" => -792, "規" => 792, "警" => -1184, "議" => -244, "谷" => -1000, "賞" => 730, "車" => -1481, "軍" => 1158, "輪" => -1433, "込" => -3370, "近" => 929, "道" => -1291, "選" => 2596, "郎" => -4866, "都" => 1192, "野" => -1100, "銀" => -2213, "長" => 357, "間" => -2344, "院" => -2297, "際" => -2604, "電" => -878, "領" => -1659, "題" => -792, "館" => -1984, "首" => 1749, "高" => 2120, "「" => 1895, "」" => 3798, "・" => -4371, "ッ" => -724, "ー" => -11870, "カ" => 2145, "コ" => 1789, "セ" => 1287, "ト" => -403, "メ" => -1635, "ラ" => -881, "リ" => -541, "ル" => -856, "ン" => -3637 }
- UW5 = { "," => 465, "." => -299, "1" => -514, "E2" => -32768, "]" => -2762, "、" => 465, "。" => -299, "「" => 363, "あ" => 1655, "い" => 331, "う" => -503, "え" => 1199, "お" => 527, "か" => 647, "が" => -421, "き" => 1624, "ぎ" => 1971, "く" => 312, "げ" => -983, "さ" => -1537, "し" => -1371, "す" => -852, "だ" => -1186, "ち" => 1093, "っ" => 52, "つ" => 921, "て" => -18, "で" => -850, "と" => -127, "ど" => 1682, "な" => -787, "に" => -1224, "の" => -635, "は" => -578, "べ" => 1001, "み" => 502, "め" => 865, "ゃ" => 3350, "ょ" => 854, "り" => -208, "る" => 429, "れ" => 504, "わ" => 419, "を" => -1264, "ん" => 327, "イ" => 241, "ル" => 451, "ン" => -343, "中" => -871, "京" => 722, "会" => -1153, "党" => -654, "務" => 3519, "区" => -901, "告" => 848, "員" => 2104, "大" => -1296, "学" => -548, "定" => 1785, "嵐" => -1304, "市" => -2991, "席" => 921, "年" => 1763, "思" => 872, "所" => -814, "挙" => 1618, "新" => -1682, "日" => 218, "月" => -4353, "査" => 932, "格" => 1356, "機" => -1508, "氏" => -1347, "田" => 240, "町" => -3912, "的" => -3149, "相" => 1319, "省" => -1052, "県" => -4003, "研" => -997, "社" => -278, "空" => -813, "統" => 1955, "者" => -2233, "表" => 663, "語" => -1073, "議" => 1219, "選" => -1018, "郎" => -368, "長" => 786, "間" => 1191, "題" => 2368, "館" => -689, "1" => -514, "E2" => -32768, "「" => 363, "イ" => 241, "ル" => 451, "ン" => -343 }
- UW6 = { "," => 227, "." => 808, "1" => -270, "E1" => 306, "、" => 227, "。" => 808, "あ" => -307, "う" => 189, "か" => 241, "が" => -73, "く" => -121, "こ" => -200, "じ" => 1782, "す" => 383, "た" => -428, "っ" => 573, "て" => -1014, "で" => 101, "と" => -105, "な" => -253, "に" => -149, "の" => -417, "は" => -236, "も" => -206, "り" => 187, "る" => -135, "を" => 195, "ル" => -673, "ン" => -496, "一" => -277, "中" => 201, "件" => -800, "会" => 624, "前" => 302, "区" => 1792, "員" => -1212, "委" => 798, "学" => -960, "市" => 887, "広" => -695, "後" => 535, "業" => -697, "相" => 753, "社" => -507, "福" => 974, "空" => -822, "者" => 1811, "連" => 463, "郎" => 1082, "1" => -270, "E1" => 306, "ル" => -673, "ン" => -496 }
+ UQ3 = {
+ "BA" => -479,
+ "BH" => 42,
+ "BI" => 1913,
+ "BK" => -7198,
+ "BM" => 3160,
+ "BN" => 6427,
+ "BO" => 14_761,
+ "OI" => -827,
+ "ON" => -3212,
+ }
+ UW1 = {
+ "," => 156,
+ "、" => 156,
+ "「" => -463,
+ "あ" => -941,
+ "う" => -127,
+ "が" => -553,
+ "き" => 121,
+ "こ" => 505,
+ "で" => -201,
+ "と" => -547,
+ "ど" => -123,
+ "に" => -789,
+ "の" => -185,
+ "は" => -847,
+ "も" => -466,
+ "や" => -470,
+ "よ" => 182,
+ "ら" => -292,
+ "り" => 208,
+ "れ" => 169,
+ "を" => -446,
+ "ん" => -137,
+ "・" => -135,
+ "主" => -402,
+ "京" => -268,
+ "区" => -912,
+ "午" => 871,
+ "国" => -460,
+ "大" => 561,
+ "委" => 729,
+ "市" => -411,
+ "日" => -141,
+ "理" => 361,
+ "生" => -408,
+ "県" => -386,
+ "都" => -718,
+ "「" => -463,
+ "・" => -135,
+ }
+ UW2 = {
+ "," => -829,
+ "、" => -829,
+ "〇" => 892,
+ "「" => -645,
+ "」" => 3145,
+ "あ" => -538,
+ "い" => 505,
+ "う" => 134,
+ "お" => -502,
+ "か" => 1454,
+ "が" => -856,
+ "く" => -412,
+ "こ" => 1141,
+ "さ" => 878,
+ "ざ" => 540,
+ "し" => 1529,
+ "す" => -675,
+ "せ" => 300,
+ "そ" => -1011,
+ "た" => 188,
+ "だ" => 1837,
+ "つ" => -949,
+ "て" => -291,
+ "で" => -268,
+ "と" => -981,
+ "ど" => 1273,
+ "な" => 1063,
+ "に" => -1764,
+ "の" => 130,
+ "は" => -409,
+ "ひ" => -1273,
+ "べ" => 1261,
+ "ま" => 600,
+ "も" => -1263,
+ "や" => -402,
+ "よ" => 1639,
+ "り" => -579,
+ "る" => -694,
+ "れ" => 571,
+ "を" => -2516,
+ "ん" => 2095,
+ "ア" => -587,
+ "カ" => 306,
+ "キ" => 568,
+ "ッ" => 831,
+ "三" => -758,
+ "不" => -2150,
+ "世" => -302,
+ "中" => -968,
+ "主" => -861,
+ "事" => 492,
+ "人" => -123,
+ "会" => 978,
+ "保" => 362,
+ "入" => 548,
+ "初" => -3025,
+ "副" => -1566,
+ "北" => -3414,
+ "区" => -422,
+ "大" => -1769,
+ "天" => -865,
+ "太" => -483,
+ "子" => -1519,
+ "学" => 760,
+ "実" => 1023,
+ "小" => -2009,
+ "市" => -813,
+ "年" => -1060,
+ "強" => 1067,
+ "手" => -1519,
+ "揺" => -1033,
+ "政" => 1522,
+ "文" => -1355,
+ "新" => -1682,
+ "日" => -1815,
+ "明" => -1462,
+ "最" => -630,
+ "朝" => -1843,
+ "本" => -1650,
+ "東" => -931,
+ "果" => -665,
+ "次" => -2378,
+ "民" => -180,
+ "気" => -1740,
+ "理" => 752,
+ "発" => 529,
+ "目" => -1584,
+ "相" => -242,
+ "県" => -1165,
+ "立" => -763,
+ "第" => 810,
+ "米" => 509,
+ "自" => -1353,
+ "行" => 838,
+ "西" => -744,
+ "見" => -3874,
+ "調" => 1010,
+ "議" => 1198,
+ "込" => 3041,
+ "開" => 1758,
+ "間" => -1257,
+ "「" => -645,
+ "」" => 3145,
+ "ッ" => 831,
+ "ア" => -587,
+ "カ" => 306,
+ "キ" => 568,
+ }
+ UW3 = {
+ "," => 4889,
+ "1" => -800,
+ "−" => -1723,
+ "、" => 4889,
+ "々" => -2311,
+ "〇" => 5827,
+ "」" => 2670,
+ "〓" => -3573,
+ "あ" => -2696,
+ "い" => 1006,
+ "う" => 2342,
+ "え" => 1983,
+ "お" => -4864,
+ "か" => -1163,
+ "が" => 3271,
+ "く" => 1004,
+ "け" => 388,
+ "げ" => 401,
+ "こ" => -3552,
+ "ご" => -3116,
+ "さ" => -1058,
+ "し" => -395,
+ "す" => 584,
+ "せ" => 3685,
+ "そ" => -5228,
+ "た" => 842,
+ "ち" => -521,
+ "っ" => -1444,
+ "つ" => -1081,
+ "て" => 6167,
+ "で" => 2318,
+ "と" => 1691,
+ "ど" => -899,
+ "な" => -2788,
+ "に" => 2745,
+ "の" => 4056,
+ "は" => 4555,
+ "ひ" => -2171,
+ "ふ" => -1798,
+ "へ" => 1199,
+ "ほ" => -5516,
+ "ま" => -4384,
+ "み" => -120,
+ "め" => 1205,
+ "も" => 2323,
+ "や" => -788,
+ "よ" => -202,
+ "ら" => 727,
+ "り" => 649,
+ "る" => 5905,
+ "れ" => 2773,
+ "わ" => -1207,
+ "を" => 6620,
+ "ん" => -518,
+ "ア" => 551,
+ "グ" => 1319,
+ "ス" => 874,
+ "ッ" => -1350,
+ "ト" => 521,
+ "ム" => 1109,
+ "ル" => 1591,
+ "ロ" => 2201,
+ "ン" => 278,
+ "・" => -3794,
+ "一" => -1619,
+ "下" => -1759,
+ "世" => -2087,
+ "両" => 3815,
+ "中" => 653,
+ "主" => -758,
+ "予" => -1193,
+ "二" => 974,
+ "人" => 2742,
+ "今" => 792,
+ "他" => 1889,
+ "以" => -1368,
+ "低" => 811,
+ "何" => 4265,
+ "作" => -361,
+ "保" => -2439,
+ "元" => 4858,
+ "党" => 3593,
+ "全" => 1574,
+ "公" => -3030,
+ "六" => 755,
+ "共" => -1880,
+ "円" => 5807,
+ "再" => 3095,
+ "分" => 457,
+ "初" => 2475,
+ "別" => 1129,
+ "前" => 2286,
+ "副" => 4437,
+ "力" => 365,
+ "動" => -949,
+ "務" => -1872,
+ "化" => 1327,
+ "北" => -1038,
+ "区" => 4646,
+ "千" => -2309,
+ "午" => -783,
+ "協" => -1006,
+ "口" => 483,
+ "右" => 1233,
+ "各" => 3588,
+ "合" => -241,
+ "同" => 3906,
+ "和" => -837,
+ "員" => 4513,
+ "国" => 642,
+ "型" => 1389,
+ "場" => 1219,
+ "外" => -241,
+ "妻" => 2016,
+ "学" => -1356,
+ "安" => -423,
+ "実" => -1008,
+ "家" => 1078,
+ "小" => -513,
+ "少" => -3102,
+ "州" => 1155,
+ "市" => 3197,
+ "平" => -1804,
+ "年" => 2416,
+ "広" => -1030,
+ "府" => 1605,
+ "度" => 1452,
+ "建" => -2352,
+ "当" => -3885,
+ "得" => 1905,
+ "思" => -1291,
+ "性" => 1822,
+ "戸" => -488,
+ "指" => -3973,
+ "政" => -2013,
+ "教" => -1479,
+ "数" => 3222,
+ "文" => -1489,
+ "新" => 1764,
+ "日" => 2099,
+ "旧" => 5792,
+ "昨" => -661,
+ "時" => -1248,
+ "曜" => -951,
+ "最" => -937,
+ "月" => 4125,
+ "期" => 360,
+ "李" => 3094,
+ "村" => 364,
+ "東" => -805,
+ "核" => 5156,
+ "森" => 2438,
+ "業" => 484,
+ "氏" => 2613,
+ "民" => -1694,
+ "決" => -1073,
+ "法" => 1868,
+ "海" => -495,
+ "無" => 979,
+ "物" => 461,
+ "特" => -3850,
+ "生" => -273,
+ "用" => 914,
+ "町" => 1215,
+ "的" => 7313,
+ "直" => -1835,
+ "省" => 792,
+ "県" => 6293,
+ "知" => -1528,
+ "私" => 4231,
+ "税" => 401,
+ "立" => -960,
+ "第" => 1201,
+ "米" => 7767,
+ "系" => 3066,
+ "約" => 3663,
+ "級" => 1384,
+ "統" => -4229,
+ "総" => 1163,
+ "線" => 1255,
+ "者" => 6457,
+ "能" => 725,
+ "自" => -2869,
+ "英" => 785,
+ "見" => 1044,
+ "調" => -562,
+ "財" => -733,
+ "費" => 1777,
+ "車" => 1835,
+ "軍" => 1375,
+ "込" => -1504,
+ "通" => -1136,
+ "選" => -681,
+ "郎" => 1026,
+ "郡" => 4404,
+ "部" => 1200,
+ "金" => 2163,
+ "長" => 421,
+ "開" => -1432,
+ "間" => 1302,
+ "関" => -1282,
+ "雨" => 2009,
+ "電" => -1045,
+ "非" => 2066,
+ "駅" => 1620,
+ "1" => -800,
+ "」" => 2670,
+ "・" => -3794,
+ "ッ" => -1350,
+ "ア" => 551,
+ "グ" => 1319,
+ "ス" => 874,
+ "ト" => 521,
+ "ム" => 1109,
+ "ル" => 1591,
+ "ロ" => 2201,
+ "ン" => 278,
+ }
+ UW4 = {
+ "," => 3930,
+ "." => 3508,
+ "―" => -4841,
+ "、" => 3930,
+ "。" => 3508,
+ "〇" => 4999,
+ "「" => 1895,
+ "」" => 3798,
+ "〓" => -5156,
+ "あ" => 4752,
+ "い" => -3435,
+ "う" => -640,
+ "え" => -2514,
+ "お" => 2405,
+ "か" => 530,
+ "が" => 6006,
+ "き" => -4482,
+ "ぎ" => -3821,
+ "く" => -3788,
+ "け" => -4376,
+ "げ" => -4734,
+ "こ" => 2255,
+ "ご" => 1979,
+ "さ" => 2864,
+ "し" => -843,
+ "じ" => -2506,
+ "す" => -731,
+ "ず" => 1251,
+ "せ" => 181,
+ "そ" => 4091,
+ "た" => 5034,
+ "だ" => 5408,
+ "ち" => -3654,
+ "っ" => -5882,
+ "つ" => -1659,
+ "て" => 3994,
+ "で" => 7410,
+ "と" => 4547,
+ "な" => 5433,
+ "に" => 6499,
+ "ぬ" => 1853,
+ "ね" => 1413,
+ "の" => 7396,
+ "は" => 8578,
+ "ば" => 1940,
+ "ひ" => 4249,
+ "び" => -4134,
+ "ふ" => 1345,
+ "へ" => 6665,
+ "べ" => -744,
+ "ほ" => 1464,
+ "ま" => 1051,
+ "み" => -2082,
+ "む" => -882,
+ "め" => -5046,
+ "も" => 4169,
+ "ゃ" => -2666,
+ "や" => 2795,
+ "ょ" => -1544,
+ "よ" => 3351,
+ "ら" => -2922,
+ "り" => -9726,
+ "る" => -14_896,
+ "れ" => -2613,
+ "ろ" => -4570,
+ "わ" => -1783,
+ "を" => 13_150,
+ "ん" => -2352,
+ "カ" => 2145,
+ "コ" => 1789,
+ "セ" => 1287,
+ "ッ" => -724,
+ "ト" => -403,
+ "メ" => -1635,
+ "ラ" => -881,
+ "リ" => -541,
+ "ル" => -856,
+ "ン" => -3637,
+ "・" => -4371,
+ "ー" => -11_870,
+ "一" => -2069,
+ "中" => 2210,
+ "予" => 782,
+ "事" => -190,
+ "井" => -1768,
+ "人" => 1036,
+ "以" => 544,
+ "会" => 950,
+ "体" => -1286,
+ "作" => 530,
+ "側" => 4292,
+ "先" => 601,
+ "党" => -2006,
+ "共" => -1212,
+ "内" => 584,
+ "円" => 788,
+ "初" => 1347,
+ "前" => 1623,
+ "副" => 3879,
+ "力" => -302,
+ "動" => -740,
+ "務" => -2715,
+ "化" => 776,
+ "区" => 4517,
+ "協" => 1013,
+ "参" => 1555,
+ "合" => -1834,
+ "和" => -681,
+ "員" => -910,
+ "器" => -851,
+ "回" => 1500,
+ "国" => -619,
+ "園" => -1200,
+ "地" => 866,
+ "場" => -1410,
+ "塁" => -2094,
+ "士" => -1413,
+ "多" => 1067,
+ "大" => 571,
+ "子" => -4802,
+ "学" => -1397,
+ "定" => -1057,
+ "寺" => -809,
+ "小" => 1910,
+ "屋" => -1328,
+ "山" => -1500,
+ "島" => -2056,
+ "川" => -2667,
+ "市" => 2771,
+ "年" => 374,
+ "庁" => -4556,
+ "後" => 456,
+ "性" => 553,
+ "感" => 916,
+ "所" => -1566,
+ "支" => 856,
+ "改" => 787,
+ "政" => 2182,
+ "教" => 704,
+ "文" => 522,
+ "方" => -856,
+ "日" => 1798,
+ "時" => 1829,
+ "最" => 845,
+ "月" => -9066,
+ "木" => -485,
+ "来" => -442,
+ "校" => -360,
+ "業" => -1043,
+ "氏" => 5388,
+ "民" => -2716,
+ "気" => -910,
+ "沢" => -939,
+ "済" => -543,
+ "物" => -735,
+ "率" => 672,
+ "球" => -1267,
+ "生" => -1286,
+ "産" => -1101,
+ "田" => -2900,
+ "町" => 1826,
+ "的" => 2586,
+ "目" => 922,
+ "省" => -3485,
+ "県" => 2997,
+ "空" => -867,
+ "立" => -2112,
+ "第" => 788,
+ "米" => 2937,
+ "系" => 786,
+ "約" => 2171,
+ "経" => 1146,
+ "統" => -1169,
+ "総" => 940,
+ "線" => -994,
+ "署" => 749,
+ "者" => 2145,
+ "能" => -730,
+ "般" => -852,
+ "行" => -792,
+ "規" => 792,
+ "警" => -1184,
+ "議" => -244,
+ "谷" => -1000,
+ "賞" => 730,
+ "車" => -1481,
+ "軍" => 1158,
+ "輪" => -1433,
+ "込" => -3370,
+ "近" => 929,
+ "道" => -1291,
+ "選" => 2596,
+ "郎" => -4866,
+ "都" => 1192,
+ "野" => -1100,
+ "銀" => -2213,
+ "長" => 357,
+ "間" => -2344,
+ "院" => -2297,
+ "際" => -2604,
+ "電" => -878,
+ "領" => -1659,
+ "題" => -792,
+ "館" => -1984,
+ "首" => 1749,
+ "高" => 2120,
+ "「" => 1895,
+ "」" => 3798,
+ "・" => -4371,
+ "ッ" => -724,
+ "ー" => -11_870,
+ "カ" => 2145,
+ "コ" => 1789,
+ "セ" => 1287,
+ "ト" => -403,
+ "メ" => -1635,
+ "ラ" => -881,
+ "リ" => -541,
+ "ル" => -856,
+ "ン" => -3637,
+ }
+ UW5 = {
+ "," => 465,
+ "." => -299,
+ "1" => -514,
+ "E2" => -32_768,
+ "]" => -2762,
+ "、" => 465,
+ "。" => -299,
+ "「" => 363,
+ "あ" => 1655,
+ "い" => 331,
+ "う" => -503,
+ "え" => 1199,
+ "お" => 527,
+ "か" => 647,
+ "が" => -421,
+ "き" => 1624,
+ "ぎ" => 1971,
+ "く" => 312,
+ "げ" => -983,
+ "さ" => -1537,
+ "し" => -1371,
+ "す" => -852,
+ "だ" => -1186,
+ "ち" => 1093,
+ "っ" => 52,
+ "つ" => 921,
+ "て" => -18,
+ "で" => -850,
+ "と" => -127,
+ "ど" => 1682,
+ "な" => -787,
+ "に" => -1224,
+ "の" => -635,
+ "は" => -578,
+ "べ" => 1001,
+ "み" => 502,
+ "め" => 865,
+ "ゃ" => 3350,
+ "ょ" => 854,
+ "り" => -208,
+ "る" => 429,
+ "れ" => 504,
+ "わ" => 419,
+ "を" => -1264,
+ "ん" => 327,
+ "イ" => 241,
+ "ル" => 451,
+ "ン" => -343,
+ "中" => -871,
+ "京" => 722,
+ "会" => -1153,
+ "党" => -654,
+ "務" => 3519,
+ "区" => -901,
+ "告" => 848,
+ "員" => 2104,
+ "大" => -1296,
+ "学" => -548,
+ "定" => 1785,
+ "嵐" => -1304,
+ "市" => -2991,
+ "席" => 921,
+ "年" => 1763,
+ "思" => 872,
+ "所" => -814,
+ "挙" => 1618,
+ "新" => -1682,
+ "日" => 218,
+ "月" => -4353,
+ "査" => 932,
+ "格" => 1356,
+ "機" => -1508,
+ "氏" => -1347,
+ "田" => 240,
+ "町" => -3912,
+ "的" => -3149,
+ "相" => 1319,
+ "省" => -1052,
+ "県" => -4003,
+ "研" => -997,
+ "社" => -278,
+ "空" => -813,
+ "統" => 1955,
+ "者" => -2233,
+ "表" => 663,
+ "語" => -1073,
+ "議" => 1219,
+ "選" => -1018,
+ "郎" => -368,
+ "長" => 786,
+ "間" => 1191,
+ "題" => 2368,
+ "館" => -689,
+ "1" => -514,
+ "E2" => -32_768,
+ "「" => 363,
+ "イ" => 241,
+ "ル" => 451,
+ "ン" => -343,
+ }
+ UW6 = {
+ "," => 227,
+ "." => 808,
+ "1" => -270,
+ "E1" => 306,
+ "、" => 227,
+ "。" => 808,
+ "あ" => -307,
+ "う" => 189,
+ "か" => 241,
+ "が" => -73,
+ "く" => -121,
+ "こ" => -200,
+ "じ" => 1782,
+ "す" => 383,
+ "た" => -428,
+ "っ" => 573,
+ "て" => -1014,
+ "で" => 101,
+ "と" => -105,
+ "な" => -253,
+ "に" => -149,
+ "の" => -417,
+ "は" => -236,
+ "も" => -206,
+ "り" => 187,
+ "る" => -135,
+ "を" => 195,
+ "ル" => -673,
+ "ン" => -496,
+ "一" => -277,
+ "中" => 201,
+ "件" => -800,
+ "会" => 624,
+ "前" => 302,
+ "区" => 1792,
+ "員" => -1212,
+ "委" => 798,
+ "学" => -960,
+ "市" => 887,
+ "広" => -695,
+ "後" => 535,
+ "業" => -697,
+ "相" => 753,
+ "社" => -507,
+ "福" => 974,
+ "空" => -822,
+ "者" => 1811,
+ "連" => 463,
+ "郎" => 1082,
+ "1" => -270,
+ "E1" => 306,
+ "ル" => -673,
+ "ン" => -496,
+ }
class << self
def segment(text)
@@ -65,16 +1387,16 @@ class TinyJapaneseSegmenter
result = []
- segments = ["B3", "B2", "B1"]
- ctypes = ["O", "O", "O"]
+ segments = %w[B3 B2 B1]
+ ctypes = %w[O O O]
text.chars.each do |char|
segments << char
ctypes << ctype(char)
end
- segments.concat(["E1", "E2", "E3"])
- ctypes.concat(["O", "O", "O"])
+ segments.concat(%w[E1 E2 E3])
+ ctypes.concat(%w[O O O])
word = segments[3]
p1 = "U"
@@ -161,11 +1483,7 @@ class TinyJapaneseSegmenter
private
def ctype(text)
- CHARTYPE.each do |regexp, value|
- if text.match(regexp)
- return value
- end
- end
+ CHARTYPE.each { |regexp, value| return value if text.match(regexp) }
"O"
end
diff --git a/lib/topic_creator.rb b/lib/topic_creator.rb
index 12ae6114a04..084c71584a3 100644
--- a/lib/topic_creator.rb
+++ b/lib/topic_creator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class TopicCreator
-
attr_reader :user, :guardian, :opts
include HasErrors
@@ -33,7 +32,12 @@ class TopicCreator
valid_tags = guardian.can_create_tag? ? tags : existing_tags
# all add to topic.errors
- DiscourseTagging.validate_min_required_tags_for_category(guardian, topic, category, valid_tags)
+ DiscourseTagging.validate_min_required_tags_for_category(
+ guardian,
+ topic,
+ category,
+ valid_tags,
+ )
DiscourseTagging.validate_required_tags_from_group(guardian, topic, category, existing_tags)
DiscourseTagging.validate_category_restricted_tags(guardian, topic, category, valid_tags)
end
@@ -84,9 +88,10 @@ class TopicCreator
end
def create_shared_draft(topic)
- return if @opts[:shared_draft].blank? || @opts[:shared_draft] == 'false'
+ return if @opts[:shared_draft].blank? || @opts[:shared_draft] == "false"
- category_id = @opts[:category].blank? ? SiteSetting.shared_drafts_category.to_i : @opts[:category]
+ category_id =
+ @opts[:category].blank? ? SiteSetting.shared_drafts_category.to_i : @opts[:category]
SharedDraft.create(topic_id: topic.id, category_id: category_id)
end
@@ -104,9 +109,7 @@ class TopicCreator
end
def watch_topic(topic)
- unless @opts[:auto_track] == false
- topic.notifier.watch_topic!(topic.user_id)
- end
+ topic.notifier.watch_topic!(topic.user_id) unless @opts[:auto_track] == false
topic.reload.topic_allowed_users.each do |tau|
next if tau.user_id == -1 || tau.user_id == topic.user_id
@@ -125,10 +128,10 @@ class TopicCreator
title: @opts[:title],
user_id: @user.id,
last_post_user_id: @user.id,
- visible: @opts[:visible]
+ visible: @opts[:visible],
}
- [:subtype, :archetype, :meta_data, :import_mode, :advance_draft].each do |key|
+ %i[subtype archetype meta_data import_mode advance_draft].each do |key|
topic_params[key] = @opts[key] if @opts[key].present?
end
@@ -144,12 +147,12 @@ class TopicCreator
topic_params[:subtype] = TopicSubtype.moderator_warning if @opts[:is_warning]
category = find_category
- @guardian.ensure_can_create!(Topic, category) unless (@opts[:skip_validations] || @opts[:archetype] == Archetype.private_message)
-
- if @opts[:category].present? && category.nil?
- raise Discourse::InvalidParameters.new(:category)
+ unless (@opts[:skip_validations] || @opts[:archetype] == Archetype.private_message)
+ @guardian.ensure_can_create!(Topic, category)
end
+ raise Discourse::InvalidParameters.new(:category) if @opts[:category].present? && category.nil?
+
topic_params[:category_id] = category.id if category.present?
topic_params[:created_at] = convert_time(@opts[:created_at]) if @opts[:created_at].present?
topic_params[:pinned_at] = convert_time(@opts[:pinned_at]) if @opts[:pinned_at].present?
@@ -169,18 +172,19 @@ class TopicCreator
end
def find_category
- @category ||= begin
- # PM can't have a category
- @opts.delete(:category) if @opts[:archetype].present? && @opts[:archetype] == Archetype.private_message
+ @category ||=
+ begin
+ # PM can't have a category
+ if @opts[:archetype].present? && @opts[:archetype] == Archetype.private_message
+ @opts.delete(:category)
+ end
- if @opts[:shared_draft]
- return Category.find(SiteSetting.shared_drafts_category)
- end
+ return Category.find(SiteSetting.shared_drafts_category) if @opts[:shared_draft]
- if (@opts[:category].is_a? Integer) || (@opts[:category] =~ /^\d+$/)
- Category.find_by(id: @opts[:category])
+ if (@opts[:category].is_a? Integer) || (@opts[:category] =~ /^\d+$/)
+ Category.find_by(id: @opts[:category])
+ end
end
- end
end
def setup_tags(topic)
@@ -215,11 +219,12 @@ class TopicCreator
return unless @opts[:archetype] == Archetype.private_message
topic.subtype = TopicSubtype.user_to_user unless topic.subtype
- unless @opts[:target_usernames].present? || @opts[:target_emails].present? || @opts[:target_group_names].present?
+ unless @opts[:target_usernames].present? || @opts[:target_emails].present? ||
+ @opts[:target_group_names].present?
rollback_with!(topic, :no_user_selected)
end
- if @opts[:target_emails].present? && [email protected]_send_private_messages_to_email? then
+ if @opts[:target_emails].present? && [email protected]_send_private_messages_to_email?
rollback_with!(topic, :send_to_email_disabled)
end
@@ -227,32 +232,30 @@ class TopicCreator
add_emails(topic, @opts[:target_emails])
add_groups(topic, @opts[:target_group_names])
- if !@added_users.include?(user)
- topic.topic_allowed_users.build(user_id: @user.id)
- end
-
+ topic.topic_allowed_users.build(user_id: @user.id) if !@added_users.include?(user)
end
def save_topic(topic)
topic.disable_rate_limits! if @opts[:skip_validations]
- unless topic.save(validate: !@opts[:skip_validations])
- rollback_from_errors!(topic)
- end
+ rollback_from_errors!(topic) unless topic.save(validate: !@opts[:skip_validations])
end
def add_users(topic, usernames)
return unless usernames
- names = usernames.split(',').flatten.map(&:downcase)
+ names = usernames.split(",").flatten.map(&:downcase)
len = 0
- User.includes(:user_option).where('username_lower in (?)', names).find_each do |user|
- check_can_send_permission!(topic, user)
- @added_users << user
- topic.topic_allowed_users.build(user_id: user.id)
- len += 1
- end
+ User
+ .includes(:user_option)
+ .where("username_lower in (?)", names)
+ .find_each do |user|
+ check_can_send_permission!(topic, user)
+ @added_users << user
+ topic.topic_allowed_users.build(user_id: user.id)
+ len += 1
+ end
rollback_with!(topic, :target_user_not_found) unless len == names.length
end
@@ -261,7 +264,7 @@ class TopicCreator
return unless emails
begin
- emails = emails.split(',').flatten
+ emails = emails.split(",").flatten
len = 0
emails.each do |email|
@@ -282,22 +285,27 @@ class TopicCreator
def add_groups(topic, groups)
return unless groups
- names = groups.split(',').flatten.map(&:downcase)
+ names = groups.split(",").flatten.map(&:downcase)
len = 0
- Group.where('lower(name) in (?)', names).each do |group|
- check_can_send_permission!(topic, group)
- topic.topic_allowed_groups.build(group_id: group.id)
- len += 1
- group.update_columns(has_messages: true) unless group.has_messages
- end
+ Group
+ .where("lower(name) in (?)", names)
+ .each do |group|
+ check_can_send_permission!(topic, group)
+ topic.topic_allowed_groups.build(group_id: group.id)
+ len += 1
+ group.update_columns(has_messages: true) unless group.has_messages
+ end
rollback_with!(topic, :target_group_not_found) unless len == names.length
end
def check_can_send_permission!(topic, obj)
unless @opts[:skip_validations] ||
- @guardian.can_send_private_message?(obj, notify_moderators: topic&.subtype == TopicSubtype.notify_moderators)
+ @guardian.can_send_private_message?(
+ obj,
+ notify_moderators: topic&.subtype == TopicSubtype.notify_moderators,
+ )
rollback_with!(topic, :cant_send_pm)
end
end
@@ -308,12 +316,13 @@ class TopicCreator
if !user && SiteSetting.enable_staged_users
username = UserNameSuggester.sanitize_username(display_name) if display_name.present?
- user = User.create!(
- email: email,
- username: UserNameSuggester.suggest(username.presence || email),
- name: display_name.presence || User.suggest_name(email),
- staged: true
- )
+ user =
+ User.create!(
+ email: email,
+ username: UserNameSuggester.suggest(username.presence || email),
+ name: display_name.presence || User.suggest_name(email),
+ staged: true,
+ )
end
user
diff --git a/lib/topic_list_responder.rb b/lib/topic_list_responder.rb
index ca15ada95b6..b99eaf0c850 100644
--- a/lib/topic_list_responder.rb
+++ b/lib/topic_list_responder.rb
@@ -2,20 +2,19 @@
# Helps us respond with a topic list from a controller
module TopicListResponder
-
def respond_with_list(list)
discourse_expires_in 1.minute
respond_to do |format|
format.html do
@list = list
- store_preloaded(list.preload_key, MultiJson.dump(TopicListSerializer.new(list, scope: guardian)))
- render 'list/list'
- end
- format.json do
- render_serialized(list, TopicListSerializer)
+ store_preloaded(
+ list.preload_key,
+ MultiJson.dump(TopicListSerializer.new(list, scope: guardian)),
+ )
+ render "list/list"
end
+ format.json { render_serialized(list, TopicListSerializer) }
end
end
-
end
diff --git a/lib/topic_publisher.rb b/lib/topic_publisher.rb
index 9c812ec0009..f0611ccfb51 100644
--- a/lib/topic_publisher.rb
+++ b/lib/topic_publisher.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class TopicPublisher
-
def initialize(topic, published_by, category_id)
@topic = topic
@published_by = published_by
@@ -11,40 +10,38 @@ class TopicPublisher
def publish!
published_at = Time.zone.now
- TopicTimestampChanger.new(timestamp: published_at, topic: @topic).change! do
- if @topic.private_message?
- @topic = TopicConverter.new(@topic, @published_by)
- .convert_to_public_topic(@category_id)
- else
- PostRevisor.new(@topic.first_post, @topic).revise!(@published_by,
- category_id: @category_id,
- )
- end
+ TopicTimestampChanger
+ .new(timestamp: published_at, topic: @topic)
+ .change! do
+ if @topic.private_message?
+ @topic = TopicConverter.new(@topic, @published_by).convert_to_public_topic(@category_id)
+ else
+ PostRevisor.new(@topic.first_post, @topic).revise!(
+ @published_by,
+ category_id: @category_id,
+ )
+ end
- @topic.update_columns(visible: true)
+ @topic.update_columns(visible: true)
- StaffActionLogger.new(@published_by).log_topic_published(@topic)
+ StaffActionLogger.new(@published_by).log_topic_published(@topic)
- # Clean up any publishing artifacts
- SharedDraft.where(topic: @topic).delete_all
+ # Clean up any publishing artifacts
+ SharedDraft.where(topic: @topic).delete_all
- TopicTimer.where(topic: @topic).update_all(
- deleted_at: DateTime.now,
- deleted_by_id: @published_by.id
- )
+ TopicTimer.where(topic: @topic).update_all(
+ deleted_at: DateTime.now,
+ deleted_by_id: @published_by.id,
+ )
- op = @topic.first_post
+ op = @topic.first_post
- if op.present?
- op.revisions.destroy_all
+ if op.present?
+ op.revisions.destroy_all
- op.update_columns(
- version: 1,
- public_version: 1,
- last_version_at: published_at
- )
+ op.update_columns(version: 1, public_version: 1, last_version_at: published_at)
+ end
end
- end
Jobs.enqueue(
:notify_tag_change,
@@ -58,5 +55,4 @@ class TopicPublisher
@topic
end
-
end
diff --git a/lib/topic_query.rb b/lib/topic_query.rb
index 48dced2a69d..5b33a15fbed 100644
--- a/lib/topic_query.rb
+++ b/lib/topic_query.rb
@@ -8,30 +8,21 @@
class TopicQuery
include PrivateMessageLists
- PG_MAX_INT ||= 2147483647
+ PG_MAX_INT ||= 2_147_483_647
DEFAULT_PER_PAGE_COUNT ||= 30
def self.validators
- @validators ||= begin
+ @validators ||=
+ begin
+ int = lambda { |x| Integer === x || (String === x && x.match?(/^-?[0-9]+$/)) }
- int = lambda do |x|
- Integer === x || (String === x && x.match?(/^-?[0-9]+$/))
- end
+ zero_up_to_max_int = lambda { |x| int.call(x) && x.to_i.between?(0, PG_MAX_INT) }
- zero_up_to_max_int = lambda do |x|
- int.call(x) && x.to_i.between?(0, PG_MAX_INT)
+ { max_posts: zero_up_to_max_int, min_posts: zero_up_to_max_int, page: zero_up_to_max_int }
end
-
- {
- max_posts: zero_up_to_max_int,
- min_posts: zero_up_to_max_int,
- page: zero_up_to_max_int
- }
- end
end
def self.validate?(option, value)
-
if fn = validators[option.to_sym]
fn.call(value)
else
@@ -41,55 +32,58 @@ class TopicQuery
def self.public_valid_options
# For these to work in Ember, add them to `controllers/discovery-sortable.js`
- @public_valid_options ||=
- %i(page
- before
- bumped_before
- topic_ids
- category
- order
- ascending
- min_posts
- max_posts
- status
- filter
- state
- search
- q
- f
- group_name
- tags
- match_all_tags
- no_subcategories
- no_tags
- exclude_tag)
+ @public_valid_options ||= %i[
+ page
+ before
+ bumped_before
+ topic_ids
+ category
+ order
+ ascending
+ min_posts
+ max_posts
+ status
+ filter
+ state
+ search
+ q
+ f
+ group_name
+ tags
+ match_all_tags
+ no_subcategories
+ no_tags
+ exclude_tag
+ ]
end
def self.valid_options
@valid_options ||=
public_valid_options +
- %i(except_topic_ids
- limit
- page
- per_page
- visible
- guardian
- no_definitions
- destination_category_id
- include_all_pms
- include_pms)
+ %i[
+ except_topic_ids
+ limit
+ page
+ per_page
+ visible
+ guardian
+ no_definitions
+ destination_category_id
+ include_all_pms
+ include_pms
+ ]
end
# Maps `order` to a columns in `topics`
SORTABLE_MAPPING = {
- 'likes' => 'like_count',
- 'op_likes' => 'op_likes',
- 'views' => 'views',
- 'posts' => 'posts_count',
- 'activity' => 'bumped_at',
- 'posters' => 'participant_count',
- 'category' => 'category_id',
- 'created' => 'created_at'
+ "likes" => "like_count",
+ "op_likes" => "op_likes",
+ "views" => "views",
+ "posts" => "posts_count",
+ "activity" => "bumped_at",
+ "posters" => "participant_count",
+ "category" => "category_id",
+ "created" => "created_at",
}
cattr_accessor :results_filter_callbacks
@@ -113,9 +107,7 @@ class TopicQuery
def self.apply_custom_filters(results, topic_query)
if @custom_filters
- @custom_filters.each do |key, filter|
- results = filter.call(results, topic_query)
- end
+ @custom_filters.each { |key, filter| results = filter.call(results, topic_query) }
end
results
end
@@ -128,43 +120,46 @@ class TopicQuery
end
def joined_topic_user(list = nil)
- (list || Topic).joins("LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{@user.id.to_i})")
+ (list || Topic).joins(
+ "LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{@user.id.to_i})",
+ )
end
def get_pm_params(topic)
if topic.private_message?
-
- my_group_ids = topic.topic_allowed_groups
- .joins("
+ my_group_ids =
+ topic
+ .topic_allowed_groups
+ .joins(
+ "
LEFT JOIN group_users gu
ON topic_allowed_groups.group_id = gu.group_id
AND gu.user_id = #{@user.id.to_i}
- ")
- .where("gu.group_id IS NOT NULL")
- .pluck(:group_id)
+ ",
+ )
+ .where("gu.group_id IS NOT NULL")
+ .pluck(:group_id)
target_group_ids = topic.topic_allowed_groups.pluck(:group_id)
- target_users = topic
- .topic_allowed_users
+ target_users = topic.topic_allowed_users
if my_group_ids.present?
-
# strip out users in groups you already belong to
- target_users = target_users
- .joins("LEFT JOIN group_users gu ON gu.user_id = topic_allowed_users.user_id AND #{DB.sql_fragment('gu.group_id IN (?)', my_group_ids)}")
- .where('gu.group_id IS NULL')
+ target_users =
+ target_users.joins(
+ "LEFT JOIN group_users gu ON gu.user_id = topic_allowed_users.user_id AND #{DB.sql_fragment("gu.group_id IN (?)", my_group_ids)}",
+ ).where("gu.group_id IS NULL")
end
- target_user_ids = target_users
- .where('NOT topic_allowed_users.user_id = ?', @user.id)
- .pluck(:user_id)
+ target_user_ids =
+ target_users.where("NOT topic_allowed_users.user_id = ?", @user.id).pluck(:user_id)
{
topic: topic,
my_group_ids: my_group_ids,
target_group_ids: target_group_ids,
- target_user_ids: target_user_ids
+ target_user_ids: target_user_ids,
}
end
end
@@ -173,23 +168,29 @@ class TopicQuery
return if !topic.private_message?
return if @user.blank?
- if [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map)
- return
- end
+ return if [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map)
builder = SuggestedTopicsBuilder.new(topic)
pm_params = pm_params || get_pm_params(topic)
if pm_params[:my_group_ids].present?
- builder.add_results(related_messages_group(
- pm_params.merge(count: [6, builder.results_left].max,
- exclude: builder.excluded_topic_ids)
- ))
+ builder.add_results(
+ related_messages_group(
+ pm_params.merge(
+ count: [6, builder.results_left].max,
+ exclude: builder.excluded_topic_ids,
+ ),
+ ),
+ )
else
- builder.add_results(related_messages_user(
- pm_params.merge(count: [6, builder.results_left].max,
- exclude: builder.excluded_topic_ids)
- ))
+ builder.add_results(
+ related_messages_user(
+ pm_params.merge(
+ count: [6, builder.results_left].max,
+ exclude: builder.excluded_topic_ids,
+ ),
+ ),
+ )
end
params = { unordered: true }
@@ -199,12 +200,10 @@ class TopicQuery
# Return a list of suggested topics for a topic
def list_suggested_for(topic, pm_params: nil)
-
# Don't suggest messages unless we have a user, and private messages are
# enabled.
- if topic.private_message? && (
- @user.blank? || [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map)
- )
+ if topic.private_message? &&
+ (@user.blank? || [email protected]_any_groups?(SiteSetting.personal_message_enabled_groups_map))
return
end
@@ -215,37 +214,39 @@ class TopicQuery
# When logged in we start with different results
if @user
if topic.private_message?
+ unless builder.full?
+ builder.add_results(new_messages(pm_params.merge(count: builder.results_left)))
+ end
- builder.add_results(new_messages(
- pm_params.merge(count: builder.results_left)
- )) unless builder.full?
-
- builder.add_results(unread_messages(
- pm_params.merge(count: builder.results_left)
- )) unless builder.full?
-
+ unless builder.full?
+ builder.add_results(unread_messages(pm_params.merge(count: builder.results_left)))
+ end
else
-
builder.add_results(
unread_results(
topic: topic,
per_page: builder.results_left,
- max_age: SiteSetting.suggested_topics_unread_max_days_old
- ), :high
+ max_age: SiteSetting.suggested_topics_unread_max_days_old,
+ ),
+ :high,
)
- builder.add_results(new_results(topic: topic, per_page: builder.category_results_left)) unless builder.full?
+ unless builder.full?
+ builder.add_results(new_results(topic: topic, per_page: builder.category_results_left))
+ end
end
end
if !topic.private_message?
- builder.add_results(random_suggested(topic, builder.results_left, builder.excluded_topic_ids)) unless builder.full?
+ unless builder.full?
+ builder.add_results(
+ random_suggested(topic, builder.results_left, builder.excluded_topic_ids),
+ )
+ end
end
params = { unordered: true }
- if topic.private_message?
- params[:preload_posters] = true
- end
+ params[:preload_posters] = true if topic.private_message?
create_list(:suggested, params, builder.results)
end
@@ -256,7 +257,7 @@ class TopicQuery
def list_read
create_list(:read, unordered: true) do |topics|
- topics.where('tu.last_visited_at IS NOT NULL').order('tu.last_visited_at DESC')
+ topics.where("tu.last_visited_at IS NOT NULL").order("tu.last_visited_at DESC")
end
end
@@ -273,11 +274,11 @@ class TopicQuery
end
def list_posted
- create_list(:posted) { |l| l.where('tu.posted') }
+ create_list(:posted) { |l| l.where("tu.posted") }
end
def list_bookmarks
- create_list(:bookmarks) { |l| l.where('tu.bookmarked') }
+ create_list(:bookmarks) { |l| l.where("tu.bookmarked") }
end
def list_top_for(period)
@@ -303,25 +304,33 @@ class TopicQuery
def list_topics_by(user)
@options[:filtered_to_user] = user.id
- create_list(:user_topics) do |topics|
- topics.where(user_id: user.id)
- end
+ create_list(:user_topics) { |topics| topics.where(user_id: user.id) }
end
def list_group_topics(group)
- list = default_results.where("
+ list =
+ default_results.where(
+ "
topics.user_id IN (
SELECT user_id FROM group_users gu WHERE gu.group_id = ?
)
- ", group.id.to_i)
+ ",
+ group.id.to_i,
+ )
create_list(:group_topics, {}, list)
end
def list_category_topic_ids(category)
query = default_results(category: category.id)
- pinned_ids = query.where('topics.pinned_at IS NOT NULL AND topics.category_id = ?', category.id).limit(nil).order('pinned_at DESC').pluck(:id)
- non_pinned_ids = query.where('topics.pinned_at IS NULL OR topics.category_id <> ?', category.id).pluck(:id)
+ pinned_ids =
+ query
+ .where("topics.pinned_at IS NOT NULL AND topics.category_id = ?", category.id)
+ .limit(nil)
+ .order("pinned_at DESC")
+ .pluck(:id)
+ non_pinned_ids =
+ query.where("topics.pinned_at IS NULL OR topics.category_id <> ?", category.id).pluck(:id)
(pinned_ids + non_pinned_ids)
end
@@ -333,23 +342,26 @@ class TopicQuery
def self.new_filter(list, treat_as_new_topic_start_date: nil, treat_as_new_topic_clause_sql: nil)
if treat_as_new_topic_start_date
- list = list.where("topics.created_at >= :created_at", created_at: treat_as_new_topic_start_date)
+ list =
+ list.where("topics.created_at >= :created_at", created_at: treat_as_new_topic_start_date)
else
list = list.where("topics.created_at >= #{treat_as_new_topic_clause_sql}")
end
- list
- .where("tu.last_read_post_number IS NULL")
- .where("COALESCE(tu.notification_level, :tracking) >= :tracking", tracking: TopicUser.notification_levels[:tracking])
+ list.where("tu.last_read_post_number IS NULL").where(
+ "COALESCE(tu.notification_level, :tracking) >= :tracking",
+ tracking: TopicUser.notification_levels[:tracking],
+ )
end
def self.unread_filter(list, whisperer: false)
col_name = whisperer ? "highest_staff_post_number" : "highest_post_number"
- list
- .where("tu.last_read_post_number < topics.#{col_name}")
- .where("COALESCE(tu.notification_level, :regular) >= :tracking",
- regular: TopicUser.notification_levels[:regular], tracking: TopicUser.notification_levels[:tracking])
+ list.where("tu.last_read_post_number < topics.#{col_name}").where(
+ "COALESCE(tu.notification_level, :regular) >= :tracking",
+ regular: TopicUser.notification_levels[:regular],
+ tracking: TopicUser.notification_levels[:tracking],
+ )
end
# Any changes here will need to be reflected in `lib/topic-list-tracked-filter.js` for the `isTrackedTopic` function on
@@ -375,8 +387,7 @@ class TopicQuery
)
SQL
- if SiteSetting.tagging_enabled
- sql << <<~SQL
+ sql << <<~SQL if SiteSetting.tagging_enabled
OR topics.id IN (
SELECT tt.topic_id FROM topic_tags tt WHERE tt.tag_id IN (
SELECT tu.tag_id
@@ -385,21 +396,17 @@ class TopicQuery
)
)
SQL
- end
- list.where(
- sql,
- user_id: user_id,
- tracking: NotificationLevels.all[:tracking]
- )
+ list.where(sql, user_id: user_id, tracking: NotificationLevels.all[:tracking])
end
def prioritize_pinned_topics(topics, options)
- pinned_clause = if options[:category_id]
- +"topics.category_id = #{options[:category_id].to_i} AND"
- else
- +"pinned_globally AND "
- end
+ pinned_clause =
+ if options[:category_id]
+ +"topics.category_id = #{options[:category_id].to_i} AND"
+ else
+ +"pinned_globally AND "
+ end
pinned_clause << " pinned_at IS NOT NULL "
@@ -421,7 +428,6 @@ class TopicQuery
offset = 0 unless offset > 0
unpinned_topics.offset(offset).to_a
end
-
end
def create_list(filter, options = {}, topics = nil)
@@ -430,9 +436,8 @@ class TopicQuery
topics = yield(topics) if block_given?
options = options.merge(@options)
- if ["activity", "default"].include?(options[:order] || "activity") &&
- !options[:unordered] &&
- filter != :private_messages
+ if %w[activity default].include?(options[:order] || "activity") && !options[:unordered] &&
+ filter != :private_messages
topics = prioritize_pinned_topics(topics, options)
end
@@ -450,10 +455,7 @@ class TopicQuery
translations = TopicPostersSummary.translations
topics.each do |t|
- t.posters = t.posters_summary(
- user_lookup: user_lookup,
- translations: translations
- )
+ t.posters = t.posters_summary(user_lookup: user_lookup, translations: translations)
end
end
@@ -494,16 +496,16 @@ class TopicQuery
end
def unread_results(options = {})
- result = TopicQuery.unread_filter(
+ result =
+ TopicQuery.unread_filter(
default_results(options.reverse_merge(unordered: true)),
- whisperer: @user&.whisperer?)
- .order('CASE WHEN topics.user_id = tu.user_id THEN 1 ELSE 2 END')
+ whisperer: @user&.whisperer?,
+ ).order("CASE WHEN topics.user_id = tu.user_id THEN 1 ELSE 2 END")
if @user
# micro optimisation so we don't load up all of user stats which we do not need
- unread_at = DB.query_single(
- "select first_unread_at from user_stats where user_id = ?",
- @user.id).first
+ unread_at =
+ DB.query_single("select first_unread_at from user_stats where user_id = ?", @user.id).first
if max_age = options[:max_age]
max_age_date = max_age.days.ago
@@ -526,10 +528,11 @@ class TopicQuery
def new_results(options = {})
# TODO does this make sense or should it be ordered on created_at
# it is ordering on bumped_at now
- result = TopicQuery.new_filter(
- default_results(options.reverse_merge(unordered: true)),
- treat_as_new_topic_start_date: @user.user_option.treat_as_new_topic_start_date
- )
+ result =
+ TopicQuery.new_filter(
+ default_results(options.reverse_merge(unordered: true)),
+ treat_as_new_topic_start_date: @user.user_option.treat_as_new_topic_start_date,
+ )
result = remove_muted(result, @user, options)
result = remove_dismissed(result, @user)
@@ -547,7 +550,6 @@ class TopicQuery
end
def apply_shared_drafts(result, category_id, options)
-
# PERF: avoid any penalty if there are no shared drafts enabled
# on some sites the cost can be high eg: gearbox
return result if SiteSetting.shared_drafts_category == ""
@@ -563,47 +565,56 @@ class TopicQuery
return result.where(id: topic_ids)
end
- if viewing_shared
- return result.includes(:shared_draft).references(:shared_draft)
- end
-
+ return result.includes(:shared_draft).references(:shared_draft) if viewing_shared
elsif viewing_shared
- return result.joins('LEFT OUTER JOIN shared_drafts sd ON sd.topic_id = topics.id').where('sd.id IS NULL')
+ return(
+ result.joins("LEFT OUTER JOIN shared_drafts sd ON sd.topic_id = topics.id").where(
+ "sd.id IS NULL",
+ )
+ )
end
- result.where('topics.category_id != ?', drafts_category_id)
+ result.where("topics.category_id != ?", drafts_category_id)
end
def apply_ordering(result, options)
- sort_column = SORTABLE_MAPPING[options[:order]] || 'default'
+ sort_column = SORTABLE_MAPPING[options[:order]] || "default"
sort_dir = (options[:ascending] == "true") ? "ASC" : "DESC"
# If we are sorting in the default order desc, we should consider including pinned
# topics. Otherwise, just use bumped_at.
- if sort_column == 'default'
- if sort_dir == 'DESC'
+ if sort_column == "default"
+ if sort_dir == "DESC"
# If something requires a custom order, for example "unread" which sorts the least read
# to the top, do nothing
return result if options[:unordered]
end
- sort_column = 'bumped_at'
+ sort_column = "bumped_at"
end
# If we are sorting by category, actually use the name
- if sort_column == 'category_id'
+ if sort_column == "category_id"
# TODO forces a table scan, slow
return result.references(:categories).order(<<~SQL)
CASE WHEN categories.id = #{SiteSetting.uncategorized_category_id.to_i} THEN '' ELSE categories.name END #{sort_dir}
SQL
end
- if sort_column == 'op_likes'
- return result.includes(:first_post).order("(SELECT like_count FROM posts p3 WHERE p3.topic_id = topics.id AND p3.post_number = 1) #{sort_dir}")
+ if sort_column == "op_likes"
+ return(
+ result.includes(:first_post).order(
+ "(SELECT like_count FROM posts p3 WHERE p3.topic_id = topics.id AND p3.post_number = 1) #{sort_dir}",
+ )
+ )
end
- if sort_column.start_with?('custom_fields')
- field = sort_column.split('.')[1]
- return result.order("(SELECT CASE WHEN EXISTS (SELECT true FROM topic_custom_fields tcf WHERE tcf.topic_id::integer = topics.id::integer AND tcf.name = '#{field}') THEN (SELECT value::integer FROM topic_custom_fields tcf WHERE tcf.topic_id::integer = topics.id::integer AND tcf.name = '#{field}') ELSE 0 END) #{sort_dir}")
+ if sort_column.start_with?("custom_fields")
+ field = sort_column.split(".")[1]
+ return(
+ result.order(
+ "(SELECT CASE WHEN EXISTS (SELECT true FROM topic_custom_fields tcf WHERE tcf.topic_id::integer = topics.id::integer AND tcf.name = '#{field}') THEN (SELECT value::integer FROM topic_custom_fields tcf WHERE tcf.topic_id::integer = topics.id::integer AND tcf.name = '#{field}') ELSE 0 END) #{sort_dir}",
+ )
+ )
end
result.order("topics.#{sort_column} #{sort_dir}")
@@ -615,9 +626,7 @@ class TopicQuery
if category_id == 0
category_id =
- Category
- .where(slug: category_id_or_slug, parent_category_id: nil)
- .pluck_first(:id)
+ Category.where(slug: category_id_or_slug, parent_category_id: nil).pluck_first(:id)
end
category_id
@@ -636,19 +645,22 @@ class TopicQuery
result = Topic.unscoped.includes(:category)
if @user
- result = result.joins("LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{@user.id.to_i})")
- .references('tu')
+ result =
+ result.joins(
+ "LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{@user.id.to_i})",
+ ).references("tu")
end
category_id = get_category_id(options[:category])
@options[:category_id] = category_id
if category_id
if options[:no_subcategories]
- result = result.where('topics.category_id = ?', category_id)
+ result = result.where("topics.category_id = ?", category_id)
else
result = result.where("topics.category_id IN (?)", Category.subcategory_ids(category_id))
if !SiteSetting.show_category_definitions_in_topic_lists
- result = result.where("categories.topic_id <> topics.id OR topics.category_id = ?", category_id)
+ result =
+ result.where("categories.topic_id <> topics.id OR topics.category_id = ?", category_id)
end
end
result = result.references(:categories)
@@ -656,13 +668,14 @@ class TopicQuery
if !@options[:order]
filter = (options[:filter] || options[:f])
# category default sort order
- sort_order, sort_ascending = Category.where(id: category_id).pluck_first(:sort_order, :sort_ascending)
- if sort_order && (filter.blank? || [:latest, :unseen].include?(filter))
+ sort_order, sort_ascending =
+ Category.where(id: category_id).pluck_first(:sort_order, :sort_ascending)
+ if sort_order && (filter.blank? || %i[latest unseen].include?(filter))
options[:order] = sort_order
- options[:ascending] = !!sort_ascending ? 'true' : 'false'
+ options[:ascending] = !!sort_ascending ? "true" : "false"
else
- options[:order] = 'default'
- options[:ascending] = 'false'
+ options[:order] = "default"
+ options[:ascending] = "false"
end
end
end
@@ -675,13 +688,14 @@ class TopicQuery
if tags_arg && tags_arg.size > 0
tags_arg = tags_arg.split if String === tags_arg
- tags_arg = tags_arg.map do |t|
- if String === t
- t.downcase
- else
- t
+ tags_arg =
+ tags_arg.map do |t|
+ if String === t
+ t.downcase
+ else
+ t
+ end
end
- end
tags_query = tags_arg[0].is_a?(String) ? Tag.where_name(tags_arg) : Tag.where(id: tags_arg)
tags = tags_query.select(:id, :target_tag_id).map { |t| t.target_tag_id || t.id }.uniq
@@ -690,8 +704,11 @@ class TopicQuery
# ALL of the given tags:
if tags_arg.length == tags.length
tags.each_with_index do |tag, index|
- sql_alias = ['t', index].join
- result = result.joins("INNER JOIN topic_tags #{sql_alias} ON #{sql_alias}.topic_id = topics.id AND #{sql_alias}.tag_id = #{tag}")
+ sql_alias = ["t", index].join
+ result =
+ result.joins(
+ "INNER JOIN topic_tags #{sql_alias} ON #{sql_alias}.topic_id = topics.id AND #{sql_alias}.tag_id = #{tag}",
+ )
end
else
result = result.none # don't return any results unless all tags exist in the database
@@ -704,14 +721,12 @@ class TopicQuery
# TODO: this is very side-effecty and should be changed
# It is done cause further up we expect normalized tags
@options[:tags] = tags
-
elsif @options[:no_tags]
# the following will do: ("topics"."id" NOT IN (SELECT DISTINCT "topic_tags"."topic_id" FROM "topic_tags"))
result = result.where.not(id: TopicTag.distinct.pluck(:topic_id))
end
- if @options[:exclude_tag].present?
- result = result.where(<<~SQL, name: @options[:exclude_tag])
+ result = result.where(<<~SQL, name: @options[:exclude_tag]) if @options[:exclude_tag].present?
topics.id NOT IN (
SELECT topic_tags.topic_id
FROM topic_tags
@@ -719,7 +734,6 @@ class TopicQuery
WHERE tags.name = :name
)
SQL
- end
end
result = apply_ordering(result, options)
@@ -727,11 +741,12 @@ class TopicQuery
all_listable_topics = @guardian.filter_allowed_categories(Topic.unscoped.listable_topics)
if options[:include_pms] || options[:include_all_pms]
- all_pm_topics = if options[:include_all_pms] && @guardian.is_admin?
- Topic.unscoped.private_messages
- else
- Topic.unscoped.private_messages_for_user(@user)
- end
+ all_pm_topics =
+ if options[:include_all_pms] && @guardian.is_admin?
+ Topic.unscoped.private_messages
+ else
+ Topic.unscoped.private_messages_for_user(@user)
+ end
result = result.merge(all_listable_topics.or(all_pm_topics))
else
result = result.merge(all_listable_topics)
@@ -739,12 +754,15 @@ class TopicQuery
# Don't include the category topics if excluded
if options[:no_definitions]
- result = result.where('COALESCE(categories.topic_id, 0) <> topics.id')
+ result = result.where("COALESCE(categories.topic_id, 0) <> topics.id")
end
result = result.limit(options[:per_page]) unless options[:limit] == false
result = result.visible if options[:visible]
- result = result.where.not(topics: { id: options[:except_topic_ids] }).references(:topics) if options[:except_topic_ids]
+ result =
+ result.where.not(topics: { id: options[:except_topic_ids] }).references(:topics) if options[
+ :except_topic_ids
+ ]
if options[:page]
offset = options[:page].to_i * options[:per_page]
@@ -752,86 +770,95 @@ class TopicQuery
end
if options[:topic_ids]
- result = result.where('topics.id in (?)', options[:topic_ids]).references(:topics)
+ result = result.where("topics.id in (?)", options[:topic_ids]).references(:topics)
end
if search = options[:search].presence
- result = result.where("topics.id in (select pp.topic_id from post_search_data pd join posts pp on pp.id = pd.post_id where pd.search_data @@ #{Search.ts_query(term: search.to_s)})")
+ result =
+ result.where(
+ "topics.id in (select pp.topic_id from post_search_data pd join posts pp on pp.id = pd.post_id where pd.search_data @@ #{Search.ts_query(term: search.to_s)})",
+ )
end
# NOTE protect against SYM attack can be removed with Ruby 2.2
#
state = options[:state]
- if @user && state &&
- TopicUser.notification_levels.keys.map(&:to_s).include?(state)
+ if @user && state && TopicUser.notification_levels.keys.map(&:to_s).include?(state)
level = TopicUser.notification_levels[state.to_sym]
- result = result.where('topics.id IN (
+ result =
+ result.where(
+ "topics.id IN (
SELECT topic_id
FROM topic_users
WHERE user_id = ? AND
- notification_level = ?)', @user.id, level)
+ notification_level = ?)",
+ @user.id,
+ level,
+ )
end
require_deleted_clause = true
if before = options[:before]
if (before = before.to_i) > 0
- result = result.where('topics.created_at < ?', before.to_i.days.ago)
+ result = result.where("topics.created_at < ?", before.to_i.days.ago)
end
end
if bumped_before = options[:bumped_before]
if (bumped_before = bumped_before.to_i) > 0
- result = result.where('topics.bumped_at < ?', bumped_before.to_i.days.ago)
+ result = result.where("topics.bumped_at < ?", bumped_before.to_i.days.ago)
end
end
if status = options[:status]
case status
- when 'open'
- result = result.where('NOT topics.closed AND NOT topics.archived')
- when 'closed'
- result = result.where('topics.closed')
- when 'archived'
- result = result.where('topics.archived')
- when 'listed'
- result = result.where('topics.visible')
- when 'unlisted'
- result = result.where('NOT topics.visible')
- when 'deleted'
+ when "open"
+ result = result.where("NOT topics.closed AND NOT topics.archived")
+ when "closed"
+ result = result.where("topics.closed")
+ when "archived"
+ result = result.where("topics.archived")
+ when "listed"
+ result = result.where("topics.visible")
+ when "unlisted"
+ result = result.where("NOT topics.visible")
+ when "deleted"
category = Category.find_by(id: options[:category])
if @guardian.can_see_deleted_topics?(category)
- result = result.where('topics.deleted_at IS NOT NULL')
+ result = result.where("topics.deleted_at IS NOT NULL")
require_deleted_clause = false
end
end
end
if (filter = (options[:filter] || options[:f])) && @user
- action =
- if filter == "liked"
- PostActionType.types[:like]
- end
+ action = (PostActionType.types[:like] if filter == "liked")
if action
- result = result.where('topics.id IN (SELECT pp.topic_id
+ result =
+ result.where(
+ "topics.id IN (SELECT pp.topic_id
FROM post_actions pa
JOIN posts pp ON pp.id = pa.post_id
WHERE pa.user_id = :user_id AND
pa.post_action_type_id = :action AND
pa.deleted_at IS NULL
- )', user_id: @user.id,
- action: action
- )
+ )",
+ user_id: @user.id,
+ action: action,
+ )
end
- if filter == "tracked"
- result = TopicQuery.tracked_filter(result, @user.id)
- end
+ result = TopicQuery.tracked_filter(result, @user.id) if filter == "tracked"
end
- result = result.where('topics.deleted_at IS NULL') if require_deleted_clause
- result = result.where('topics.posts_count <= ?', options[:max_posts]) if options[:max_posts].present?
- result = result.where('topics.posts_count >= ?', options[:min_posts]) if options[:min_posts].present?
+ result = result.where("topics.deleted_at IS NULL") if require_deleted_clause
+ result = result.where("topics.posts_count <= ?", options[:max_posts]) if options[
+ :max_posts
+ ].present?
+ result = result.where("topics.posts_count >= ?", options[:min_posts]) if options[
+ :min_posts
+ ].present?
result = TopicQuery.apply_custom_filters(result, self)
@@ -846,7 +873,11 @@ class TopicQuery
def remove_muted_topics(list, user)
if user
- list = list.where('COALESCE(tu.notification_level,1) > :muted', muted: TopicUser.notification_levels[:muted])
+ list =
+ list.where(
+ "COALESCE(tu.notification_level,1) > :muted",
+ muted: TopicUser.notification_levels[:muted],
+ )
end
list
@@ -856,24 +887,30 @@ class TopicQuery
category_id = get_category_id(opts[:exclude]) if opts
if user
- list = list
- .references("cu")
- .joins("LEFT JOIN category_users ON category_users.category_id = topics.category_id AND category_users.user_id = #{user.id}")
- .where("topics.category_id = :category_id
+ list =
+ list
+ .references("cu")
+ .joins(
+ "LEFT JOIN category_users ON category_users.category_id = topics.category_id AND category_users.user_id = #{user.id}",
+ )
+ .where(
+ "topics.category_id = :category_id
OR
(COALESCE(category_users.notification_level, :default) <> :muted AND (topics.category_id IS NULL OR topics.category_id NOT IN(:indirectly_muted_category_ids)))
OR tu.notification_level > :regular",
- category_id: category_id || -1,
- default: CategoryUser.default_notification_level,
- indirectly_muted_category_ids: CategoryUser.indirectly_muted_category_ids(user).presence || [-1],
- muted: CategoryUser.notification_levels[:muted],
- regular: TopicUser.notification_levels[:regular])
+ category_id: category_id || -1,
+ default: CategoryUser.default_notification_level,
+ indirectly_muted_category_ids:
+ CategoryUser.indirectly_muted_category_ids(user).presence || [-1],
+ muted: CategoryUser.notification_levels[:muted],
+ regular: TopicUser.notification_levels[:regular],
+ )
elsif SiteSetting.mute_all_categories_by_default
category_ids = [
SiteSetting.default_categories_watching.split("|"),
SiteSetting.default_categories_tracking.split("|"),
SiteSetting.default_categories_watching_first_post.split("|"),
- SiteSetting.default_categories_normal.split("|")
+ SiteSetting.default_categories_normal.split("|"),
].flatten.map(&:to_i)
category_ids << category_id if category_id.present? && category_ids.exclude?(category_id)
@@ -889,7 +926,7 @@ class TopicQuery
end
def self.remove_muted_tags(list, user, opts = {})
- if !SiteSetting.tagging_enabled || SiteSetting.remove_muted_tags_from_latest == 'never'
+ if !SiteSetting.tagging_enabled || SiteSetting.remove_muted_tags_from_latest == "never"
return list
end
@@ -900,70 +937,79 @@ class TopicQuery
else
muted_tag_names = SiteSetting.default_tags_muted.split("|")
- if muted_tag_names.present?
- muted_tag_ids = Tag.where(name: muted_tag_names).pluck(:id)
- end
+ muted_tag_ids = Tag.where(name: muted_tag_names).pluck(:id) if muted_tag_names.present?
end
- if muted_tag_ids.blank?
- return list
- end
+ return list if muted_tag_ids.blank?
# if viewing the topic list for a muted tag, show all the topics
if !opts[:no_tags] && opts[:tags].present?
- return list if TagUser.lookup(user, :muted).joins(:tag).where('lower(tags.name) = ?', opts[:tags].first.downcase).exists?
+ if TagUser
+ .lookup(user, :muted)
+ .joins(:tag)
+ .where("lower(tags.name) = ?", opts[:tags].first.downcase)
+ .exists?
+ return list
+ end
end
- if SiteSetting.remove_muted_tags_from_latest == 'always'
- list = list.where("
+ if SiteSetting.remove_muted_tags_from_latest == "always"
+ list =
+ list.where(
+ "
NOT EXISTS(
SELECT 1
FROM topic_tags tt
WHERE tt.tag_id IN (:tag_ids)
- AND tt.topic_id = topics.id)", tag_ids: muted_tag_ids)
+ AND tt.topic_id = topics.id)",
+ tag_ids: muted_tag_ids,
+ )
else
- list = list.where("
+ list =
+ list.where(
+ "
EXISTS (
SELECT 1
FROM topic_tags tt
WHERE tt.tag_id NOT IN (:tag_ids)
AND tt.topic_id = topics.id
- ) OR NOT EXISTS (SELECT 1 FROM topic_tags tt WHERE tt.topic_id = topics.id)", tag_ids: muted_tag_ids)
+ ) OR NOT EXISTS (SELECT 1 FROM topic_tags tt WHERE tt.topic_id = topics.id)",
+ tag_ids: muted_tag_ids,
+ )
end
end
def remove_dismissed(list, user)
if user
- list
- .joins(<<~SQL)
+ list.joins(<<~SQL).where("dismissed_topic_users.id IS NULL")
LEFT JOIN dismissed_topic_users
ON dismissed_topic_users.topic_id = topics.id
AND dismissed_topic_users.user_id = #{user.id.to_i}
SQL
- .where("dismissed_topic_users.id IS NULL")
else
list
end
end
def new_messages(params)
- TopicQuery
- .new_filter(
- messages_for_groups_or_user(params[:my_group_ids]),
- treat_as_new_topic_start_date: Time.at(SiteSetting.min_new_topics_time).to_datetime
- )
- .limit(params[:count])
+ TopicQuery.new_filter(
+ messages_for_groups_or_user(params[:my_group_ids]),
+ treat_as_new_topic_start_date: Time.at(SiteSetting.min_new_topics_time).to_datetime,
+ ).limit(params[:count])
end
def unread_messages(params)
- query = TopicQuery.unread_filter(
- messages_for_groups_or_user(params[:my_group_ids]),
- whisperer: @user.whisperer?
- )
+ query =
+ TopicQuery.unread_filter(
+ messages_for_groups_or_user(params[:my_group_ids]),
+ whisperer: @user.whisperer?,
+ )
first_unread_pm_at =
if params[:my_group_ids].present?
- GroupUser.where(user_id: @user.id, group_id: params[:my_group_ids]).minimum(:first_unread_pm_at)
+ GroupUser.where(user_id: @user.id, group_id: params[:my_group_ids]).minimum(
+ :first_unread_pm_at,
+ )
else
UserStat.where(user_id: @user.id).pluck_first(:first_unread_pm_at)
end
@@ -989,20 +1035,24 @@ class TopicQuery
if user_ids.present?
messages =
- messages.joins("
+ messages.joins(
+ "
LEFT JOIN topic_allowed_users ta2
ON topics.id = ta2.topic_id
- AND #{DB.sql_fragment('ta2.user_id IN (?)', user_ids)}
- ")
+ AND #{DB.sql_fragment("ta2.user_id IN (?)", user_ids)}
+ ",
+ )
end
if group_ids.present?
messages =
- messages.joins("
+ messages.joins(
+ "
LEFT JOIN topic_allowed_groups tg2
ON topics.id = tg2.topic_id
- AND #{DB.sql_fragment('tg2.group_id IN (?)', group_ids)}
- ")
+ AND #{DB.sql_fragment("tg2.group_id IN (?)", group_ids)}
+ ",
+ )
end
messages =
@@ -1017,39 +1067,40 @@ class TopicQuery
def messages_for_groups_or_user(group_ids)
if group_ids.present?
- base_messages
- .joins("
+ base_messages.joins(
+ "
LEFT JOIN (
SELECT * FROM topic_allowed_groups _tg
LEFT JOIN group_users gu
ON gu.user_id = #{@user.id.to_i}
AND gu.group_id = _tg.group_id
- WHERE #{DB.sql_fragment('gu.group_id IN (?)', group_ids)}
+ WHERE #{DB.sql_fragment("gu.group_id IN (?)", group_ids)}
) tg ON topics.id = tg.topic_id
- ")
- .where("tg.topic_id IS NOT NULL")
+ ",
+ ).where("tg.topic_id IS NOT NULL")
else
messages_for_user
end
end
def messages_for_user
- base_messages
- .joins("
+ base_messages.joins(
+ "
LEFT JOIN topic_allowed_users ta
ON topics.id = ta.topic_id
AND ta.user_id = #{@user.id.to_i}
- ")
- .where("ta.topic_id IS NOT NULL")
+ ",
+ ).where("ta.topic_id IS NOT NULL")
end
def base_messages
- query = Topic
- .where('topics.archetype = ?', Archetype.private_message)
- .joins("LEFT JOIN topic_users tu ON topics.id = tu.topic_id AND tu.user_id = #{@user.id.to_i}")
+ query =
+ Topic.where("topics.archetype = ?", Archetype.private_message).joins(
+ "LEFT JOIN topic_users tu ON topics.id = tu.topic_id AND tu.user_id = #{@user.id.to_i}",
+ )
query = query.includes(:tags) if SiteSetting.tagging_enabled
- query.order('topics.bumped_at DESC')
+ query.order("topics.bumped_at DESC")
end
def random_suggested(topic, count, excluded_topic_ids = [])
@@ -1060,14 +1111,16 @@ class TopicQuery
else
excluded_topic_ids += Category.topic_ids.to_a
end
- result = result.where("topics.id NOT IN (?)", excluded_topic_ids) unless excluded_topic_ids.empty?
+ result =
+ result.where("topics.id NOT IN (?)", excluded_topic_ids) unless excluded_topic_ids.empty?
result = remove_muted_categories(result, @user)
result = remove_muted_topics(result, @user)
# If we are in a category, prefer it for the random results
if topic.category_id
- result = result.order("CASE WHEN topics.category_id = #{topic.category_id.to_i} THEN 0 ELSE 1 END")
+ result =
+ result.order("CASE WHEN topics.category_id = #{topic.category_id.to_i} THEN 0 ELSE 1 END")
end
# Best effort, it over selects, however if you have a high number
@@ -1086,10 +1139,13 @@ class TopicQuery
def suggested_ordering(result, options)
# Prefer unread in the same category
if options[:topic] && options[:topic].category_id
- result = result.order("CASE WHEN topics.category_id = #{options[:topic].category_id.to_i} THEN 0 ELSE 1 END")
+ result =
+ result.order(
+ "CASE WHEN topics.category_id = #{options[:topic].category_id.to_i} THEN 0 ELSE 1 END",
+ )
end
- result.order('topics.bumped_at DESC')
+ result.order("topics.bumped_at DESC")
end
private
diff --git a/lib/topic_query/private_message_lists.rb b/lib/topic_query/private_message_lists.rb
index c8883169a97..0c4874ba2a8 100644
--- a/lib/topic_query/private_message_lists.rb
+++ b/lib/topic_query/private_message_lists.rb
@@ -21,7 +21,8 @@ class TopicQuery
def list_private_messages_archive(user)
list = private_messages_for(user, :user)
- list = list.joins(:user_archived_messages).where('user_archived_messages.user_id = ?', user.id)
+ list =
+ list.joins(:user_archived_messages).where("user_archived_messages.user_id = ?", user.id)
create_list(:private_messages, {}, list)
end
@@ -96,9 +97,9 @@ class TopicQuery
def list_private_messages_warnings(user)
list = private_messages_for(user, :user)
- list = list.where('topics.subtype = ?', TopicSubtype.moderator_warning)
+ list = list.where("topics.subtype = ?", TopicSubtype.moderator_warning)
# Exclude official warnings that the user created, instead of received
- list = list.where('topics.user_id <> ?', user.id)
+ list = list.where("topics.user_id <> ?", user.id)
create_list(:private_messages, {}, list)
end
@@ -110,21 +111,29 @@ class TopicQuery
result = result.includes(:tags) if SiteSetting.tagging_enabled
if type == :group
- result = result.joins(
- "INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')"
- )
+ result =
+ result.joins(
+ "INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')",
+ )
unless user.admin?
- result = result.joins("INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}")
+ result =
+ result.joins(
+ "INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}",
+ )
end
elsif type == :user
- result = result.where("topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = ?)", user.id.to_i)
+ result =
+ result.where(
+ "topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = ?)",
+ user.id.to_i,
+ )
elsif type == :all
group_ids = group_with_messages_ids(user)
result =
- if group_ids.present?
- result.where(<<~SQL, user.id.to_i, group_ids)
+ if group_ids.present?
+ result.where(<<~SQL, user.id.to_i, group_ids)
topics.id IN (
SELECT topic_id
FROM topic_allowed_users
@@ -134,18 +143,22 @@ class TopicQuery
WHERE group_id IN (?)
)
SQL
- else
- result.joins(<<~SQL)
+ else
+ result.joins(<<~SQL)
INNER JOIN topic_allowed_users tau
ON tau.topic_id = topics.id
AND tau.user_id = #{user.id.to_i}
SQL
- end
+ end
end
- result = result.joins("LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{user.id.to_i})")
- .order("topics.bumped_at DESC")
- .private_messages
+ result =
+ result
+ .joins(
+ "LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{user.id.to_i})",
+ )
+ .order("topics.bumped_at DESC")
+ .private_messages
result = result.limit(options[:per_page]) unless options[:limit] == false
result = result.visible if options[:visible] || @user.nil? || @user.regular?
@@ -159,38 +172,32 @@ class TopicQuery
def list_private_messages_tag(user)
list = private_messages_for(user, :all)
- list = list.joins("JOIN topic_tags tt ON tt.topic_id = topics.id
- JOIN tags t ON t.id = tt.tag_id AND t.name = '#{@options[:tags][0]}'")
+ list =
+ list.joins(
+ "JOIN topic_tags tt ON tt.topic_id = topics.id
+ JOIN tags t ON t.id = tt.tag_id AND t.name = '#{@options[:tags][0]}'",
+ )
create_list(:private_messages, {}, list)
end
def filter_private_messages_unread(user, type)
- list = TopicQuery.unread_filter(
- private_messages_for(user, type),
- whisperer: user.whisperer?
- )
+ list = TopicQuery.unread_filter(private_messages_for(user, type), whisperer: user.whisperer?)
first_unread_pm_at =
case type
when :user
user_first_unread_pm_at(user)
when :group
- GroupUser
- .where(user: user, group: group)
- .pluck_first(:first_unread_pm_at)
+ GroupUser.where(user: user, group: group).pluck_first(:first_unread_pm_at)
else
user_first_unread_pm_at = user_first_unread_pm_at(user)
- group_first_unread_pm_at = GroupUser
- .where(user: user)
- .minimum(:first_unread_pm_at)
+ group_first_unread_pm_at = GroupUser.where(user: user).minimum(:first_unread_pm_at)
[user_first_unread_pm_at, group_first_unread_pm_at].compact.min
end
- if first_unread_pm_at
- list = list.where("topics.updated_at >= ?", first_unread_pm_at)
- end
+ list = list.where("topics.updated_at >= ?", first_unread_pm_at) if first_unread_pm_at
list
end
@@ -198,7 +205,7 @@ class TopicQuery
def filter_private_message_new(user, type)
TopicQuery.new_filter(
private_messages_for(user, type),
- treat_as_new_topic_start_date: user.user_option.treat_as_new_topic_start_date
+ treat_as_new_topic_start_date: user.user_option.treat_as_new_topic_start_date,
)
end
@@ -208,12 +215,12 @@ class TopicQuery
group_id = group.id
return list if group_id.nil?
- selected_values = list.select_values.empty? ? ['topics.*'] : list.select_values
+ selected_values = list.select_values.empty? ? ["topics.*"] : list.select_values
selected_values << "COALESCE(tg.last_read_post_number, 0) AS last_read_post_number"
- list
- .joins("LEFT OUTER JOIN topic_groups tg ON topics.id = tg.topic_id AND tg.group_id = #{group_id}")
- .select(*selected_values)
+ list.joins(
+ "LEFT OUTER JOIN topic_groups tg ON topics.id = tg.topic_id AND tg.group_id = #{group_id}",
+ ).select(*selected_values)
end
def filter_archived(list, user, archived: true)
@@ -249,9 +256,10 @@ class TopicQuery
end
def not_archived(list, user)
- list.joins("LEFT JOIN user_archived_messages um
- ON um.user_id = #{user.id.to_i} AND um.topic_id = topics.id")
- .where('um.user_id IS NULL')
+ list.joins(
+ "LEFT JOIN user_archived_messages um
+ ON um.user_id = #{user.id.to_i} AND um.topic_id = topics.id",
+ ).where("um.user_id IS NULL")
end
def not_archived_in_groups(list)
@@ -269,12 +277,10 @@ class TopicQuery
end
def group
- @group ||= begin
- Group
- .where('name ilike ?', @options[:group_name])
- .select(:id, :publish_read_state)
- .first
- end
+ @group ||=
+ begin
+ Group.where("name ilike ?", @options[:group_name]).select(:id, :publish_read_state).first
+ end
end
def user_first_unread_pm_at(user)
diff --git a/lib/topic_query_params.rb b/lib/topic_query_params.rb
index 5c0175a8ba7..291886604d6 100644
--- a/lib/topic_query_params.rb
+++ b/lib/topic_query_params.rb
@@ -8,15 +8,15 @@ module TopicQueryParams
TopicQuery.public_valid_options.each do |key|
if params.key?(key)
val = options[key] = params[key]
- if !TopicQuery.validate?(key, val)
- raise Discourse::InvalidParameters.new key
- end
+ raise Discourse::InvalidParameters.new key if !TopicQuery.validate?(key, val)
end
end
# hacky columns get special handling
options[:topic_ids] = param_to_integer_list(:topic_ids)
- options[:no_subcategories] = options[:no_subcategories] == 'true' if options[:no_subcategories].present?
+ options[:no_subcategories] = options[:no_subcategories] == "true" if options[
+ :no_subcategories
+ ].present?
if hide_welcome_topic?
options[:except_topic_ids] ||= []
diff --git a/lib/topic_retriever.rb b/lib/topic_retriever.rb
index 88d4d7c8e7a..b798df6cd7b 100644
--- a/lib/topic_retriever.rb
+++ b/lib/topic_retriever.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class TopicRetriever
-
def initialize(embed_url, opts = nil)
@embed_url = embed_url
@opts = opts || {}
@@ -41,7 +40,9 @@ class TopicRetriever
def fetch_http
if @author_username.nil?
- username = SiteSetting.embed_by_username.presence || SiteSetting.site_contact_username.presence || Discourse.system_user.username
+ username =
+ SiteSetting.embed_by_username.presence || SiteSetting.site_contact_username.presence ||
+ Discourse.system_user.username
else
username = @author_username
end
@@ -51,5 +52,4 @@ class TopicRetriever
TopicEmbed.import_remote(user, @embed_url)
end
-
end
diff --git a/lib/topic_subtype.rb b/lib/topic_subtype.rb
index c20f639271e..e4c4621c81e 100644
--- a/lib/topic_subtype.rb
+++ b/lib/topic_subtype.rb
@@ -11,7 +11,7 @@ class TopicSubtype
end
def attributes
- { 'id' => @id, 'options' => @options }
+ { "id" => @id, "options" => @options }
end
def self.list
@@ -20,27 +20,27 @@ class TopicSubtype
end
def self.user_to_user
- 'user_to_user'
+ "user_to_user"
end
def self.system_message
- 'system_message'
+ "system_message"
end
def self.moderator_warning
- 'moderator_warning'
+ "moderator_warning"
end
def self.notify_moderators
- 'notify_moderators'
+ "notify_moderators"
end
def self.notify_user
- 'notify_user'
+ "notify_user"
end
def self.pending_users_reminder
- 'pending_users'
+ "pending_users"
end
def self.register(name, options = {})
@@ -48,10 +48,9 @@ class TopicSubtype
@subtypes[name] = TopicSubtype.new(name, options)
end
- register 'user_to_user'
- register 'system_message'
- register 'moderator_warning'
- register 'notify_moderators'
- register 'notify_user'
-
+ register "user_to_user"
+ register "system_message"
+ register "moderator_warning"
+ register "notify_moderators"
+ register "notify_user"
end
diff --git a/lib/topic_upload_security_manager.rb b/lib/topic_upload_security_manager.rb
index 3425297a2d0..aec874804bf 100644
--- a/lib/topic_upload_security_manager.rb
+++ b/lib/topic_upload_security_manager.rb
@@ -27,14 +27,17 @@ class TopicUploadSecurityManager
Rails.logger.debug("Updating upload security in topic #{@topic.id} - post #{post.id}")
post.topic = @topic
- secure_status_did_change = post.owned_uploads_via_access_control.any? do |upload|
- # we have already got the post preloaded so we may as well
- # attach it here to avoid another load in UploadSecurity
- upload.access_control_post = post
- upload.update_secure_status(source: "topic upload security")
- end
+ secure_status_did_change =
+ post.owned_uploads_via_access_control.any? do |upload|
+ # we have already got the post preloaded so we may as well
+ # attach it here to avoid another load in UploadSecurity
+ upload.access_control_post = post
+ upload.update_secure_status(source: "topic upload security")
+ end
post.rebake! if secure_status_did_change
- Rails.logger.debug("Security updated & rebake complete in topic #{@topic.id} - post #{post.id}")
+ Rails.logger.debug(
+ "Security updated & rebake complete in topic #{@topic.id} - post #{post.id}",
+ )
end
end
@@ -55,21 +58,27 @@ class TopicUploadSecurityManager
# -> a topic is moved from a private to a public category
posts_with_unowned_uploads.each do |post|
Post.transaction do
- Rails.logger.debug("Setting upload access control posts in topic #{@topic.id} - post #{post.id}")
+ Rails.logger.debug(
+ "Setting upload access control posts in topic #{@topic.id} - post #{post.id}",
+ )
post.topic = @topic
- secure_status_did_change = post.uploads.any? do |upload|
- first_post_upload_appeared_in = upload.upload_references.where(target_type: 'Post').first.target
- if first_post_upload_appeared_in == post
- upload.update(access_control_post: post)
- upload.update_secure_status(source: "topic upload security")
- else
- false
+ secure_status_did_change =
+ post.uploads.any? do |upload|
+ first_post_upload_appeared_in =
+ upload.upload_references.where(target_type: "Post").first.target
+ if first_post_upload_appeared_in == post
+ upload.update(access_control_post: post)
+ upload.update_secure_status(source: "topic upload security")
+ else
+ false
+ end
end
- end
post.rebake! if secure_status_did_change
- Rails.logger.debug("Completed changing access control posts #{secure_status_did_change ? 'and rebaking' : ''} in topic #{@topic.id} - post #{post.id}")
+ Rails.logger.debug(
+ "Completed changing access control posts #{secure_status_did_change ? "and rebaking" : ""} in topic #{@topic.id} - post #{post.id}",
+ )
end
end
@@ -79,15 +88,17 @@ class TopicUploadSecurityManager
private
def posts_owning_uploads
- Post.where(topic_id: @topic.id).joins('INNER JOIN uploads ON access_control_post_id = posts.id')
+ Post.where(topic_id: @topic.id).joins("INNER JOIN uploads ON access_control_post_id = posts.id")
end
def posts_with_unowned_uploads
Post
.where(topic_id: @topic.id)
- .joins("INNER JOIN upload_references ON upload_references.target_type = 'Post' AND upload_references.target_id = posts.id")
- .joins('INNER JOIN uploads ON upload_references.upload_id = uploads.id')
- .where('uploads.access_control_post_id IS NULL')
+ .joins(
+ "INNER JOIN upload_references ON upload_references.target_type = 'Post' AND upload_references.target_id = posts.id",
+ )
+ .joins("INNER JOIN uploads ON upload_references.upload_id = uploads.id")
+ .where("uploads.access_control_post_id IS NULL")
.includes(:uploads)
end
end
diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index 63b6ec7580a..a6431e392ec 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class TopicView
- MEGA_TOPIC_POSTS_COUNT = 10000
+ MEGA_TOPIC_POSTS_COUNT = 10_000
MIN_POST_READ_TIME = 4.0
def self.on_preload(&blk)
@@ -11,16 +11,12 @@ class TopicView
def self.cancel_preload(&blk)
if @preload
@preload.delete blk
- if @preload.length == 0
- @preload = nil
- end
+ @preload = nil if @preload.length == 0
end
end
def self.preload(topic_view)
- if @preload
- @preload.each { |preload| preload.call(topic_view) }
- end
+ @preload.each { |preload| preload.call(topic_view) } if @preload
end
attr_reader(
@@ -36,7 +32,7 @@ class TopicView
:can_review_topic,
:page,
:mentioned_users,
- :mentions
+ :mentions,
)
alias queued_posts_enabled? queued_posts_enabled
@@ -46,7 +42,7 @@ class TopicView
:draft_sequence,
:user_custom_fields,
:post_custom_fields,
- :post_number
+ :post_number,
)
delegate :category, to: :topic, allow_nil: true, private: true
@@ -73,7 +69,8 @@ class TopicView
end
def self.allowed_post_custom_fields(user, topic)
- wpcf = default_post_custom_fields + post_custom_fields_allowlisters.map { |w| w.call(user, topic) }
+ wpcf =
+ default_post_custom_fields + post_custom_fields_allowlisters.map { |w| w.call(user, topic) }
wpcf.flatten.uniq
end
@@ -114,9 +111,7 @@ class TopicView
@message_bus_last_id = MessageBus.last_id("/topic/#{@topic.id}")
- options.each do |key, value|
- self.instance_variable_set("@#{key}".to_sym, value)
- end
+ options.each { |key, value| self.instance_variable_set("@#{key}".to_sym, value) }
@post_number = [@post_number.to_i, 1].max
@@ -125,8 +120,10 @@ class TopicView
@chunk_size =
case
- when @print then TopicView.print_chunk_size
- else TopicView.chunk_size
+ when @print
+ TopicView.print_chunk_size
+ else
+ TopicView.chunk_size
end
@limit ||= @chunk_size
@@ -163,9 +160,7 @@ class TopicView
def show_read_indicator?
return false if !@user || !topic.private_message?
- topic.allowed_groups.any? do |group|
- group.publish_read_state? && group.users.include?(@user)
- end
+ topic.allowed_groups.any? { |group| group.publish_read_state? && group.users.include?(@user) }
end
def canonical_path
@@ -185,13 +180,14 @@ class TopicView
def gaps
return unless @contains_gaps
- @gaps ||= begin
- if is_mega_topic?
- nil
- else
- Gaps.new(filtered_post_ids, apply_default_scope(unfiltered_posts).pluck(:id))
+ @gaps ||=
+ begin
+ if is_mega_topic?
+ nil
+ else
+ Gaps.new(filtered_post_ids, apply_default_scope(unfiltered_posts).pluck(:id))
+ end
end
- end
end
def last_post
@@ -204,11 +200,12 @@ class TopicView
end
def next_page
- @next_page ||= begin
- if last_post && highest_post_number && (highest_post_number > last_post.post_number)
- @page + 1
+ @next_page ||=
+ begin
+ if last_post && highest_post_number && (highest_post_number > last_post.post_number)
+ @page + 1
+ end
end
- end
end
def prev_page_path
@@ -228,7 +225,7 @@ class TopicView
end
def relative_url
- "#{@topic.relative_url}#{@print ? '/print' : ''}"
+ "#{@topic.relative_url}#{@print ? "/print" : ""}"
end
def page_title
@@ -238,23 +235,22 @@ class TopicView
post = @topic.posts.find_by(post_number: @post_number)
author = post&.user
if author && @guardian.can_see_post?(post)
- title += I18n.t(
- "inline_oneboxer.topic_page_title_post_number_by_user",
- post_number: @post_number,
- username: author.username
- )
+ title +=
+ I18n.t(
+ "inline_oneboxer.topic_page_title_post_number_by_user",
+ post_number: @post_number,
+ username: author.username,
+ )
else
- title += I18n.t(
- "inline_oneboxer.topic_page_title_post_number",
- post_number: @post_number
- )
+ title += I18n.t("inline_oneboxer.topic_page_title_post_number", post_number: @post_number)
end
end
if SiteSetting.topic_page_title_includes_category
- if @topic.category_id != SiteSetting.uncategorized_category_id && @topic.category_id && @topic.category
+ if @topic.category_id != SiteSetting.uncategorized_category_id && @topic.category_id &&
+ @topic.category
title += " - #{@topic.category.name}"
elsif SiteSetting.tagging_enabled && @topic.tags.exists?
- title += " - #{@topic.tags.order('tags.topic_count DESC').first.name}"
+ title += " - #{@topic.tags.order("tags.topic_count DESC").first.name}"
end
end
title
@@ -277,7 +273,7 @@ class TopicView
return nil if desired_post.blank?
# TODO, this is actually quite slow, should be cached in the post table
excerpt = desired_post.excerpt(500, opts.merge(strip_links: true, text_entities: true))
- (excerpt || "").gsub(/\n/, ' ').strip
+ (excerpt || "").gsub(/\n/, " ").strip
end
def read_time
@@ -286,7 +282,7 @@ class TopicView
if @topic.word_count && SiteSetting.read_time_word_count > 0
[
@topic.word_count / SiteSetting.read_time_word_count,
- @topic.posts_count * MIN_POST_READ_TIME / 60
+ @topic.posts_count * MIN_POST_READ_TIME / 60,
].max.ceil
end
end
@@ -299,9 +295,9 @@ class TopicView
def published_time
return nil if desired_post.blank?
if desired_post.wiki && desired_post.post_number == 1 && desired_post.revisions.size > 0
- desired_post.revisions.last.updated_at.strftime('%FT%T%:z')
+ desired_post.revisions.last.updated_at.strftime("%FT%T%:z")
else
- desired_post.created_at.strftime('%FT%T%:z')
+ desired_post.created_at.strftime("%FT%T%:z")
end
end
@@ -336,9 +332,7 @@ class TopicView
result = {}
unless primary_group_ids.empty?
- Group.where(id: primary_group_ids.to_a).pluck(:id, :name).each do |g|
- result[g[0]] = g[1]
- end
+ Group.where(id: primary_group_ids.to_a).pluck(:id, :name).each { |g| result[g[0]] = g[1] }
end
@group_names = result
@@ -350,22 +344,29 @@ class TopicView
posts_before = 1 if posts_before.zero?
sort_order = get_sort_order(post_number)
- before_post_ids = @filtered_posts.reverse_order
- .where("posts.sort_order < ?", sort_order)
- .limit(posts_before)
- .pluck(:id)
+ before_post_ids =
+ @filtered_posts
+ .reverse_order
+ .where("posts.sort_order < ?", sort_order)
+ .limit(posts_before)
+ .pluck(:id)
- post_ids = before_post_ids + @filtered_posts
- .where("posts.sort_order >= ?", sort_order)
- .limit(@limit - before_post_ids.length)
- .pluck(:id)
+ post_ids =
+ before_post_ids +
+ @filtered_posts
+ .where("posts.sort_order >= ?", sort_order)
+ .limit(@limit - before_post_ids.length)
+ .pluck(:id)
if post_ids.length < @limit
- post_ids = post_ids + @filtered_posts.reverse_order
- .where("posts.sort_order < ?", sort_order)
- .offset(before_post_ids.length)
- .limit(@limit - post_ids.length)
- .pluck(:id)
+ post_ids =
+ post_ids +
+ @filtered_posts
+ .reverse_order
+ .where("posts.sort_order < ?", sort_order)
+ .offset(before_post_ids.length)
+ .limit(@limit - post_ids.length)
+ .pluck(:id)
end
filter_posts_by_ids(post_ids)
@@ -378,12 +379,7 @@ class TopicView
# Sometimes we don't care about the OP, for example when embedding comments
min = 1 if min == 0 && @exclude_first
- filter_posts_by_ids(
- @filtered_posts
- .offset(min)
- .limit(@limit)
- .pluck(:id)
- )
+ filter_posts_by_ids(@filtered_posts.offset(min).limit(@limit).pluck(:id))
end
def filter_best(max, opts = {})
@@ -398,17 +394,19 @@ class TopicView
end
def has_deleted?
- @predelete_filtered_posts.with_deleted
+ @predelete_filtered_posts
+ .with_deleted
.where("posts.deleted_at IS NOT NULL")
.where("posts.post_number > 1")
.exists?
end
def topic_user
- @topic_user ||= begin
- return nil if @user.blank?
- @topic.topic_users.find_by(user_id: @user.id)
- end
+ @topic_user ||=
+ begin
+ return nil if @user.blank?
+ @topic.topic_users.find_by(user_id: @user.id)
+ end
end
def has_bookmarks?
@@ -419,19 +417,26 @@ class TopicView
return [] if @user.blank?
return [] if @topic.trashed?
- @bookmarks ||= Bookmark.for_user_in_topic(@user, @topic.id).select(
- :id, :bookmarkable_id, :bookmarkable_type, :reminder_at, :name, :auto_delete_preference
- )
+ @bookmarks ||=
+ Bookmark.for_user_in_topic(@user, @topic.id).select(
+ :id,
+ :bookmarkable_id,
+ :bookmarkable_type,
+ :reminder_at,
+ :name,
+ :auto_delete_preference,
+ )
end
MAX_PARTICIPANTS = 24
def post_counts_by_user
- @post_counts_by_user ||= begin
- if is_mega_topic?
- {}
- else
- sql = <<~SQL
+ @post_counts_by_user ||=
+ begin
+ if is_mega_topic?
+ {}
+ else
+ sql = <<~SQL
SELECT user_id, count(*) AS count_all
FROM posts
WHERE topic_id = :topic_id
@@ -444,9 +449,15 @@ class TopicView
LIMIT #{MAX_PARTICIPANTS}
SQL
- Hash[*DB.query_single(sql, topic_id: @topic.id, post_types: Topic.visible_post_types(@guardian&.user))]
+ Hash[
+ *DB.query_single(
+ sql,
+ topic_id: @topic.id,
+ post_types: Topic.visible_post_types(@guardian&.user),
+ )
+ ]
+ end
end
- end
end
# if a topic has more that N posts no longer attempt to
@@ -476,38 +487,49 @@ class TopicView
end
def participants
- @participants ||= begin
- participants = {}
- User.where(id: post_counts_by_user.keys).includes(:primary_group, :flair_group).each { |u| participants[u.id] = u }
- participants
- end
+ @participants ||=
+ begin
+ participants = {}
+ User
+ .where(id: post_counts_by_user.keys)
+ .includes(:primary_group, :flair_group)
+ .each { |u| participants[u.id] = u }
+ participants
+ end
end
def topic_allowed_group_ids
- @topic_allowed_group_ids ||= begin
- @topic.allowed_groups.map(&:id)
- end
+ @topic_allowed_group_ids ||=
+ begin
+ @topic.allowed_groups.map(&:id)
+ end
end
def group_allowed_user_ids
return @group_allowed_user_ids unless @group_allowed_user_ids.nil?
- @group_allowed_user_ids = GroupUser
- .where(group_id: topic_allowed_group_ids)
- .pluck('distinct user_id')
+ @group_allowed_user_ids =
+ GroupUser.where(group_id: topic_allowed_group_ids).pluck("distinct user_id")
end
def category_group_moderator_user_ids
- @category_group_moderator_user_ids ||= begin
- if SiteSetting.enable_category_group_moderation? && @topic.category&.reviewable_by_group.present?
- posts_user_ids = Set.new(@posts.map(&:user_id))
- Set.new(
- @topic.category.reviewable_by_group.group_users.where(user_id: posts_user_ids).pluck('distinct user_id')
- )
- else
- Set.new
+ @category_group_moderator_user_ids ||=
+ begin
+ if SiteSetting.enable_category_group_moderation? &&
+ @topic.category&.reviewable_by_group.present?
+ posts_user_ids = Set.new(@posts.map(&:user_id))
+ Set.new(
+ @topic
+ .category
+ .reviewable_by_group
+ .group_users
+ .where(user_id: posts_user_ids)
+ .pluck("distinct user_id"),
+ )
+ else
+ Set.new
+ end
end
- end
end
def all_post_actions
@@ -519,8 +541,9 @@ class TopicView
end
def reviewable_counts
- @reviewable_counts ||= begin
- sql = <<~SQL
+ @reviewable_counts ||=
+ begin
+ sql = <<~SQL
SELECT
target_id,
MAX(r.id) reviewable_id,
@@ -538,26 +561,25 @@ class TopicView
target_id
SQL
- counts = {}
-
- DB.query(
- sql,
- pending: ReviewableScore.statuses[:pending],
- post_ids: @posts.map(&:id)
- ).each do |row|
- counts[row.target_id] = {
- total: row.total,
- pending: row.pending,
- reviewable_id: row.reviewable_id
- }
- end
+ counts = {}
- counts
- end
+ DB
+ .query(sql, pending: ReviewableScore.statuses[:pending], post_ids: @posts.map(&:id))
+ .each do |row|
+ counts[row.target_id] = {
+ total: row.total,
+ pending: row.pending,
+ reviewable_id: row.reviewable_id,
+ }
+ end
+
+ counts
+ end
end
def pending_posts
- @pending_posts ||= ReviewableQueuedPost.pending.where(created_by: @user, topic: @topic).order(:created_at)
+ @pending_posts ||=
+ ReviewableQueuedPost.pending.where(created_by: @user, topic: @topic).order(:created_at)
end
def actions_summary
@@ -570,7 +592,7 @@ class TopicView
id: id,
count: 0,
hidden: false,
- can_act: @guardian.post_can_act?(post, sym)
+ can_act: @guardian.post_can_act?(post, sym),
}
end
@@ -617,26 +639,28 @@ class TopicView
# Returns an array of [id, days_ago] tuples.
# `days_ago` is there for the timeline calculations.
def filtered_post_stream
- @filtered_post_stream ||= begin
- posts = @filtered_posts
- columns = [:id]
+ @filtered_post_stream ||=
+ begin
+ posts = @filtered_posts
+ columns = [:id]
- if !is_mega_topic?
- columns << '(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - posts.created_at) / 86400)::INT AS days_ago'
- end
+ if !is_mega_topic?
+ columns << "(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - posts.created_at) / 86400)::INT AS days_ago"
+ end
- posts.pluck(*columns)
- end
+ posts.pluck(*columns)
+ end
end
def filtered_post_ids
- @filtered_post_ids ||= filtered_post_stream.map do |tuple|
- if is_mega_topic?
- tuple
- else
- tuple[0]
+ @filtered_post_ids ||=
+ filtered_post_stream.map do |tuple|
+ if is_mega_topic?
+ tuple
+ else
+ tuple[0]
+ end
end
- end
end
def unfiltered_post_ids
@@ -677,18 +701,14 @@ class TopicView
end
def parse_mentions
- @mentions = @posts
- .to_h { |p| [p.id, p.mentions] }
- .reject { |_, v| v.empty? }
+ @mentions = @posts.to_h { |p| [p.id, p.mentions] }.reject { |_, v| v.empty? }
end
def load_mentioned_users
usernames = @mentions.values.flatten.uniq
mentioned_users = User.where(username: usernames)
- if SiteSetting.enable_user_status
- mentioned_users = mentioned_users.includes(:user_status)
- end
+ mentioned_users = mentioned_users.includes(:user_status) if SiteSetting.enable_user_status
@mentioned_users = mentioned_users.to_h { |u| [u.username, u] }
end
@@ -696,25 +716,28 @@ class TopicView
protected
def read_posts_set
- @read_posts_set ||= begin
- result = Set.new
- return result unless @user.present?
- return result unless topic_user.present?
-
- post_numbers = PostTiming
- .where(topic_id: @topic.id, user_id: @user.id)
- .where(post_number: @posts.pluck(:post_number))
- .pluck(:post_number)
-
- post_numbers.each { |pn| result << pn }
- result
- end
+ @read_posts_set ||=
+ begin
+ result = Set.new
+ return result unless @user.present?
+ return result unless topic_user.present?
+
+ post_numbers =
+ PostTiming
+ .where(topic_id: @topic.id, user_id: @user.id)
+ .where(post_number: @posts.pluck(:post_number))
+ .pluck(:post_number)
+
+ post_numbers.each { |pn| result << pn }
+ result
+ end
end
private
def calculate_page
- posts_count = is_mega_topic? ? @post_number : unfiltered_posts.where("post_number <= ?", @post_number).count
+ posts_count =
+ is_mega_topic? ? @post_number : unfiltered_posts.where("post_number <= ?", @post_number).count
((posts_count - 1) / @limit) + 1
end
@@ -773,13 +796,13 @@ class TopicView
end
def filter_posts_by_ids(post_ids)
- @posts = Post.where(id: post_ids, topic_id: @topic.id)
- .includes(
- { user: [:primary_group, :flair_group] },
+ @posts =
+ Post.where(id: post_ids, topic_id: @topic.id).includes(
+ { user: %i[primary_group flair_group] },
:reply_to_user,
:deleted_by,
:incoming_email,
- :image_upload
+ :image_upload,
)
@posts = @posts.includes({ user: :user_status }) if SiteSetting.enable_user_status
@@ -811,9 +834,7 @@ class TopicView
def apply_default_scope(scope)
scope = scope.order(sort_order: :asc)
- self.class.custom_default_scopes.each do |block|
- scope = block.call(scope, self)
- end
+ self.class.custom_default_scopes.each { |block| scope = block.call(scope, self) }
scope
end
@@ -837,23 +858,24 @@ class TopicView
ignored_user_ids = DB.query_single(sql, current_user_id: @user.id)
if ignored_user_ids.present?
- @filtered_posts = @filtered_posts.where.not("user_id IN (?) AND posts.post_number != 1", ignored_user_ids)
+ @filtered_posts =
+ @filtered_posts.where.not("user_id IN (?) AND posts.post_number != 1", ignored_user_ids)
@contains_gaps = true
end
end
# Filters
- if @filter == 'summary'
+ if @filter == "summary"
@filtered_posts = @filtered_posts.summary(@topic.id)
@contains_gaps = true
end
- if @filter.present? && @filter.to_s != 'summary' && TopicView.custom_filters[@filter].present?
+ if @filter.present? && @filter.to_s != "summary" && TopicView.custom_filters[@filter].present?
@filtered_posts = TopicView.custom_filters[@filter].call(@filtered_posts, self)
end
if @best.present?
- @filtered_posts = @filtered_posts.where('posts.post_type = ?', Post.types[:regular])
+ @filtered_posts = @filtered_posts.where("posts.post_type = ?", Post.types[:regular])
@contains_gaps = true
end
@@ -861,10 +883,14 @@ class TopicView
if @username_filters.present?
usernames = @username_filters.map { |u| u.downcase }
- @filtered_posts = @filtered_posts.where('
+ @filtered_posts =
+ @filtered_posts.where(
+ "
posts.post_number = 1
OR posts.user_id IN (SELECT u.id FROM users u WHERE u.username_lower IN (?))
- ', usernames)
+ ",
+ usernames,
+ )
@contains_gaps = true
end
@@ -872,21 +898,28 @@ class TopicView
# Filter replies
if @replies_to_post_number.present?
post_id = filtered_post_id(@replies_to_post_number.to_i)
- @filtered_posts = @filtered_posts.where('
+ @filtered_posts =
+ @filtered_posts.where(
+ "
posts.post_number = 1
OR posts.post_number = :post_number
OR posts.reply_to_post_number = :post_number
- OR posts.id IN (SELECT pr.reply_post_id FROM post_replies pr WHERE pr.post_id = :post_id)', { post_number: @replies_to_post_number.to_i, post_id: post_id })
+ OR posts.id IN (SELECT pr.reply_post_id FROM post_replies pr WHERE pr.post_id = :post_id)",
+ { post_number: @replies_to_post_number.to_i, post_id: post_id },
+ )
@contains_gaps = true
end
# Show Only Top Level Replies
if @filter_top_level_replies.present?
- @filtered_posts = @filtered_posts.where('
+ @filtered_posts =
+ @filtered_posts.where(
+ "
posts.post_number > 1
AND posts.reply_to_post_number IS NULL
- ')
+ ",
+ )
end
# Filtering upwards
@@ -909,10 +942,14 @@ class TopicView
post_ids = (post_ids[(0 - SiteSetting.max_reply_history)..-1] || post_ids)
post_ids.push(post.id)
- @filtered_posts = @filtered_posts.where('
+ @filtered_posts =
+ @filtered_posts.where(
+ "
posts.post_number = 1
OR posts.id IN (:post_ids)
- OR posts.id > :max_post_id', { post_ids: post_ids, max_post_id: post_ids.max })
+ OR posts.id > :max_post_id",
+ { post_ids: post_ids, max_post_id: post_ids.max },
+ )
@contains_gaps = true
end
@@ -923,9 +960,7 @@ class TopicView
@predelete_filtered_posts = @filtered_posts.spawn
if @guardian.can_see_deleted_posts?(@topic.category) && !@show_deleted && has_deleted?
- @filtered_posts = @filtered_posts.where(
- "posts.deleted_at IS NULL OR posts.post_number = 1"
- )
+ @filtered_posts = @filtered_posts.where("posts.deleted_at IS NULL OR posts.post_number = 1")
@contains_gaps = true
end
@@ -935,14 +970,22 @@ class TopicView
raise Discourse::NotFound if @topic.blank?
# Special case: If the topic is private and the user isn't logged in, ask them
# to log in!
- if @topic.present? && @topic.private_message? && @user.blank?
- raise Discourse::NotLoggedIn.new
- end
+ raise Discourse::NotLoggedIn.new if @topic.present? && @topic.private_message? && @user.blank?
# can user see this topic?
- raise Discourse::InvalidAccess.new("can't see #{@topic}", @topic) unless @guardian.can_see?(@topic)
+ unless @guardian.can_see?(@topic)
+ raise Discourse::InvalidAccess.new("can't see #{@topic}", @topic)
+ end
# log personal message views
- if SiteSetting.log_personal_messages_views && !skip_staff_action && @topic.present? && @topic.private_message? && @topic.all_allowed_users.where(id: @user.id).blank?
- unless UserHistory.where(acting_user_id: @user.id, action: UserHistory.actions[:check_personal_message], topic_id: @topic.id).where("created_at > ?", 1.hour.ago).exists?
+ if SiteSetting.log_personal_messages_views && !skip_staff_action && @topic.present? &&
+ @topic.private_message? && @topic.all_allowed_users.where(id: @user.id).blank?
+ unless UserHistory
+ .where(
+ acting_user_id: @user.id,
+ action: UserHistory.actions[:check_personal_message],
+ topic_id: @topic.id,
+ )
+ .where("created_at > ?", 1.hour.ago)
+ .exists?
StaffActionLogger.new(@user).log_check_personal_message(@topic)
end
end
diff --git a/lib/topics_bulk_action.rb b/lib/topics_bulk_action.rb
index 48f7819041b..89ed9f446d2 100644
--- a/lib/topics_bulk_action.rb
+++ b/lib/topics_bulk_action.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class TopicsBulkAction
-
def initialize(user, topic_ids, operation, options = {})
@user = user
@topic_ids = topic_ids
@@ -11,10 +10,24 @@ class TopicsBulkAction
end
def self.operations
- @operations ||= %w(change_category close archive change_notification_level
- destroy_post_timing dismiss_posts delete unlist archive_messages
- move_messages_to_inbox change_tags append_tags remove_tags
- relist dismiss_topics reset_bump_dates)
+ @operations ||= %w[
+ change_category
+ close
+ archive
+ change_notification_level
+ destroy_post_timing
+ dismiss_posts
+ delete
+ unlist
+ archive_messages
+ move_messages_to_inbox
+ change_tags
+ append_tags
+ remove_tags
+ relist
+ dismiss_topics
+ reset_bump_dates
+ ]
end
def self.register_operation(name, &block)
@@ -23,7 +36,9 @@ class TopicsBulkAction
end
def perform!
- raise Discourse::InvalidParameters.new(:operation) unless TopicsBulkAction.operations.include?(@operation[:type])
+ unless TopicsBulkAction.operations.include?(@operation[:type])
+ raise Discourse::InvalidParameters.new(:operation)
+ end
# careful these are private methods, we need send
send(@operation[:type])
@changed_ids.sort
@@ -34,7 +49,7 @@ class TopicsBulkAction
def find_group
return unless @options[:group]
- group = Group.where('name ilike ?', @options[:group]).first
+ group = Group.where("name ilike ?", @options[:group]).first
raise Discourse::InvalidParameters.new(:group) unless group
unless group.group_users.where(user_id: @user.id).exists?
raise Discourse::InvalidParameters.new(:group)
@@ -69,7 +84,8 @@ class TopicsBulkAction
end
def dismiss_posts
- highest_number_source_column = @user.whisperer? ? 'highest_staff_post_number' : 'highest_post_number'
+ highest_number_source_column =
+ @user.whisperer? ? "highest_staff_post_number" : "highest_post_number"
sql = <<~SQL
UPDATE topic_users tu
SET last_read_post_number = t.#{highest_number_source_column}
@@ -82,18 +98,17 @@ class TopicsBulkAction
end
def dismiss_topics
- rows = Topic.where(id: @topic_ids)
- .joins("LEFT JOIN topic_users ON topic_users.topic_id = topics.id AND topic_users.user_id = #{@user.id}")
- .where("topics.created_at >= ?", dismiss_topics_since_date)
- .where("topic_users.last_read_post_number IS NULL")
- .order("topics.created_at DESC")
- .limit(SiteSetting.max_new_topics).map do |topic|
- {
- topic_id: topic.id,
- user_id: @user.id,
- created_at: Time.zone.now
- }
- end
+ rows =
+ Topic
+ .where(id: @topic_ids)
+ .joins(
+ "LEFT JOIN topic_users ON topic_users.topic_id = topics.id AND topic_users.user_id = #{@user.id}",
+ )
+ .where("topics.created_at >= ?", dismiss_topics_since_date)
+ .where("topic_users.last_read_post_number IS NULL")
+ .order("topics.created_at DESC")
+ .limit(SiteSetting.max_new_topics)
+ .map { |topic| { topic_id: topic.id, user_id: @user.id, created_at: Time.zone.now } }
DismissedTopicUser.insert_all(rows) if rows.present?
@changed_ids = rows.map { |row| row[:topic_id] }
end
@@ -109,11 +124,7 @@ class TopicsBulkAction
updatable_topics = topics.where.not(category_id: @operation[:category_id])
if SiteSetting.create_revision_on_bulk_topic_moves
- opts = {
- bypass_bump: true,
- validate_post: false,
- bypass_rate_limiter: true
- }
+ opts = { bypass_bump: true, validate_post: false, bypass_rate_limiter: true }
updatable_topics.each do |t|
if guardian.can_edit?(t)
@@ -142,7 +153,7 @@ class TopicsBulkAction
def close
topics.each do |t|
if guardian.can_moderate?(t)
- t.update_status('closed', true, @user)
+ t.update_status("closed", true, @user)
@changed_ids << t.id
end
end
@@ -151,7 +162,7 @@ class TopicsBulkAction
def unlist
topics.each do |t|
if guardian.can_moderate?(t)
- t.update_status('visible', false, @user)
+ t.update_status("visible", false, @user)
@changed_ids << t.id
end
end
@@ -160,7 +171,7 @@ class TopicsBulkAction
def relist
topics.each do |t|
if guardian.can_moderate?(t)
- t.update_status('visible', true, @user)
+ t.update_status("visible", true, @user)
@changed_ids << t.id
end
end
@@ -178,7 +189,7 @@ class TopicsBulkAction
def archive
topics.each do |t|
if guardian.can_moderate?(t)
- t.update_status('archived', true, @user)
+ t.update_status("archived", true, @user)
@changed_ids << t.id
end
end
@@ -215,9 +226,7 @@ class TopicsBulkAction
topics.each do |t|
if guardian.can_edit?(t)
- if tags.present?
- DiscourseTagging.tag_topic_by_names(t, guardian, tags, append: true)
- end
+ DiscourseTagging.tag_topic_by_names(t, guardian, tags, append: true) if tags.present?
@changed_ids << t.id
end
end
@@ -241,7 +250,9 @@ class TopicsBulkAction
end
def dismiss_topics_since_date
- new_topic_duration_minutes = @user.user_option&.new_topic_duration_minutes || SiteSetting.default_other_new_topic_duration_minutes
+ new_topic_duration_minutes =
+ @user.user_option&.new_topic_duration_minutes ||
+ SiteSetting.default_other_new_topic_duration_minutes
setting_date =
case new_topic_duration_minutes
when User::NewTopicDuration::LAST_VISIT
@@ -253,5 +264,4 @@ class TopicsBulkAction
end
[setting_date, @user.created_at, Time.at(SiteSetting.min_new_topics_time).to_datetime].max
end
-
end
diff --git a/lib/trust_level.rb b/lib/trust_level.rb
index b776056b7aa..184b44ced6e 100644
--- a/lib/trust_level.rb
+++ b/lib/trust_level.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
-class InvalidTrustLevel < StandardError; end
+class InvalidTrustLevel < StandardError
+end
class TrustLevel
def self.[](level)
diff --git a/lib/turbo_tests.rb b/lib/turbo_tests.rb
index f81562804f6..dd3e9c0b619 100644
--- a/lib/turbo_tests.rb
+++ b/lib/turbo_tests.rb
@@ -1,20 +1,20 @@
# frozen_string_literal: true
-require 'bundler/setup'
+require "bundler/setup"
-require 'open3'
-require 'fileutils'
-require 'json'
-require 'rspec'
-require 'rails'
-require File.expand_path('../../config/environment', __FILE__)
+require "open3"
+require "fileutils"
+require "json"
+require "rspec"
+require "rails"
+require File.expand_path("../../config/environment", __FILE__)
-require 'parallel_tests'
-require 'parallel_tests/rspec/runner'
+require "parallel_tests"
+require "parallel_tests/rspec/runner"
-require './lib/turbo_tests/reporter'
-require './lib/turbo_tests/runner'
-require './lib/turbo_tests/json_rows_formatter'
+require "./lib/turbo_tests/reporter"
+require "./lib/turbo_tests/runner"
+require "./lib/turbo_tests/json_rows_formatter"
module TurboTests
FakeException = Struct.new(:backtrace, :message, :cause)
@@ -23,23 +23,22 @@ module TurboTests
if obj
obj = obj.symbolize_keys
- klass =
- Class.new(FakeException) do
- define_singleton_method(:name) do
- obj[:class_name]
- end
- end
+ klass = Class.new(FakeException) { define_singleton_method(:name) { obj[:class_name] } }
- klass.new(
- obj[:backtrace],
- obj[:message],
- FakeException.from_obj(obj[:cause])
- )
+ klass.new(obj[:backtrace], obj[:message], FakeException.from_obj(obj[:cause]))
end
end
end
- FakeExecutionResult = Struct.new(:example_skipped?, :pending_message, :status, :pending_fixed?, :exception, :pending_exception)
+ FakeExecutionResult =
+ Struct.new(
+ :example_skipped?,
+ :pending_message,
+ :status,
+ :pending_fixed?,
+ :exception,
+ :pending_exception,
+ )
class FakeExecutionResult
def self.from_obj(obj)
obj = obj.symbolize_keys
@@ -49,26 +48,25 @@ module TurboTests
obj[:status].to_sym,
obj[:pending_fixed?],
FakeException.from_obj(obj[:exception]),
- FakeException.from_obj(obj[:pending_exception])
+ FakeException.from_obj(obj[:pending_exception]),
)
end
end
- FakeExample = Struct.new(:execution_result, :location, :full_description, :metadata, :location_rerun_argument)
+ FakeExample =
+ Struct.new(:execution_result, :location, :full_description, :metadata, :location_rerun_argument)
class FakeExample
def self.from_obj(obj)
obj = obj.symbolize_keys
- metadata =
- obj[:metadata].symbolize_keys
+ metadata = obj[:metadata].symbolize_keys
- metadata[:shared_group_inclusion_backtrace]
- .map! { |frame|
- frame = frame.symbolize_keys
- RSpec::Core::SharedExampleGroupInclusionStackFrame.new(
- frame[:shared_group_name],
- frame[:inclusion_location]
- )
- }
+ metadata[:shared_group_inclusion_backtrace].map! do |frame|
+ frame = frame.symbolize_keys
+ RSpec::Core::SharedExampleGroupInclusionStackFrame.new(
+ frame[:shared_group_name],
+ frame[:inclusion_location],
+ )
+ end
new(
FakeExecutionResult.from_obj(obj[:execution_result]),
@@ -80,9 +78,7 @@ module TurboTests
end
def notification
- RSpec::Core::Notifications::ExampleNotification.for(
- self
- )
+ RSpec::Core::Notifications::ExampleNotification.for(self)
end
end
end
diff --git a/lib/turbo_tests/json_rows_formatter.rb b/lib/turbo_tests/json_rows_formatter.rb
index 1c2e78a0839..35118c35027 100644
--- a/lib/turbo_tests/json_rows_formatter.rb
+++ b/lib/turbo_tests/json_rows_formatter.rb
@@ -10,7 +10,7 @@ module TurboTests
:example_passed,
:example_pending,
:message,
- :seed
+ :seed,
)
attr_reader :output
@@ -25,7 +25,7 @@ module TurboTests
class_name: exception.class.name.to_s,
backtrace: exception.backtrace,
message: exception.message,
- cause: exception_to_json(exception.cause)
+ cause: exception_to_json(exception.cause),
}
end
end
@@ -42,10 +42,7 @@ module TurboTests
end
def stack_frame_to_json(frame)
- {
- shared_group_name: frame.shared_group_name,
- inclusion_location: frame.inclusion_location
- }
+ { shared_group_name: frame.shared_group_name, inclusion_location: frame.inclusion_location }
end
def example_to_json(example)
@@ -55,54 +52,35 @@ module TurboTests
full_description: example.full_description,
metadata: {
shared_group_inclusion_backtrace:
- example
- .metadata[:shared_group_inclusion_backtrace]
- .map(&method(:stack_frame_to_json)),
- extra_failure_lines: example.metadata[:extra_failure_lines]
+ example.metadata[:shared_group_inclusion_backtrace].map(&method(:stack_frame_to_json)),
+ extra_failure_lines: example.metadata[:extra_failure_lines],
},
- location_rerun_argument: example.location_rerun_argument
+ location_rerun_argument: example.location_rerun_argument,
}
end
def example_passed(notification)
- output_row(
- type: :example_passed,
- example: example_to_json(notification.example)
- )
+ output_row(type: :example_passed, example: example_to_json(notification.example))
end
def example_pending(notification)
- output_row(
- type: :example_pending,
- example: example_to_json(notification.example)
- )
+ output_row(type: :example_pending, example: example_to_json(notification.example))
end
def example_failed(notification)
- output_row(
- type: :example_failed,
- example: example_to_json(notification.example)
- )
+ output_row(type: :example_failed, example: example_to_json(notification.example))
end
def seed(notification)
- output_row(
- type: :seed,
- seed: notification.seed,
- )
+ output_row(type: :seed, seed: notification.seed)
end
def close(notification)
- output_row(
- type: :close,
- )
+ output_row(type: :close)
end
def message(notification)
- output_row(
- type: :message,
- message: notification.message
- )
+ output_row(type: :message, message: notification.message)
end
private
diff --git a/lib/turbo_tests/reporter.rb b/lib/turbo_tests/reporter.rb
index 6d02a1fb588..67c2a71bc30 100644
--- a/lib/turbo_tests/reporter.rb
+++ b/lib/turbo_tests/reporter.rb
@@ -8,9 +8,7 @@ module TurboTests
formatter_config.each do |config|
name, outputs = config.values_at(:name, :outputs)
- outputs.map! do |filename|
- filename == '-' ? STDOUT : File.open(filename, 'w')
- end
+ outputs.map! { |filename| filename == "-" ? STDOUT : File.open(filename, "w") }
reporter.add(name, outputs)
end
@@ -35,7 +33,7 @@ module TurboTests
outputs.each do |output|
formatter_class =
case name
- when 'p', 'progress'
+ when "p", "progress"
RSpec::Core::Formatters::ProgressFormatter
else
Kernel.const_get(name)
@@ -77,32 +75,27 @@ module TurboTests
def finish
end_time = Time.now
- delegate_to_formatters(:start_dump,
- RSpec::Core::Notifications::NullNotification
+ delegate_to_formatters(:start_dump, RSpec::Core::Notifications::NullNotification)
+ delegate_to_formatters(
+ :dump_pending,
+ RSpec::Core::Notifications::ExamplesNotification.new(self),
)
- delegate_to_formatters(:dump_pending,
- RSpec::Core::Notifications::ExamplesNotification.new(
- self
- )
+ delegate_to_formatters(
+ :dump_failures,
+ RSpec::Core::Notifications::ExamplesNotification.new(self),
)
- delegate_to_formatters(:dump_failures,
- RSpec::Core::Notifications::ExamplesNotification.new(
- self
- )
- )
- delegate_to_formatters(:dump_summary,
+ delegate_to_formatters(
+ :dump_summary,
RSpec::Core::Notifications::SummaryNotification.new(
end_time - @start_time,
@all_examples,
@failed_examples,
@pending_examples,
0,
- @errors_outside_of_examples_count
- )
- )
- delegate_to_formatters(:close,
- RSpec::Core::Notifications::NullNotification
+ @errors_outside_of_examples_count,
+ ),
)
+ delegate_to_formatters(:close, RSpec::Core::Notifications::NullNotification)
end
protected
diff --git a/lib/turbo_tests/runner.rb b/lib/turbo_tests/runner.rb
index 76137a70265..b81be543ed9 100644
--- a/lib/turbo_tests/runner.rb
+++ b/lib/turbo_tests/runner.rb
@@ -9,18 +9,11 @@ module TurboTests
verbose = opts.fetch(:verbose, false)
fail_fast = opts.fetch(:fail_fast, nil)
- if verbose
- STDERR.puts "VERBOSE"
- end
+ STDERR.puts "VERBOSE" if verbose
reporter = Reporter.from_config(formatters, start_time)
- new(
- reporter: reporter,
- files: files,
- verbose: verbose,
- fail_fast: fail_fast
- ).run
+ new(reporter: reporter, files: files, verbose: verbose, fail_fast: fail_fast).run
end
def initialize(opts)
@@ -39,7 +32,7 @@ module TurboTests
check_for_migrations
@num_processes = ParallelTests.determine_number_of_processes(nil)
- use_runtime_info = @files == ['spec']
+ use_runtime_info = @files == ["spec"]
group_opts = {}
@@ -50,17 +43,11 @@ module TurboTests
end
tests_in_groups =
- ParallelTests::RSpec::Runner.tests_in_groups(
- @files,
- @num_processes,
- **group_opts,
- )
+ ParallelTests::RSpec::Runner.tests_in_groups(@files, @num_processes, **group_opts)
setup_tmp_dir
- subprocess_opts = {
- record_runtime: use_runtime_info
- }
+ subprocess_opts = { record_runtime: use_runtime_info }
start_multisite_subprocess(@files, **subprocess_opts)
@@ -87,7 +74,7 @@ module TurboTests
.configuration_hash
.merge("database" => "discourse_test_1")
- ActiveRecord::Tasks::DatabaseTasks.migrations_paths = ['db/migrate', 'db/post_migrate']
+ ActiveRecord::Tasks::DatabaseTasks.migrations_paths = %w[db/migrate db/post_migrate]
conn = ActiveRecord::Base.establish_connection(config).connection
@@ -103,39 +90,30 @@ module TurboTests
def setup_tmp_dir
begin
- FileUtils.rm_r('tmp/test-pipes')
+ FileUtils.rm_r("tmp/test-pipes")
rescue Errno::ENOENT
end
- FileUtils.mkdir_p('tmp/test-pipes/')
+ FileUtils.mkdir_p("tmp/test-pipes/")
end
def start_multisite_subprocess(tests, **opts)
- start_subprocess(
- {},
- ["--tag", "type:multisite"],
- tests,
- "multisite",
- **opts
- )
+ start_subprocess({}, %w[--tag type:multisite], tests, "multisite", **opts)
end
def start_regular_subprocess(tests, process_id, **opts)
start_subprocess(
- { 'TEST_ENV_NUMBER' => process_id.to_s },
- ["--tag", "~type:multisite"],
+ { "TEST_ENV_NUMBER" => process_id.to_s },
+ %w[--tag ~type:multisite],
tests,
process_id,
- **opts
+ **opts,
)
end
def start_subprocess(env, extra_args, tests, process_id, record_runtime:)
if tests.empty?
- @messages << {
- type: 'exit',
- process_id: process_id
- }
+ @messages << { type: "exit", process_id: process_id }
else
tmp_filename = "tmp/test-pipes/subprocess-#{process_id}"
@@ -144,33 +122,34 @@ module TurboTests
rescue Errno::EEXIST
end
- env['RSPEC_SILENCE_FILTER_ANNOUNCEMENTS'] = '1'
+ env["RSPEC_SILENCE_FILTER_ANNOUNCEMENTS"] = "1"
record_runtime_options =
if record_runtime
- [
- "--format", "ParallelTests::RSpec::RuntimeLogger",
- "--out", "tmp/turbo_rspec_runtime.log",
- ]
+ %w[--format ParallelTests::RSpec::RuntimeLogger --out tmp/turbo_rspec_runtime.log]
else
[]
end
command = [
- "bundle", "exec", "rspec",
+ "bundle",
+ "exec",
+ "rspec",
*extra_args,
- "--seed", rand(2**16).to_s,
- "--format", "TurboTests::JsonRowsFormatter",
- "--out", tmp_filename,
+ "--seed",
+ rand(2**16).to_s,
+ "--format",
+ "TurboTests::JsonRowsFormatter",
+ "--out",
+ tmp_filename,
*record_runtime_options,
- *tests
+ *tests,
]
if @verbose
- command_str = [
- env.map { |k, v| "#{k}=#{v}" }.join(' '),
- command.join(' ')
- ].select { |x| x.size > 0 }.join(' ')
+ command_str =
+ [env.map { |k, v| "#{k}=#{v}" }.join(" "), command.join(" ")].select { |x| x.size > 0 }
+ .join(" ")
STDERR.puts "Process #{process_id}: #{command_str}"
end
@@ -178,28 +157,23 @@ module TurboTests
stdin, stdout, stderr, wait_thr = Open3.popen3(env, *command)
stdin.close
- @threads <<
- Thread.new do
- File.open(tmp_filename) do |fd|
- fd.each_line do |line|
- message = JSON.parse(line)
- message = message.symbolize_keys
- message[:process_id] = process_id
- @messages << message
- end
+ @threads << Thread.new do
+ File.open(tmp_filename) do |fd|
+ fd.each_line do |line|
+ message = JSON.parse(line)
+ message = message.symbolize_keys
+ message[:process_id] = process_id
+ @messages << message
end
-
- @messages << { type: 'exit', process_id: process_id }
end
+ @messages << { type: "exit", process_id: process_id }
+ end
+
@threads << start_copy_thread(stdout, STDOUT)
@threads << start_copy_thread(stderr, STDERR)
- @threads << Thread.new do
- if wait_thr.value.exitstatus != 0
- @messages << { type: 'error' }
- end
- end
+ @threads << Thread.new { @messages << { type: "error" } if wait_thr.value.exitstatus != 0 }
end
end
@@ -225,13 +199,13 @@ module TurboTests
while true
message = @messages.pop
case message[:type]
- when 'example_passed'
+ when "example_passed"
example = FakeExample.from_obj(message[:example])
@reporter.example_passed(example)
- when 'example_pending'
+ when "example_pending"
example = FakeExample.from_obj(message[:example])
@reporter.example_pending(example)
- when 'example_failed'
+ when "example_failed"
example = FakeExample.from_obj(message[:example])
@reporter.example_failed(example)
@failure_count += 1
@@ -239,18 +213,16 @@ module TurboTests
@threads.each(&:kill)
break
end
- when 'message'
+ when "message"
@reporter.message(message[:message])
- when 'seed'
- when 'close'
- when 'error'
+ when "seed"
+ when "close"
+ when "error"
@reporter.error_outside_of_examples
@error = true
- when 'exit'
+ when "exit"
exited += 1
- if exited == @num_processes + 1
- break
- end
+ break if exited == @num_processes + 1
else
STDERR.puts("Unhandled message in main process: #{message}")
end
diff --git a/lib/twitter_api.rb b/lib/twitter_api.rb
index 9d5e626fb2f..c7f5126e1e9 100644
--- a/lib/twitter_api.rb
+++ b/lib/twitter_api.rb
@@ -5,13 +5,16 @@ class TwitterApi
class << self
include ActionView::Helpers::NumberHelper
- BASE_URL = 'https://api.twitter.com'
+ BASE_URL = "https://api.twitter.com"
def prettify_tweet(tweet)
text = tweet["full_text"].dup
if (entities = tweet["entities"]) && (urls = entities["urls"])
urls.each do |url|
- text.gsub!(url["url"], "<a target='_blank' href='#{url["expanded_url"]}'>#{url["display_url"]}</a>")
+ text.gsub!(
+ url["url"],
+ "<a target='_blank' href='#{url["expanded_url"]}'>#{url["display_url"]}</a>",
+ )
end
end
@@ -19,37 +22,29 @@ class TwitterApi
result = Rinku.auto_link(text, :all, 'target="_blank"').to_s
- if tweet['extended_entities'] && media = tweet['extended_entities']['media']
+ if tweet["extended_entities"] && media = tweet["extended_entities"]["media"]
media.each do |m|
- if m['type'] == 'photo'
- if large = m['sizes']['large']
- result << "<div class='tweet-images'><img class='tweet-image' src='#{m['media_url_https']}' width='#{large['w']}' height='#{large['h']}'></div>"
+ if m["type"] == "photo"
+ if large = m["sizes"]["large"]
+ result << "<div class='tweet-images'><img class='tweet-image' src='#{m["media_url_https"]}' width='#{large["w"]}' height='#{large["h"]}'></div>"
end
- elsif m['type'] == 'video' || m['type'] == 'animated_gif'
- video_to_display = m['video_info']['variants']
- .select { |v| v['content_type'] == 'video/mp4' }
- .sort { |v| v['bitrate'] }.last # choose highest bitrate
+ elsif m["type"] == "video" || m["type"] == "animated_gif"
+ video_to_display =
+ m["video_info"]["variants"]
+ .select { |v| v["content_type"] == "video/mp4" }
+ .sort { |v| v["bitrate"] }
+ .last # choose highest bitrate
- if video_to_display && url = video_to_display['url']
- width = m['sizes']['large']['w']
- height = m['sizes']['large']['h']
+ if video_to_display && url = video_to_display["url"]
+ width = m["sizes"]["large"]["w"]
+ height = m["sizes"]["large"]["h"]
attributes =
- if m['type'] == 'animated_gif'
- %w{
- playsinline
- loop
- muted
- autoplay
- disableRemotePlayback
- disablePictureInPicture
- }
+ if m["type"] == "animated_gif"
+ %w[playsinline loop muted autoplay disableRemotePlayback disablePictureInPicture]
else
- %w{
- controls
- playsinline
- }
- end.join(' ')
+ %w[controls playsinline]
+ end.join(" ")
result << <<~HTML
<div class='tweet-images'>
@@ -57,7 +52,7 @@ class TwitterApi
<video class='tweet-video' #{attributes}
width='#{width}'
height='#{height}'
- poster='#{m['media_url_https']}'>
+ poster='#{m["media_url_https"]}'>
<source src='#{url}' type="video/mp4">
</video>
</div>
@@ -72,7 +67,16 @@ class TwitterApi
end
def prettify_number(count)
- number_to_human(count, format: '%n%u', precision: 2, units: { thousand: 'K', million: 'M', billion: 'B' })
+ number_to_human(
+ count,
+ format: "%n%u",
+ precision: 2,
+ units: {
+ thousand: "K",
+ million: "M",
+ billion: "B",
+ },
+ )
end
def tweet_for(id)
@@ -87,19 +91,23 @@ class TwitterApi
protected
def link_handles_in(text)
- text.gsub(/(?:^|\s)@\w+/) do |match|
- whitespace = match[0] == " " ? " " : ""
- handle = match.strip[1..]
- "#{whitespace}<a href='https://twitter.com/#{handle}' target='_blank'>@#{handle}</a>"
- end.strip
+ text
+ .gsub(/(?:^|\s)@\w+/) do |match|
+ whitespace = match[0] == " " ? " " : ""
+ handle = match.strip[1..]
+ "#{whitespace}<a href='https://twitter.com/#{handle}' target='_blank'>@#{handle}</a>"
+ end
+ .strip
end
def link_hashtags_in(text)
- text.gsub(/(?:^|\s)#\w+/) do |match|
- whitespace = match[0] == " " ? " " : ""
- hashtag = match.strip[1..]
- "#{whitespace}<a href='https://twitter.com/search?q=%23#{hashtag}' target='_blank'>##{hashtag}</a>"
- end.strip
+ text
+ .gsub(/(?:^|\s)#\w+/) do |match|
+ whitespace = match[0] == " " ? " " : ""
+ hashtag = match.strip[1..]
+ "#{whitespace}<a href='https://twitter.com/search?q=%23#{hashtag}' target='_blank'>##{hashtag}</a>"
+ end
+ .strip
end
def tweet_uri_for(id)
@@ -108,7 +116,7 @@ class TwitterApi
def twitter_get(uri)
request = Net::HTTP::Get.new(uri)
- request.add_field 'Authorization', "Bearer #{bearer_token}"
+ request.add_field "Authorization", "Bearer #{bearer_token}"
response = http(uri).request(request)
if response.kind_of?(Net::HTTPTooManyRequests)
@@ -121,23 +129,21 @@ class TwitterApi
def authorization
request = Net::HTTP::Post.new(auth_uri)
- request.add_field 'Authorization',
- "Basic #{bearer_token_credentials}"
- request.add_field 'Content-Type',
- 'application/x-www-form-urlencoded;charset=UTF-8'
+ request.add_field "Authorization", "Basic #{bearer_token_credentials}"
+ request.add_field "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"
- request.set_form_data 'grant_type' => 'client_credentials'
+ request.set_form_data "grant_type" => "client_credentials"
http(auth_uri).request(request).body
end
def bearer_token
- @access_token ||= JSON.parse(authorization).fetch('access_token')
+ @access_token ||= JSON.parse(authorization).fetch("access_token")
end
def bearer_token_credentials
Base64.strict_encode64(
- "#{UrlHelper.encode_component(consumer_key)}:#{UrlHelper.encode_component(consumer_secret)}"
+ "#{UrlHelper.encode_component(consumer_key)}:#{UrlHelper.encode_component(consumer_secret)}",
)
end
diff --git a/lib/unread.rb b/lib/unread.rb
index e59c388caa4..cc5c2cc5a16 100644
--- a/lib/unread.rb
+++ b/lib/unread.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class Unread
-
# This module helps us calculate unread post counts
def initialize(topic, topic_user, guardian)
@@ -14,7 +13,8 @@ class Unread
return 0 if @topic_user.last_read_post_number.blank?
return 0 if do_not_notify?(@topic_user.notification_level)
- highest_post_number = @guardian.is_whisperer? ? @topic.highest_staff_post_number : @topic.highest_post_number
+ highest_post_number =
+ @guardian.is_whisperer? ? @topic.highest_staff_post_number : @topic.highest_post_number
return 0 if @topic_user.last_read_post_number > highest_post_number
@@ -27,11 +27,10 @@ class Unread
DO_NOT_NOTIFY_LEVELS = [
TopicUser.notification_levels[:muted],
- TopicUser.notification_levels[:regular]
+ TopicUser.notification_levels[:regular],
]
def do_not_notify?(notification_level)
DO_NOT_NOTIFY_LEVELS.include?(notification_level)
end
-
end
diff --git a/lib/upload_creator.rb b/lib/upload_creator.rb
index 52ace3202a5..d83af7461c9 100644
--- a/lib/upload_creator.rb
+++ b/lib/upload_creator.rb
@@ -3,17 +3,36 @@
require "fastimage"
class UploadCreator
-
- TYPES_TO_CROP ||= %w{avatar card_background custom_emoji profile_background}.each(&:freeze)
-
- ALLOWED_SVG_ELEMENTS ||= %w{
- circle clipPath defs ellipse feGaussianBlur filter g line linearGradient
- marker path polygon polyline radialGradient rect stop style svg text
- textPath tref tspan use
- }.each(&:freeze)
+ TYPES_TO_CROP ||= %w[avatar card_background custom_emoji profile_background].each(&:freeze)
+
+ ALLOWED_SVG_ELEMENTS ||= %w[
+ circle
+ clipPath
+ defs
+ ellipse
+ feGaussianBlur
+ filter
+ g
+ line
+ linearGradient
+ marker
+ path
+ polygon
+ polyline
+ radialGradient
+ rect
+ stop
+ style
+ svg
+ text
+ textPath
+ tref
+ tspan
+ use
+ ].each(&:freeze)
include ActiveSupport::Deprecation::DeprecatedConstantAccessor
- deprecate_constant 'WHITELISTED_SVG_ELEMENTS', 'UploadCreator::ALLOWED_SVG_ELEMENTS'
+ deprecate_constant "WHITELISTED_SVG_ELEMENTS", "UploadCreator::ALLOWED_SVG_ELEMENTS"
# Available options
# - type (string)
@@ -31,7 +50,13 @@ class UploadCreator
@upload = Upload.new(original_filename: @filename, filesize: 0)
@opts = opts
@filesize = @opts[:filesize] if @opts[:external_upload_too_big]
- @opts[:validate] = opts[:skip_validations].present? ? !ActiveRecord::Type::Boolean.new.cast(opts[:skip_validations]) : true
+ @opts[:validate] = (
+ if opts[:skip_validations].present?
+ !ActiveRecord::Type::Boolean.new.cast(opts[:skip_validations])
+ else
+ true
+ end
+ )
# TODO (martin) Validate @opts[:type] to make sure only blessed types are passed
# in, since the clientside can pass any type it wants.
@@ -43,7 +68,12 @@ class UploadCreator
return @upload
end
- @image_info = FastImage.new(@file) rescue nil
+ @image_info =
+ begin
+ FastImage.new(@file)
+ rescue StandardError
+ nil
+ end
is_image = FileHelper.is_supported_image?(@filename)
is_image ||= @image_info && FileHelper.is_supported_image?("test.#{@image_info.type}")
is_image = false if @opts[:for_theme]
@@ -79,10 +109,10 @@ class UploadCreator
elsif !Rails.env.test? || @opts[:force_optimize]
convert_to_jpeg! if convert_png_to_jpeg? || should_alter_quality?
fix_orientation! if should_fix_orientation?
- crop! if should_crop?
- optimize! if should_optimize?
- downsize! if should_downsize?
- return @upload if is_still_too_big?
+ crop! if should_crop?
+ optimize! if should_optimize?
+ downsize! if should_downsize?
+ return @upload if is_still_too_big?
end
# conversion may have switched the type
@@ -91,12 +121,8 @@ class UploadCreator
# compute the sha of the file and generate a unique hash
# which is only used for secure uploads
- if !external_upload_too_big
- sha1 = Upload.generate_digest(@file)
- end
- if SiteSetting.secure_uploads || external_upload_too_big
- unique_hash = generate_fake_sha1_hash
- end
+ sha1 = Upload.generate_digest(@file) if !external_upload_too_big
+ unique_hash = generate_fake_sha1_hash if SiteSetting.secure_uploads || external_upload_too_big
# we do not check for duplicate uploads if secure uploads is
# enabled because we use a unique access hash to differentiate
@@ -137,17 +163,17 @@ class UploadCreator
# create the upload otherwise
@upload = Upload.new
- @upload.user_id = user_id
+ @upload.user_id = user_id
@upload.original_filename = fixed_original_filename || @filename
- @upload.filesize = filesize
- @upload.sha1 = (SiteSetting.secure_uploads? || external_upload_too_big) ? unique_hash : sha1
- @upload.original_sha1 = SiteSetting.secure_uploads? ? sha1 : nil
- @upload.url = ""
- @upload.origin = @opts[:origin][0...1000] if @opts[:origin]
- @upload.extension = image_type || File.extname(@filename)[1..10]
+ @upload.filesize = filesize
+ @upload.sha1 = (SiteSetting.secure_uploads? || external_upload_too_big) ? unique_hash : sha1
+ @upload.original_sha1 = SiteSetting.secure_uploads? ? sha1 : nil
+ @upload.url = ""
+ @upload.origin = @opts[:origin][0...1000] if @opts[:origin]
+ @upload.extension = image_type || File.extname(@filename)[1..10]
if is_image && !external_upload_too_big
- if @image_info.type.to_s == 'svg'
+ if @image_info.type.to_s == "svg"
w, h = [0, 0]
# identify can behave differently depending on how it's compiled and
@@ -155,10 +181,19 @@ class UploadCreator
# 'MSVG:' forces ImageMagick to use internal routines and behave
# consistently whether it's running from our docker container or not
begin
- w, h = Discourse::Utils
- .execute_command("identify", "-ping", "-format", "%w %h", "MSVG:#{@file.path}", timeout: Upload::MAX_IDENTIFY_SECONDS)
- .split(' ').map(&:to_i)
- rescue
+ w, h =
+ Discourse::Utils
+ .execute_command(
+ "identify",
+ "-ping",
+ "-format",
+ "%w %h",
+ "MSVG:#{@file.path}",
+ timeout: Upload::MAX_IDENTIFY_SECONDS,
+ )
+ .split(" ")
+ .map(&:to_i)
+ rescue StandardError
# use default 0, 0
end
else
@@ -174,7 +209,8 @@ class UploadCreator
add_metadata!
if SiteSetting.secure_uploads
- secure, reason = UploadSecurity.new(@upload, @opts.merge(creating: true)).should_be_secure_with_reason
+ secure, reason =
+ UploadSecurity.new(@upload, @opts.merge(creating: true)).should_be_secure_with_reason
attrs = @upload.secure_params(secure, reason, "upload creator")
@upload.assign_attributes(attrs)
end
@@ -190,7 +226,7 @@ class UploadCreator
return @upload unless @upload.errors.empty? && @upload.save(validate: @opts[:validate])
should_move = false
- upload_changed = \
+ upload_changed =
if external_upload_too_big
false
else
@@ -205,23 +241,27 @@ class UploadCreator
if should_move
# move the file in the store instead of reuploading
- url = store.move_existing_stored_upload(
- existing_external_upload_key: @opts[:existing_external_upload_key],
- upload: @upload
- )
+ url =
+ store.move_existing_stored_upload(
+ existing_external_upload_key: @opts[:existing_external_upload_key],
+ upload: @upload,
+ )
else
# store the file and update its url
- File.open(@file.path) do |f|
- url = store.store_upload(f, @upload)
+ File.open(@file.path) { |f| url = store.store_upload(f, @upload) }
+ if @opts[:existing_external_upload_key]
+ store.delete_file(@opts[:existing_external_upload_key])
end
- store.delete_file(@opts[:existing_external_upload_key]) if @opts[:existing_external_upload_key]
end
if url.present?
@upload.url = url
@upload.save!(validate: @opts[:validate])
else
- @upload.errors.add(:url, I18n.t("upload.store_failure", upload_id: @upload.id, user_id: user_id))
+ @upload.errors.add(
+ :url,
+ I18n.t("upload.store_failure", upload_id: @upload.id, user_id: user_id),
+ )
end
if @upload.errors.empty? && is_image && @opts[:type] == "avatar" && @upload.extension != "svg"
@@ -241,17 +281,28 @@ class UploadCreator
end
def extract_image_info!
- @image_info = FastImage.new(@file) rescue nil
+ @image_info =
+ begin
+ FastImage.new(@file)
+ rescue StandardError
+ nil
+ end
@file.rewind
if @image_info.nil?
@upload.errors.add(:base, I18n.t("upload.images.not_supported_or_corrupted"))
elsif filesize <= 0
@upload.errors.add(:base, I18n.t("upload.empty"))
- elsif pixels == 0 && @image_info.type.to_s != 'svg'
+ elsif pixels == 0 && @image_info.type.to_s != "svg"
@upload.errors.add(:base, I18n.t("upload.images.size_not_found"))
elsif max_image_pixels > 0 && pixels >= max_image_pixels * 2
- @upload.errors.add(:base, I18n.t("upload.images.larger_than_x_megapixels", max_image_megapixels: SiteSetting.max_image_megapixels * 2))
+ @upload.errors.add(
+ :base,
+ I18n.t(
+ "upload.images.larger_than_x_megapixels",
+ max_image_megapixels: SiteSetting.max_image_megapixels * 2,
+ ),
+ )
end
end
@@ -259,7 +310,7 @@ class UploadCreator
def convert_png_to_jpeg?
return false unless @image_info.type == :png
- return true if @opts[:pasted]
+ return true if @opts[:pasted]
return false if SiteSetting.png_to_jpg_quality == 100
pixels > MIN_PIXELS_TO_CONVERT_TO_JPEG
end
@@ -268,7 +319,7 @@ class UploadCreator
MIN_CONVERT_TO_JPEG_SAVING_RATIO = 0.70
def convert_favicon_to_png!
- png_tempfile = Tempfile.new(["image", ".png"])
+ png_tempfile = Tempfile.new(%w[image .png])
from = @file.path
to = png_tempfile.path
@@ -284,7 +335,7 @@ class UploadCreator
begin
execute_convert(from, to, opts)
- rescue
+ rescue StandardError
# retry with debugging enabled
execute_convert(from, to, opts.merge(debug: true))
end
@@ -298,7 +349,7 @@ class UploadCreator
return if @opts[:for_site_setting]
return if filesize < MIN_CONVERT_TO_JPEG_BYTES_SAVED
- jpeg_tempfile = Tempfile.new(["image", ".jpg"])
+ jpeg_tempfile = Tempfile.new(%w[image .jpg])
from = @file.path
to = jpeg_tempfile.path
@@ -309,13 +360,16 @@ class UploadCreator
to = OptimizedImage.prepend_decoder!(to)
opts = {}
- desired_quality = [SiteSetting.png_to_jpg_quality, SiteSetting.recompress_original_jpg_quality].compact.min
+ desired_quality = [
+ SiteSetting.png_to_jpg_quality,
+ SiteSetting.recompress_original_jpg_quality,
+ ].compact.min
target_quality = @upload.target_image_quality(from, desired_quality)
opts = { quality: target_quality } if target_quality
begin
execute_convert(from, to, opts)
- rescue
+ rescue StandardError
# retry with debugging enabled
execute_convert(from, to, opts.merge(debug: true))
end
@@ -339,14 +393,14 @@ class UploadCreator
end
def convert_heif!
- jpeg_tempfile = Tempfile.new(["image", ".jpg"])
+ jpeg_tempfile = Tempfile.new(%w[image .jpg])
from = @file.path
to = jpeg_tempfile.path
OptimizedImage.ensure_safe_paths!(from, to)
begin
execute_convert(from, to)
- rescue
+ rescue StandardError
# retry with debugging enabled
execute_convert(from, to, { debug: true })
end
@@ -358,13 +412,7 @@ class UploadCreator
MAX_CONVERT_FORMAT_SECONDS = 20
def execute_convert(from, to, opts = {})
- command = [
- "convert",
- from,
- "-auto-orient",
- "-background", "white",
- "-interlace", "none",
- ]
+ command = ["convert", from, "-auto-orient", "-background", "white", "-interlace", "none"]
command << "-flatten" unless opts[:flatten] == false
command << "-debug" << "all" if opts[:debug]
command << "-quality" << opts[:quality].to_s if opts[:quality]
@@ -373,14 +421,21 @@ class UploadCreator
Discourse::Utils.execute_command(
*command,
failure_message: I18n.t("upload.png_to_jpg_conversion_failure_message"),
- timeout: MAX_CONVERT_FORMAT_SECONDS
+ timeout: MAX_CONVERT_FORMAT_SECONDS,
)
end
def should_alter_quality?
return false if animated?
- desired_quality = @image_info.type == :png ? SiteSetting.png_to_jpg_quality : SiteSetting.recompress_original_jpg_quality
+ desired_quality =
+ (
+ if @image_info.type == :png
+ SiteSetting.png_to_jpg_quality
+ else
+ SiteSetting.recompress_original_jpg_quality
+ end
+ )
@upload.target_image_quality(@file.path, desired_quality).present?
end
@@ -398,13 +453,7 @@ class UploadCreator
OptimizedImage.ensure_safe_paths!(from, to)
- OptimizedImage.downsize(
- from,
- to,
- "50%",
- scale_image: true,
- raise_on_error: true
- )
+ OptimizedImage.downsize(from, to, "50%", scale_image: true, raise_on_error: true)
@file.respond_to?(:close!) ? @file.close! : @file.close
@file = down_tempfile
@@ -413,18 +462,28 @@ class UploadCreator
return if filesize >= original_size || pixels == 0 || !should_downsize?
end
- rescue
+ rescue StandardError
@upload.errors.add(:base, I18n.t("upload.optimize_failure_message"))
end
def is_still_too_big?
if max_image_pixels > 0 && pixels >= max_image_pixels
- @upload.errors.add(:base, I18n.t("upload.images.larger_than_x_megapixels", max_image_megapixels: SiteSetting.max_image_megapixels))
+ @upload.errors.add(
+ :base,
+ I18n.t(
+ "upload.images.larger_than_x_megapixels",
+ max_image_megapixels: SiteSetting.max_image_megapixels,
+ ),
+ )
true
elsif max_image_size > 0 && filesize >= max_image_size
- @upload.errors.add(:base, I18n.t(
- "upload.images.too_large_humanized", max_size: ActiveSupport::NumberHelper.number_to_human_size(max_image_size)
- ))
+ @upload.errors.add(
+ :base,
+ I18n.t(
+ "upload.images.too_large_humanized",
+ max_size: ActiveSupport::NumberHelper.number_to_human_size(max_image_size),
+ ),
+ )
true
else
false
@@ -432,14 +491,16 @@ class UploadCreator
end
def clean_svg!
- doc = Nokogiri::XML(@file)
+ doc = Nokogiri.XML(@file)
doc.xpath(svg_allowlist_xpath).remove
doc.xpath("//@*[starts-with(name(), 'on')]").remove
- doc.css('use').each do |use_el|
- if use_el.attr('href')
- use_el.remove_attribute('href') unless use_el.attr('href').starts_with?('#')
+ doc
+ .css("use")
+ .each do |use_el|
+ if use_el.attr("href")
+ use_el.remove_attribute("href") unless use_el.attr("href").starts_with?("#")
+ end
end
- end
File.write(@file.path, doc.to_s)
@file.rewind
end
@@ -457,13 +518,21 @@ class UploadCreator
OptimizedImage.ensure_safe_paths!(path)
path = OptimizedImage.prepend_decoder!(path, nil, filename: "image.#{@image_info.type}")
- Discourse::Utils.execute_command('convert', path, '-auto-orient', path, timeout: MAX_FIX_ORIENTATION_TIME)
+ Discourse::Utils.execute_command(
+ "convert",
+ path,
+ "-auto-orient",
+ path,
+ timeout: MAX_FIX_ORIENTATION_TIME,
+ )
extract_image_info!
end
def should_crop?
- return false if ['profile_background', 'card_background', 'custom_emoji'].include?(@opts[:type]) && animated?
+ if %w[profile_background card_background custom_emoji].include?(@opts[:type]) && animated?
+ return false
+ end
TYPES_TO_CROP.include?(@opts[:type])
end
@@ -475,17 +544,50 @@ class UploadCreator
case @opts[:type]
when "avatar"
width = height = Discourse.avatar_sizes.max
- OptimizedImage.resize(@file.path, @file.path, width, height, filename: filename_with_correct_ext)
+ OptimizedImage.resize(
+ @file.path,
+ @file.path,
+ width,
+ height,
+ filename: filename_with_correct_ext,
+ )
when "profile_background"
max_width = 850 * max_pixel_ratio
- width, height = ImageSizer.resize(@image_info.size[0], @image_info.size[1], max_width: max_width, max_height: max_width)
- OptimizedImage.downsize(@file.path, @file.path, "#{width}x#{height}\>", filename: filename_with_correct_ext)
+ width, height =
+ ImageSizer.resize(
+ @image_info.size[0],
+ @image_info.size[1],
+ max_width: max_width,
+ max_height: max_width,
+ )
+ OptimizedImage.downsize(
+ @file.path,
+ @file.path,
+ "#{width}x#{height}\>",
+ filename: filename_with_correct_ext,
+ )
when "card_background"
max_width = 590 * max_pixel_ratio
- width, height = ImageSizer.resize(@image_info.size[0], @image_info.size[1], max_width: max_width, max_height: max_width)
- OptimizedImage.downsize(@file.path, @file.path, "#{width}x#{height}\>", filename: filename_with_correct_ext)
+ width, height =
+ ImageSizer.resize(
+ @image_info.size[0],
+ @image_info.size[1],
+ max_width: max_width,
+ max_height: max_width,
+ )
+ OptimizedImage.downsize(
+ @file.path,
+ @file.path,
+ "#{width}x#{height}\>",
+ filename: filename_with_correct_ext,
+ )
when "custom_emoji"
- OptimizedImage.downsize(@file.path, @file.path, "100x100\>", filename: filename_with_correct_ext)
+ OptimizedImage.downsize(
+ @file.path,
+ @file.path,
+ "100x100\>",
+ filename: filename_with_correct_ext,
+ )
end
extract_image_info!
@@ -524,16 +626,17 @@ class UploadCreator
end
def svg_allowlist_xpath
- @@svg_allowlist_xpath ||= "//*[#{ALLOWED_SVG_ELEMENTS.map { |e| "name()!='#{e}'" }.join(" and ") }]"
+ @@svg_allowlist_xpath ||=
+ "//*[#{ALLOWED_SVG_ELEMENTS.map { |e| "name()!='#{e}'" }.join(" and ")}]"
end
def add_metadata!
@upload.for_private_message = true if @opts[:for_private_message]
- @upload.for_group_message = true if @opts[:for_group_message]
- @upload.for_theme = true if @opts[:for_theme]
- @upload.for_export = true if @opts[:for_export]
- @upload.for_site_setting = true if @opts[:for_site_setting]
- @upload.for_gravatar = true if @opts[:for_gravatar]
+ @upload.for_group_message = true if @opts[:for_group_message]
+ @upload.for_theme = true if @opts[:for_theme]
+ @upload.for_export = true if @opts[:for_export]
+ @upload.for_site_setting = true if @opts[:for_site_setting]
+ @upload.for_gravatar = true if @opts[:for_gravatar]
end
private
@@ -541,25 +644,31 @@ class UploadCreator
def animated?
return @animated if @animated != nil
- @animated ||= begin
- is_animated = FastImage.animated?(@file)
- type = @image_info.type.to_s
-
- if is_animated != nil
- # FastImage will return nil if it cannot determine if animated
- is_animated
- elsif type == "gif" || type == "webp"
- # Only GIFs, WEBPs and a few other unsupported image types can be animated
- OptimizedImage.ensure_safe_paths!(@file.path)
-
- command = ["identify", "-format", "%n\\n", @file.path]
- frames = Discourse::Utils.execute_command(*command, timeout: Upload::MAX_IDENTIFY_SECONDS).to_i rescue 1
-
- frames > 1
- else
- false
+ @animated ||=
+ begin
+ is_animated = FastImage.animated?(@file)
+ type = @image_info.type.to_s
+
+ if is_animated != nil
+ # FastImage will return nil if it cannot determine if animated
+ is_animated
+ elsif type == "gif" || type == "webp"
+ # Only GIFs, WEBPs and a few other unsupported image types can be animated
+ OptimizedImage.ensure_safe_paths!(@file.path)
+
+ command = ["identify", "-format", "%n\\n", @file.path]
+ frames =
+ begin
+ Discourse::Utils.execute_command(*command, timeout: Upload::MAX_IDENTIFY_SECONDS).to_i
+ rescue StandardError
+ 1
+ end
+
+ frames > 1
+ else
+ false
+ end
end
- end
end
def generate_fake_sha1_hash
diff --git a/lib/upload_fixer.rb b/lib/upload_fixer.rb
index e1846466601..799824b6895 100644
--- a/lib/upload_fixer.rb
+++ b/lib/upload_fixer.rb
@@ -2,9 +2,9 @@
class UploadFixer
def self.fix_all_extensions
- Upload.where("uploads.extension IS NOT NULL").find_each do |upload|
- fix_extension_on_upload(upload)
- end
+ Upload
+ .where("uploads.extension IS NOT NULL")
+ .find_each { |upload| fix_extension_on_upload(upload) }
end
def self.fix_extension_on_upload(upload)
@@ -22,14 +22,11 @@ class UploadFixer
current_extension = upload.extension.to_s.downcase
if correct_extension.present?
- correct_extension = 'jpg' if correct_extension == 'jpeg'
- current_extension = 'jpg' if current_extension == 'jpeg'
+ correct_extension = "jpg" if correct_extension == "jpeg"
+ current_extension = "jpg" if current_extension == "jpeg"
if correct_extension != current_extension
- new_filename = change_extension(
- upload.original_filename,
- correct_extension
- )
+ new_filename = change_extension(upload.original_filename, correct_extension)
new_url = change_extension(previous_url, correct_extension)
@@ -38,16 +35,12 @@ class UploadFixer
source = Discourse.store.get_path_for_upload(upload)
destination = change_extension(source, correct_extension)
- Discourse.store.copy_file(
- previous_url,
- source,
- destination
- )
+ Discourse.store.copy_file(previous_url, source, destination)
upload.update!(
original_filename: new_filename,
url: new_url,
- extension: correct_extension
+ extension: correct_extension,
)
DbHelper.remap(previous_url, upload.url)
@@ -59,7 +52,7 @@ class UploadFixer
upload.update!(
original_filename: new_filename,
url: new_url,
- extension: correct_extension
+ extension: correct_extension,
)
DbHelper.remap(previous_url, upload.url)
@@ -67,12 +60,8 @@ class UploadFixer
tombstone_path = source.sub("/uploads/", "/uploads/tombstone/")
FileUtils.mkdir_p(File.dirname(tombstone_path))
- FileUtils.move(
- source,
- tombstone_path
- )
+ FileUtils.move(source, tombstone_path)
end
-
end
end
rescue => e
diff --git a/lib/upload_markdown.rb b/lib/upload_markdown.rb
index b2c94917882..eae2319d625 100644
--- a/lib/upload_markdown.rb
+++ b/lib/upload_markdown.rb
@@ -27,7 +27,7 @@ class UploadMarkdown
end
def playable_media_markdown
- type = \
+ type =
if FileHelper.is_supported_audio?(@upload.original_filename)
"audio"
elsif FileHelper.is_supported_video?(@upload.original_filename)
diff --git a/lib/upload_recovery.rb b/lib/upload_recovery.rb
index 04f5ea93704..c2e340d9693 100644
--- a/lib/upload_recovery.rb
+++ b/lib/upload_recovery.rb
@@ -14,35 +14,36 @@ class UploadRecovery
begin
analyzer = PostAnalyzer.new(post.raw, post.topic_id)
- analyzer.cooked_stripped.css("img", "a").each do |media|
- if media.name == "img" && orig_src = media["data-orig-src"]
- if dom_class = media["class"]
- if (Post.allowed_image_classes & dom_class.split).count > 0
- next
+ analyzer
+ .cooked_stripped
+ .css("img", "a")
+ .each do |media|
+ if media.name == "img" && orig_src = media["data-orig-src"]
+ if dom_class = media["class"]
+ next if (Post.allowed_image_classes & dom_class.split).count > 0
end
- end
-
- if @dry_run
- puts "#{post.full_url} #{orig_src}"
- else
- recover_post_upload(post, Upload.sha1_from_short_url(orig_src))
- end
- elsif url = (media["href"] || media["src"])
- data = Upload.extract_url(url)
- next unless data
-
- upload = Upload.get_from_url(url)
- if !upload || upload.verification_status == Upload.verification_statuses[:invalid_etag]
if @dry_run
- puts "#{post.full_url} #{url}"
+ puts "#{post.full_url} #{orig_src}"
else
- sha1 = data[2]
- recover_post_upload(post, sha1)
+ recover_post_upload(post, Upload.sha1_from_short_url(orig_src))
+ end
+ elsif url = (media["href"] || media["src"])
+ data = Upload.extract_url(url)
+ next unless data
+
+ upload = Upload.get_from_url(url)
+
+ if !upload || upload.verification_status == Upload.verification_statuses[:invalid_etag]
+ if @dry_run
+ puts "#{post.full_url} #{url}"
+ else
+ sha1 = data[2]
+ recover_post_upload(post, sha1)
+ end
end
end
end
- end
rescue => e
raise e if @stop_on_error
puts "#{post.full_url} #{e.class}: #{e.message}"
@@ -54,10 +55,7 @@ class UploadRecovery
def recover_post_upload(post, sha1)
return unless valid_sha1?(sha1)
- attributes = {
- post: post,
- sha1: sha1
- }
+ attributes = { post: post, sha1: sha1 }
if Discourse.store.external?
recover_post_upload_from_s3(**attributes)
@@ -96,19 +94,12 @@ class UploadRecovery
end
def recover_from_local(sha1:, user_id:)
- @paths ||= begin
- Dir.glob(File.join(
- Discourse.store.tombstone_dir,
- 'original',
- '**',
- '*.*'
- )).concat(Dir.glob(File.join(
- Discourse.store.upload_path,
- 'original',
- '**',
- '*.*'
- )))
- end
+ @paths ||=
+ begin
+ Dir.glob(File.join(Discourse.store.tombstone_dir, "original", "**", "*.*")).concat(
+ Dir.glob(File.join(Discourse.store.upload_path, "original", "**", "*.*")),
+ )
+ end
@paths.each do |path|
if path =~ /#{sha1}/
@@ -127,20 +118,27 @@ class UploadRecovery
end
def recover_from_s3(sha1:, user_id:)
- @object_keys ||= begin
- s3_helper = Discourse.store.s3_helper
-
- if Rails.configuration.multisite
- current_db = RailsMultisite::ConnectionManagement.current_db
- s3_helper.list("uploads/#{current_db}/original").map(&:key).concat(
- s3_helper.list("uploads/#{FileStore::S3Store::TOMBSTONE_PREFIX}#{current_db}/original").map(&:key)
- )
- else
- s3_helper.list("original").map(&:key).concat(
- s3_helper.list("#{FileStore::S3Store::TOMBSTONE_PREFIX}original").map(&:key)
- )
+ @object_keys ||=
+ begin
+ s3_helper = Discourse.store.s3_helper
+
+ if Rails.configuration.multisite
+ current_db = RailsMultisite::ConnectionManagement.current_db
+ s3_helper
+ .list("uploads/#{current_db}/original")
+ .map(&:key)
+ .concat(
+ s3_helper.list(
+ "uploads/#{FileStore::S3Store::TOMBSTONE_PREFIX}#{current_db}/original",
+ ).map(&:key),
+ )
+ else
+ s3_helper
+ .list("original")
+ .map(&:key)
+ .concat(s3_helper.list("#{FileStore::S3Store::TOMBSTONE_PREFIX}original").map(&:key))
+ end
end
- end
upload_exists = Upload.exists?(sha1: sha1)
@@ -152,11 +150,7 @@ class UploadRecovery
old_key = key
key = key.sub(tombstone_prefix, "")
- Discourse.store.s3_helper.copy(
- old_key,
- key,
- options: { acl: "public-read" }
- )
+ Discourse.store.s3_helper.copy(old_key, key, options: { acl: "public-read" })
end
next if upload_exists
@@ -164,11 +158,12 @@ class UploadRecovery
url = "https:#{SiteSetting.Upload.absolute_base_url}/#{key}"
begin
- tmp = FileHelper.download(
- url,
- max_file_size: SiteSetting.max_image_size_kb.kilobytes,
- tmp_file_name: "recover_from_s3"
- )
+ tmp =
+ FileHelper.download(
+ url,
+ max_file_size: SiteSetting.max_image_size_kb.kilobytes,
+ tmp_file_name: "recover_from_s3",
+ )
if tmp
upload = create_upload(tmp, File.basename(key), user_id)
diff --git a/lib/upload_security.rb b/lib/upload_security.rb
index c784b25aa28..ccaf86f1ed4 100644
--- a/lib/upload_security.rb
+++ b/lib/upload_security.rb
@@ -56,12 +56,10 @@ class UploadSecurity
end
def should_be_secure_with_reason
- insecure_context_checks.each do |check, reason|
- return [false, reason] if perform_check(check)
- end
+ insecure_context_checks.each { |check, reason| return false, reason if perform_check(check) }
secure_context_checks.each do |check, reason|
- return [perform_check(check), reason] if priority_check?(check)
- return [true, reason] if perform_check(check)
+ return perform_check(check), reason if priority_check?(check)
+ return true, reason if perform_check(check)
end
[false, "no checks satisfied"]
@@ -123,7 +121,8 @@ class UploadSecurity
private
def access_control_post
- @access_control_post ||= @upload.access_control_post_id.present? ? @upload.access_control_post : nil
+ @access_control_post ||=
+ @upload.access_control_post_id.present? ? @upload.access_control_post : nil
end
def insecure_context_checks
@@ -132,7 +131,7 @@ class UploadSecurity
insecure_creation_for_modifiers: "one or more creation for_modifiers was satisfied",
public_type: "upload is public type",
custom_emoji: "upload is used for custom emoji",
- regular_emoji: "upload is used for regular emoji"
+ regular_emoji: "upload is used for regular emoji",
}
end
@@ -142,7 +141,7 @@ class UploadSecurity
access_control_post_has_secure_uploads: "access control post dictates security",
secure_creation_for_modifiers: "one or more creation for_modifiers was satisfied",
uploading_in_composer: "uploading via the composer",
- already_secure: "upload is already secure"
+ already_secure: "upload is already secure",
}
end
diff --git a/lib/url_helper.rb b/lib/url_helper.rb
index 6b43cf609ab..097b3866db0 100644
--- a/lib/url_helper.rb
+++ b/lib/url_helper.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class UrlHelper
-
# At the moment this handles invalid URLs that browser address bar accepts
# where second # is not encoded
#
@@ -12,7 +11,11 @@ class UrlHelper
if uri
# Addressable::URI::CharacterClasses::UNRESERVED is used here because without it
# the # in the fragment is not encoded
- fragment = Addressable::URI.encode_component(fragment, Addressable::URI::CharacterClasses::UNRESERVED) if fragment&.include?('#')
+ fragment =
+ Addressable::URI.encode_component(
+ fragment,
+ Addressable::URI::CharacterClasses::UNRESERVED,
+ ) if fragment&.include?("#")
uri.fragment = fragment
uri
end
@@ -36,16 +39,17 @@ class UrlHelper
end
def self.is_local(url)
- url.present? && (
- Discourse.store.has_been_uploaded?(url) ||
- !!(url =~ Regexp.new("^#{Discourse.base_path}/(assets|plugins|images)/")) ||
- url.start_with?(Discourse.asset_host || Discourse.base_url_no_prefix)
- )
+ url.present? &&
+ (
+ Discourse.store.has_been_uploaded?(url) ||
+ !!(url =~ Regexp.new("^#{Discourse.base_path}/(assets|plugins|images)/")) ||
+ url.start_with?(Discourse.asset_host || Discourse.base_url_no_prefix)
+ )
end
def self.absolute(url, cdn = Discourse.asset_host)
- cdn = "https:#{cdn}" if cdn && cdn =~ /^\/\//
- url =~ /^\/[^\/]/ ? (cdn || Discourse.base_url_no_prefix) + url : url
+ cdn = "https:#{cdn}" if cdn && cdn =~ %r{^//}
+ url =~ %r{^/[^/]} ? (cdn || Discourse.base_url_no_prefix) + url : url
end
def self.absolute_without_cdn(url)
@@ -64,7 +68,7 @@ class UrlHelper
Discourse.deprecate(
"UrlHelper.escape_uri is deprecated. For normalization of user input use `.normalized_encode`. For true encoding, use `.encode`",
output_in_test: true,
- drop_from: '3.0'
+ drop_from: "3.0",
)
normalized_encode(uri)
end
@@ -80,15 +84,11 @@ class UrlHelper
# Hopefully we can simplify this back to `Addressable::URI.normalized_encode` in the future.
# edge case where we expect mailto:test%40test.com to normalize to mailto:[email protected]
- if url.match(/\Amailto:/)
- return normalize_with_addressable(url)
- end
+ return normalize_with_addressable(url) if url.match(/\Amailto:/)
# If it doesn't pass the regexp, it's definitely not gonna parse with URI.parse. Skip
# to addressable
- if !url.match?(/\A#{URI::regexp}\z/)
- return normalize_with_addressable(url)
- end
+ return normalize_with_addressable(url) if !url.match?(/\A#{URI.regexp}\z/)
begin
normalize_with_ruby_uri(url)
@@ -153,9 +153,7 @@ class UrlHelper
def self.normalize_with_addressable(url)
u = Addressable::URI.normalized_encode(url, Addressable::URI)
- if u.host && !u.host.ascii_only?
- u.host = ::Addressable::IDNA.to_ascii(u.host)
- end
+ u.host = ::Addressable::IDNA.to_ascii(u.host) if u.host && !u.host.ascii_only?
u.to_s
end
@@ -163,15 +161,10 @@ class UrlHelper
def self.normalize_with_ruby_uri(url)
u = URI.parse(url)
- if u.scheme && u.scheme != u.scheme.downcase
- u.scheme = u.scheme.downcase
- end
+ u.scheme = u.scheme.downcase if u.scheme && u.scheme != u.scheme.downcase
- if u.host && u.host != u.host.downcase
- u.host = u.host.downcase
- end
+ u.host = u.host.downcase if u.host && u.host != u.host.downcase
u.to_s
end
-
end
diff --git a/lib/user_comm_screener.rb b/lib/user_comm_screener.rb
index 7d575f80724..6593606dc8a 100644
--- a/lib/user_comm_screener.rb
+++ b/lib/user_comm_screener.rb
@@ -35,8 +35,11 @@ class UserCommScreener
attr_reader :acting_user, :preferences
class UserCommPref
- attr_accessor :user_id, :is_muting, :is_ignoring, :is_disallowing_all_pms,
- :is_disallowing_pms_from_acting_user
+ attr_accessor :user_id,
+ :is_muting,
+ :is_ignoring,
+ :is_disallowing_all_pms,
+ :is_disallowing_pms_from_acting_user
def initialize(preferences)
@user_id = preferences[:user_id]
@@ -59,45 +62,42 @@ class UserCommScreener
end
end
- UserCommPrefs = Struct.new(:acting_user, :user_preference_map) do
- def acting_user_staff?
- acting_user.staff?
- end
+ UserCommPrefs =
+ Struct.new(:acting_user, :user_preference_map) do
+ def acting_user_staff?
+ acting_user.staff?
+ end
- def user_ids
- user_preference_map.keys
- end
+ def user_ids
+ user_preference_map.keys
+ end
- def for_user(user_id)
- user_preference_map[user_id]
- end
+ def for_user(user_id)
+ user_preference_map[user_id]
+ end
- def allowing_actor_communication
- return user_preference_map.values if acting_user_staff?
- user_preference_map.reject do |user_id, pref|
- pref.communication_prevented?
- end.values
- end
+ def allowing_actor_communication
+ return user_preference_map.values if acting_user_staff?
+ user_preference_map.reject { |user_id, pref| pref.communication_prevented? }.values
+ end
- def preventing_actor_communication
- return [] if acting_user_staff?
- user_preference_map.select do |user_id, pref|
- pref.communication_prevented?
- end.values
- end
+ def preventing_actor_communication
+ return [] if acting_user_staff?
+ user_preference_map.select { |user_id, pref| pref.communication_prevented? }.values
+ end
- def ignoring_or_muting?(user_id)
- return false if acting_user_staff?
- pref = for_user(user_id)
- pref.present? && pref.ignoring_or_muting?
- end
+ def ignoring_or_muting?(user_id)
+ return false if acting_user_staff?
+ pref = for_user(user_id)
+ pref.present? && pref.ignoring_or_muting?
+ end
- def disallowing_pms?(user_id)
- return false if acting_user_staff?
- pref = for_user(user_id)
- pref.present? && pref.disallowing_pms?
+ def disallowing_pms?(user_id)
+ return false if acting_user_staff?
+ pref = for_user(user_id)
+ pref.present? && pref.disallowing_pms?
+ end
end
- end
private_constant :UserCommPref
private_constant :UserCommPrefs
@@ -148,7 +148,10 @@ class UserCommScreener
end
def actor_preventing_communication
- (actor_preferences[:ignoring] + actor_preferences[:muting] + actor_preferences[:disallowed_pms_from]).uniq
+ (
+ actor_preferences[:ignoring] + actor_preferences[:muting] +
+ actor_preferences[:disallowed_pms_from]
+ ).uniq
end
##
@@ -204,7 +207,7 @@ class UserCommScreener
is_muting: user.is_muting,
is_ignoring: user.is_ignoring,
is_disallowing_all_pms: user.is_disallowing_all_pms,
- is_disallowing_pms_from_acting_user: false
+ is_disallowing_pms_from_acting_user: false,
)
end
@@ -214,22 +217,25 @@ class UserCommScreener
if users_with_allowed_pms.any?
user_ids_with_allowed_pms = users_with_allowed_pms.map(&:id)
- user_ids_acting_can_pm = AllowedPmUser.where(
- allowed_pm_user_id: acting_user.id, user_id: user_ids_with_allowed_pms
- ).pluck(:user_id).uniq
+ user_ids_acting_can_pm =
+ AllowedPmUser
+ .where(allowed_pm_user_id: acting_user.id, user_id: user_ids_with_allowed_pms)
+ .pluck(:user_id)
+ .uniq
# If not in the list mark them as not accepting communication.
user_ids_acting_cannot_pm = user_ids_with_allowed_pms - user_ids_acting_can_pm
user_ids_acting_cannot_pm.each do |user_id|
if resolved_user_communication_preferences[user_id]
- resolved_user_communication_preferences[user_id].is_disallowing_pms_from_acting_user = true
+ resolved_user_communication_preferences[user_id].is_disallowing_pms_from_acting_user =
+ true
else
resolved_user_communication_preferences[user_id] = UserCommPref.new(
user_id: user_id,
is_muting: false,
is_ignoring: false,
is_disallowing_all_pms: false,
- is_disallowing_pms_from_acting_user: true
+ is_disallowing_pms_from_acting_user: true,
)
end
end
@@ -239,28 +245,31 @@ class UserCommScreener
end
def actor_preferences
- @actor_preferences ||= begin
- user_ids_by_preference_type = actor_communication_preferences.reduce({}) do |hash, pref|
- hash[pref.preference_type] ||= []
- hash[pref.preference_type] << pref.target_user_id
- hash
+ @actor_preferences ||=
+ begin
+ user_ids_by_preference_type =
+ actor_communication_preferences.reduce({}) do |hash, pref|
+ hash[pref.preference_type] ||= []
+ hash[pref.preference_type] << pref.target_user_id
+ hash
+ end
+ disallowed_pms_from =
+ if acting_user.user_option.enable_allowed_pm_users
+ (user_ids_by_preference_type["disallowed_pm"] || [])
+ else
+ []
+ end
+ {
+ muting: user_ids_by_preference_type["muted"] || [],
+ ignoring: user_ids_by_preference_type["ignored"] || [],
+ disallowed_pms_from: disallowed_pms_from,
+ }
end
- disallowed_pms_from = \
- if acting_user.user_option.enable_allowed_pm_users
- (user_ids_by_preference_type["disallowed_pm"] || [])
- else
- []
- end
- {
- muting: user_ids_by_preference_type["muted"] || [],
- ignoring: user_ids_by_preference_type["ignored"] || [],
- disallowed_pms_from: disallowed_pms_from
- }
- end
end
def user_communication_preferences
- @user_communication_preferences ||= DB.query(<<~SQL, acting_user_id: acting_user.id, target_user_ids: @target_users.keys)
+ @user_communication_preferences ||=
+ DB.query(<<~SQL, acting_user_id: acting_user.id, target_user_ids: @target_users.keys)
SELECT users.id,
CASE WHEN muted_users.muted_user_id IS NOT NULL THEN true ELSE false END AS is_muting,
CASE WHEN ignored_users.ignored_user_id IS NOT NULL THEN true ELSE false END AS is_ignoring,
@@ -281,7 +290,8 @@ class UserCommScreener
end
def actor_communication_preferences
- @actor_communication_preferences ||= DB.query(<<~SQL, acting_user_id: acting_user.id, target_user_ids: @target_users.keys)
+ @actor_communication_preferences ||=
+ DB.query(<<~SQL, acting_user_id: acting_user.id, target_user_ids: @target_users.keys)
SELECT users.id AS target_user_id, 'disallowed_pm' AS preference_type FROM users
LEFT JOIN allowed_pm_users ON allowed_pm_users.allowed_pm_user_id = users.id
WHERE users.id IN (:target_user_ids)
diff --git a/lib/user_lookup.rb b/lib/user_lookup.rb
index 92ca3806bd2..97535eaf4bf 100644
--- a/lib/user_lookup.rb
+++ b/lib/user_lookup.rb
@@ -2,11 +2,21 @@
class UserLookup
def self.lookup_columns
- @user_lookup_columns ||= %i{id username name uploaded_avatar_id primary_group_id flair_group_id admin moderator trust_level}
+ @user_lookup_columns ||= %i[
+ id
+ username
+ name
+ uploaded_avatar_id
+ primary_group_id
+ flair_group_id
+ admin
+ moderator
+ trust_level
+ ]
end
def self.group_lookup_columns
- @group_lookup_columns ||= %i{id name flair_icon flair_upload_id flair_bg_color flair_color}
+ @group_lookup_columns ||= %i[id name flair_icon flair_upload_id flair_bg_color flair_color]
end
def initialize(user_ids = [])
@@ -19,23 +29,29 @@ class UserLookup
end
def primary_groups
- @primary_groups ||= users.values.each_with_object({}) do |user, hash|
- if user.primary_group_id
- group = groups[user.primary_group_id]
- set_user_group_preload(user, group, :primary_group)
- hash[user.id] = group
- end
- end
+ @primary_groups ||=
+ users
+ .values
+ .each_with_object({}) do |user, hash|
+ if user.primary_group_id
+ group = groups[user.primary_group_id]
+ set_user_group_preload(user, group, :primary_group)
+ hash[user.id] = group
+ end
+ end
end
def flair_groups
- @flair_groups ||= users.values.each_with_object({}) do |user, hash|
- if user.flair_group_id
- group = groups[user.flair_group_id]
- set_user_group_preload(user, group, :flair_group)
- hash[user.id] = group
- end
- end
+ @flair_groups ||=
+ users
+ .values
+ .each_with_object({}) do |user, hash|
+ if user.flair_group_id
+ group = groups[user.flair_group_id]
+ set_user_group_preload(user, group, :flair_group)
+ hash[user.id] = group
+ end
+ end
end
private
@@ -46,24 +62,22 @@ class UserLookup
end
def users
- @users ||= User
- .where(id: @user_ids)
- .select(self.class.lookup_columns)
- .index_by(&:id)
+ @users ||= User.where(id: @user_ids).select(self.class.lookup_columns).index_by(&:id)
end
def groups
- @group_lookup ||= begin
- group_ids = users.values.map { |u| [u.primary_group_id, u.flair_group_id] }
- group_ids.flatten!
- group_ids.uniq!
- group_ids.compact!
+ @group_lookup ||=
+ begin
+ group_ids = users.values.map { |u| [u.primary_group_id, u.flair_group_id] }
+ group_ids.flatten!
+ group_ids.uniq!
+ group_ids.compact!
- Group
- .includes(:flair_upload)
- .where(id: group_ids)
- .select(self.class.group_lookup_columns)
- .index_by(&:id)
- end
+ Group
+ .includes(:flair_upload)
+ .where(id: group_ids)
+ .select(self.class.group_lookup_columns)
+ .index_by(&:id)
+ end
end
end
diff --git a/lib/user_name_suggester.rb b/lib/user_name_suggester.rb
index e964dbf8109..dc63d476b0b 100644
--- a/lib/user_name_suggester.rb
+++ b/lib/user_name_suggester.rb
@@ -1,14 +1,15 @@
# frozen_string_literal: true
module UserNameSuggester
- GENERIC_NAMES = ['i', 'me', 'info', 'support', 'admin', 'webmaster', 'hello', 'mail', 'office', 'contact', 'team']
+ GENERIC_NAMES = %w[i me info support admin webmaster hello mail office contact team]
LAST_RESORT_USERNAME = "user"
- def self.suggest(*input, current_username: nil)
- name = input.find do |item|
- parsed_name = parse_name_from_email(item)
- break parsed_name if sanitize_username(parsed_name).present?
- end
+ def self.suggest(*input, current_username: nil)
+ name =
+ input.find do |item|
+ parsed_name = parse_name_from_email(item)
+ break parsed_name if sanitize_username(parsed_name).present?
+ end
name = fix_username(name)
find_available_username_based_on(name, current_username)
@@ -35,12 +36,7 @@ module UserNameSuggester
original_allowed_username = current_username
current_username = User.normalize_username(current_username) if current_username
- until (
- normalized_attempt == current_username ||
- User.username_available?(attempt) ||
- i > 100
- )
-
+ until (normalized_attempt == current_username || User.username_available?(attempt) || i > 100)
if offset.nil?
normalized = User.normalize_username(name)
similar = "#{normalized}(0|1|2|3|4|5|6|7|8|9)+"
@@ -52,11 +48,10 @@ module UserNameSuggester
SQL
if count > 0
-
params = {
count: count + 10,
name: normalized,
- allowed_normalized: current_username || ''
+ allowed_normalized: current_username || "",
}
# increasing the search space a bit to allow for some extra noise
@@ -106,7 +101,7 @@ module UserNameSuggester
def self.fix_username(name)
fixed_username = sanitize_username(name)
if fixed_username.empty?
- fixed_username << sanitize_username(I18n.t('fallback_username'))
+ fixed_username << sanitize_username(I18n.t("fallback_username"))
fixed_username << LAST_RESORT_USERNAME if fixed_username.empty?
end
@@ -121,7 +116,7 @@ module UserNameSuggester
# TODO: Jan 2022, review if still needed
# see: https://meta.discourse.org/t/unicode-username-with-as-the-final-char-leads-to-an-error-loading-profile-page/173182
- if name.include?('Σ')
+ if name.include?("Σ")
ctx = MiniRacer::Context.new
name = ctx.eval("#{name.to_s.to_json}.toLowerCase()")
ctx.dispose
@@ -130,27 +125,25 @@ module UserNameSuggester
name = ActiveSupport::Inflector.transliterate(name)
end
- name.gsub!(UsernameValidator.invalid_char_pattern, '_')
+ name.gsub!(UsernameValidator.invalid_char_pattern, "_")
name = apply_allowlist(name) if UsernameValidator.char_allowlist_exists?
- name.gsub!(UsernameValidator::INVALID_LEADING_CHAR_PATTERN, '')
+ name.gsub!(UsernameValidator::INVALID_LEADING_CHAR_PATTERN, "")
name.gsub!(UsernameValidator::CONFUSING_EXTENSIONS, "_")
- name.gsub!(UsernameValidator::INVALID_TRAILING_CHAR_PATTERN, '')
- name.gsub!(UsernameValidator::REPEATED_SPECIAL_CHAR_PATTERN, '_')
+ name.gsub!(UsernameValidator::INVALID_TRAILING_CHAR_PATTERN, "")
+ name.gsub!(UsernameValidator::REPEATED_SPECIAL_CHAR_PATTERN, "_")
name
end
def self.apply_allowlist(name)
- name.grapheme_clusters
- .map { |c| UsernameValidator.allowed_char?(c) ? c : '_' }
- .join
+ name.grapheme_clusters.map { |c| UsernameValidator.allowed_char?(c) ? c : "_" }.join
end
def self.rightsize_username(name)
name = truncate(name, User.username_length.end)
- name.gsub!(UsernameValidator::INVALID_TRAILING_CHAR_PATTERN, '')
+ name.gsub!(UsernameValidator::INVALID_TRAILING_CHAR_PATTERN, "")
missing_char_count = User.username_length.begin - name.grapheme_clusters.size
- name << '1' * missing_char_count if missing_char_count > 0
+ name << "1" * missing_char_count if missing_char_count > 0
name
end
diff --git a/lib/validators/allow_user_locale_enabled_validator.rb b/lib/validators/allow_user_locale_enabled_validator.rb
index 0998950a2bd..573471fabd5 100644
--- a/lib/validators/allow_user_locale_enabled_validator.rb
+++ b/lib/validators/allow_user_locale_enabled_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class AllowUserLocaleEnabledValidator
-
def initialize(opts = {})
@opts = opts
end
@@ -16,5 +15,4 @@ class AllowUserLocaleEnabledValidator
def error_message
I18n.t("site_settings.errors.user_locale_not_enabled")
end
-
end
diff --git a/lib/validators/allowed_ip_address_validator.rb b/lib/validators/allowed_ip_address_validator.rb
index d2f008f27d4..f8c231aa5ae 100644
--- a/lib/validators/allowed_ip_address_validator.rb
+++ b/lib/validators/allowed_ip_address_validator.rb
@@ -1,16 +1,15 @@
# frozen_string_literal: true
class AllowedIpAddressValidator < ActiveModel::EachValidator
-
def validate_each(record, attribute, value)
if record.ip_address
if ScreenedIpAddress.should_block?(record.ip_address)
- record.errors.add(attribute, I18n.t('user.ip_address.blocked'))
+ record.errors.add(attribute, I18n.t("user.ip_address.blocked"))
end
- if record.trust_level == TrustLevel[0] && SpamHandler.should_prevent_registration_from_ip?(record.ip_address)
- record.errors.add(attribute, I18n.t('user.ip_address.max_new_accounts_per_registration_ip'))
+ if record.trust_level == TrustLevel[0] &&
+ SpamHandler.should_prevent_registration_from_ip?(record.ip_address)
+ record.errors.add(attribute, I18n.t("user.ip_address.max_new_accounts_per_registration_ip"))
end
end
end
-
end
diff --git a/lib/validators/alternative_reply_by_email_addresses_validator.rb b/lib/validators/alternative_reply_by_email_addresses_validator.rb
index 0c39cde7399..3136483c1b4 100644
--- a/lib/validators/alternative_reply_by_email_addresses_validator.rb
+++ b/lib/validators/alternative_reply_by_email_addresses_validator.rb
@@ -13,6 +13,6 @@ class AlternativeReplyByEmailAddressesValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_alternative_reply_by_email_addresses')
+ I18n.t("site_settings.errors.invalid_alternative_reply_by_email_addresses")
end
end
diff --git a/lib/validators/categories_topics_validator.rb b/lib/validators/categories_topics_validator.rb
index 23552803d82..3f7b13a5e1f 100644
--- a/lib/validators/categories_topics_validator.rb
+++ b/lib/validators/categories_topics_validator.rb
@@ -14,6 +14,6 @@ class CategoriesTopicsValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_integer_min', min: 5)
+ I18n.t("site_settings.errors.invalid_integer_min", min: 5)
end
end
diff --git a/lib/validators/censored_words_validator.rb b/lib/validators/censored_words_validator.rb
index eacc69f9e5d..e69b7f77806 100644
--- a/lib/validators/censored_words_validator.rb
+++ b/lib/validators/censored_words_validator.rb
@@ -10,7 +10,7 @@ class CensoredWordsValidator < ActiveModel::EachValidator
record.errors.add(
attribute,
:contains_censored_words,
- censored_words: join_censored_words(censored_words)
+ censored_words: join_censored_words(censored_words),
)
end
end
diff --git a/lib/validators/color_list_validator.rb b/lib/validators/color_list_validator.rb
index be6395564df..cbe019c044f 100644
--- a/lib/validators/color_list_validator.rb
+++ b/lib/validators/color_list_validator.rb
@@ -11,6 +11,6 @@ class ColorListValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_hex_value')
+ I18n.t("site_settings.errors.invalid_hex_value")
end
end
diff --git a/lib/validators/css_color_validator.rb b/lib/validators/css_color_validator.rb
index 630e9cad57c..fdc1fe8f28a 100644
--- a/lib/validators/css_color_validator.rb
+++ b/lib/validators/css_color_validator.rb
@@ -1,29 +1,155 @@
# frozen_string_literal: true
class CssColorValidator
- COLORS = %w{
- aliceblue antiquewhite aqua aquamarine azure beige bisque black
- blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse
- chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan
- darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta
- darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen
- darkslateblue darkslategray darkslategrey darkturquoise darkviolet
- deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite
- forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green
- greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender
- lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan
- lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon
- lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue
- lightyellow lime limegreen linen magenta maroon mediumaquamarine
- mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue
- mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream
- mistyrose moccasin navajowhite navy oldlace olive olivedrab orange
- orangered orchid palegoldenrod palegreen paleturquoise palevioletred
- papayawhip peachpuff peru pink plum powderblue purple red rosybrown
- royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver
- skyblue slateblue slategray slategrey snow springgreen steelblue tan teal
- thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen
- }
+ COLORS = %w[
+ aliceblue
+ antiquewhite
+ aqua
+ aquamarine
+ azure
+ beige
+ bisque
+ black
+ blanchedalmond
+ blue
+ blueviolet
+ brown
+ burlywood
+ cadetblue
+ chartreuse
+ chocolate
+ coral
+ cornflowerblue
+ cornsilk
+ crimson
+ cyan
+ darkblue
+ darkcyan
+ darkgoldenrod
+ darkgray
+ darkgreen
+ darkgrey
+ darkkhaki
+ darkmagenta
+ darkolivegreen
+ darkorange
+ darkorchid
+ darkred
+ darksalmon
+ darkseagreen
+ darkslateblue
+ darkslategray
+ darkslategrey
+ darkturquoise
+ darkviolet
+ deeppink
+ deepskyblue
+ dimgray
+ dimgrey
+ dodgerblue
+ firebrick
+ floralwhite
+ forestgreen
+ fuchsia
+ gainsboro
+ ghostwhite
+ gold
+ goldenrod
+ gray
+ green
+ greenyellow
+ grey
+ honeydew
+ hotpink
+ indianred
+ indigo
+ ivory
+ khaki
+ lavender
+ lavenderblush
+ lawngreen
+ lemonchiffon
+ lightblue
+ lightcoral
+ lightcyan
+ lightgoldenrodyellow
+ lightgray
+ lightgreen
+ lightgrey
+ lightpink
+ lightsalmon
+ lightseagreen
+ lightskyblue
+ lightslategray
+ lightslategrey
+ lightsteelblue
+ lightyellow
+ lime
+ limegreen
+ linen
+ magenta
+ maroon
+ mediumaquamarine
+ mediumblue
+ mediumorchid
+ mediumpurple
+ mediumseagreen
+ mediumslateblue
+ mediumspringgreen
+ mediumturquoise
+ mediumvioletred
+ midnightblue
+ mintcream
+ mistyrose
+ moccasin
+ navajowhite
+ navy
+ oldlace
+ olive
+ olivedrab
+ orange
+ orangered
+ orchid
+ palegoldenrod
+ palegreen
+ paleturquoise
+ palevioletred
+ papayawhip
+ peachpuff
+ peru
+ pink
+ plum
+ powderblue
+ purple
+ red
+ rosybrown
+ royalblue
+ saddlebrown
+ salmon
+ sandybrown
+ seagreen
+ seashell
+ sienna
+ silver
+ skyblue
+ slateblue
+ slategray
+ slategrey
+ snow
+ springgreen
+ steelblue
+ tan
+ teal
+ thistle
+ tomato
+ turquoise
+ violet
+ wheat
+ white
+ whitesmoke
+ yellow
+ yellowgreen
+ ]
def initialize(opts = {})
@opts = opts
diff --git a/lib/validators/default_composer_category_validator.rb b/lib/validators/default_composer_category_validator.rb
index 2ce38692ca0..274efebf38b 100644
--- a/lib/validators/default_composer_category_validator.rb
+++ b/lib/validators/default_composer_category_validator.rb
@@ -14,6 +14,6 @@ class DefaultComposerCategoryValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_uncategorized_category_setting')
+ I18n.t("site_settings.errors.invalid_uncategorized_category_setting")
end
end
diff --git a/lib/validators/delete_rejected_email_after_days_validator.rb b/lib/validators/delete_rejected_email_after_days_validator.rb
index 0ad322e7064..d6c3fccdeb1 100644
--- a/lib/validators/delete_rejected_email_after_days_validator.rb
+++ b/lib/validators/delete_rejected_email_after_days_validator.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class DeleteRejectedEmailAfterDaysValidator
- MAX = 36500
+ MAX = 36_500
def initialize(opts = {})
@opts = opts
diff --git a/lib/validators/email_setting_validator.rb b/lib/validators/email_setting_validator.rb
index f35328bfce9..55f9df3c354 100644
--- a/lib/validators/email_setting_validator.rb
+++ b/lib/validators/email_setting_validator.rb
@@ -11,6 +11,6 @@ class EmailSettingValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_email')
+ I18n.t("site_settings.errors.invalid_email")
end
end
diff --git a/lib/validators/email_validator.rb b/lib/validators/email_validator.rb
index 3f96c2d7164..aca5a069507 100644
--- a/lib/validators/email_validator.rb
+++ b/lib/validators/email_validator.rb
@@ -1,24 +1,23 @@
# frozen_string_literal: true
class EmailValidator < ActiveModel::EachValidator
-
def validate_each(record, attribute, value)
if !EmailAddressValidator.valid_value?(value)
if Invite === record && attribute == :email
- record.errors.add(:base, I18n.t(:'invite.invalid_email', email: CGI.escapeHTML(value)))
+ record.errors.add(:base, I18n.t(:"invite.invalid_email", email: CGI.escapeHTML(value)))
else
- record.errors.add(attribute, I18n.t(:'user.email.invalid'))
+ record.errors.add(attribute, I18n.t(:"user.email.invalid"))
end
invalid = true
end
if !EmailValidator.allowed?(value)
- record.errors.add(attribute, I18n.t(:'user.email.not_allowed'))
+ record.errors.add(attribute, I18n.t(:"user.email.not_allowed"))
invalid = true
end
if !invalid && ScreenedEmail.should_block?(value)
- record.errors.add(attribute, I18n.t(:'user.email.blocked'))
+ record.errors.add(attribute, I18n.t(:"user.email.blocked"))
end
end
@@ -41,20 +40,21 @@ class EmailValidator < ActiveModel::EachValidator
end
def self.email_in_restriction_setting?(setting, value)
- domains = setting.gsub('.', '\.')
+ domains = setting.gsub(".", '\.')
regexp = Regexp.new("@(.+\\.)?(#{domains})$", true)
value =~ regexp
end
def self.is_developer?(value)
- Rails.configuration.respond_to?(:developer_emails) && Rails.configuration.developer_emails.include?(value)
+ Rails.configuration.respond_to?(:developer_emails) &&
+ Rails.configuration.developer_emails.include?(value)
end
def self.email_regex
Discourse.deprecate(
"EmailValidator.email_regex is deprecated. Please use EmailAddressValidator instead.",
output_in_test: true,
- drop_from: '2.9.0',
+ drop_from: "2.9.0",
)
EmailAddressValidator.email_regex
end
diff --git a/lib/validators/enable_invite_only_validator.rb b/lib/validators/enable_invite_only_validator.rb
index b2efcdf83f5..89e062ff162 100644
--- a/lib/validators/enable_invite_only_validator.rb
+++ b/lib/validators/enable_invite_only_validator.rb
@@ -6,11 +6,11 @@ class EnableInviteOnlyValidator
end
def valid_value?(val)
- return true if val == 'f'
+ return true if val == "f"
!SiteSetting.enable_discourse_connect?
end
def error_message
- I18n.t('site_settings.errors.discourse_connect_invite_only')
+ I18n.t("site_settings.errors.discourse_connect_invite_only")
end
end
diff --git a/lib/validators/enable_local_logins_via_email_validator.rb b/lib/validators/enable_local_logins_via_email_validator.rb
index 46021e9b244..c0a40dcf46f 100644
--- a/lib/validators/enable_local_logins_via_email_validator.rb
+++ b/lib/validators/enable_local_logins_via_email_validator.rb
@@ -6,11 +6,11 @@ class EnableLocalLoginsViaEmailValidator
end
def valid_value?(val)
- return true if val == 'f'
+ return true if val == "f"
SiteSetting.enable_local_logins
end
def error_message
- I18n.t('site_settings.errors.enable_local_logins_disabled')
+ I18n.t("site_settings.errors.enable_local_logins_disabled")
end
end
diff --git a/lib/validators/enable_private_email_messages_validator.rb b/lib/validators/enable_private_email_messages_validator.rb
index 932b63f5ada..cd961932d25 100644
--- a/lib/validators/enable_private_email_messages_validator.rb
+++ b/lib/validators/enable_private_email_messages_validator.rb
@@ -1,15 +1,13 @@
# frozen_string_literal: true
class EnablePrivateEmailMessagesValidator
-
def initialize(opts = {})
@opts = opts
end
def valid_value?(val)
return true if val == "f"
- SiteSetting.enable_staged_users &&
- SiteSetting.reply_by_email_enabled
+ SiteSetting.enable_staged_users && SiteSetting.reply_by_email_enabled
end
def error_message
diff --git a/lib/validators/enable_sso_validator.rb b/lib/validators/enable_sso_validator.rb
index d3701b89d03..3d75391f53b 100644
--- a/lib/validators/enable_sso_validator.rb
+++ b/lib/validators/enable_sso_validator.rb
@@ -6,18 +6,24 @@ class EnableSsoValidator
end
def valid_value?(val)
- return true if val == 'f'
- return false if SiteSetting.discourse_connect_url.blank? || SiteSetting.invite_only? || is_2fa_enforced?
+ return true if val == "f"
+ if SiteSetting.discourse_connect_url.blank? || SiteSetting.invite_only? || is_2fa_enforced?
+ return false
+ end
true
end
def error_message
- return I18n.t('site_settings.errors.discourse_connect_url_is_empty') if SiteSetting.discourse_connect_url.blank?
- return I18n.t('site_settings.errors.discourse_connect_invite_only') if SiteSetting.invite_only?
- return I18n.t('site_settings.errors.discourse_connect_cannot_be_enabled_if_second_factor_enforced') if is_2fa_enforced?
+ if SiteSetting.discourse_connect_url.blank?
+ return I18n.t("site_settings.errors.discourse_connect_url_is_empty")
+ end
+ return I18n.t("site_settings.errors.discourse_connect_invite_only") if SiteSetting.invite_only?
+ if is_2fa_enforced?
+ I18n.t("site_settings.errors.discourse_connect_cannot_be_enabled_if_second_factor_enforced")
+ end
end
def is_2fa_enforced?
- SiteSetting.enforce_second_factor? != 'no'
+ SiteSetting.enforce_second_factor? != "no"
end
end
diff --git a/lib/validators/google_oauth2_hd_groups_validator.rb b/lib/validators/google_oauth2_hd_groups_validator.rb
index 39acf6b9bf7..4d2a3b70b4c 100644
--- a/lib/validators/google_oauth2_hd_groups_validator.rb
+++ b/lib/validators/google_oauth2_hd_groups_validator.rb
@@ -6,7 +6,13 @@ class GoogleOauth2HdGroupsValidator
end
def valid_value?(value)
- @valid = value == "f" || (SiteSetting.google_oauth2_hd.present? && SiteSetting.google_oauth2_hd_groups_service_account_admin_email.present? && SiteSetting.google_oauth2_hd_groups_service_account_json.present?)
+ @valid =
+ value == "f" ||
+ (
+ SiteSetting.google_oauth2_hd.present? &&
+ SiteSetting.google_oauth2_hd_groups_service_account_admin_email.present? &&
+ SiteSetting.google_oauth2_hd_groups_service_account_json.present?
+ )
end
def error_message
diff --git a/lib/validators/group_setting_validator.rb b/lib/validators/group_setting_validator.rb
index 31be1eb3178..9442b2b4950 100644
--- a/lib/validators/group_setting_validator.rb
+++ b/lib/validators/group_setting_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class GroupSettingValidator
-
def initialize(opts = {})
@opts = opts
end
@@ -11,6 +10,6 @@ class GroupSettingValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_group')
+ I18n.t("site_settings.errors.invalid_group")
end
end
diff --git a/lib/validators/host_list_setting_validator.rb b/lib/validators/host_list_setting_validator.rb
index 93d51aa2b03..b60cec76df8 100644
--- a/lib/validators/host_list_setting_validator.rb
+++ b/lib/validators/host_list_setting_validator.rb
@@ -10,6 +10,6 @@ class HostListSettingValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_domain_hostname')
+ I18n.t("site_settings.errors.invalid_domain_hostname")
end
end
diff --git a/lib/validators/integer_setting_validator.rb b/lib/validators/integer_setting_validator.rb
index 0d785f202f5..0a0f5789642 100644
--- a/lib/validators/integer_setting_validator.rb
+++ b/lib/validators/integer_setting_validator.rb
@@ -17,13 +17,13 @@ class IntegerSettingValidator
def error_message
if @opts[:min] && @opts[:max]
- I18n.t('site_settings.errors.invalid_integer_min_max', min: @opts[:min], max: @opts[:max])
+ I18n.t("site_settings.errors.invalid_integer_min_max", min: @opts[:min], max: @opts[:max])
elsif @opts[:min]
- I18n.t('site_settings.errors.invalid_integer_min', min: @opts[:min])
+ I18n.t("site_settings.errors.invalid_integer_min", min: @opts[:min])
elsif @opts[:max]
- I18n.t('site_settings.errors.invalid_integer_max', max: @opts[:max])
+ I18n.t("site_settings.errors.invalid_integer_max", max: @opts[:max])
else
- I18n.t('site_settings.errors.invalid_integer')
+ I18n.t("site_settings.errors.invalid_integer")
end
end
end
diff --git a/lib/validators/ip_address_format_validator.rb b/lib/validators/ip_address_format_validator.rb
index 53ee97210f1..f01aaca3891 100644
--- a/lib/validators/ip_address_format_validator.rb
+++ b/lib/validators/ip_address_format_validator.rb
@@ -3,7 +3,6 @@
# Allows unique IP address (10.0.1.20), and IP addresses with a mask (10.0.0.0/8).
# Useful when storing in a Postgresql inet column.
class IpAddressFormatValidator < ActiveModel::EachValidator
-
def validate_each(record, attribute, value)
# In Rails 4.0.0, ip_address will be nil if an invalid IP address was assigned.
# https://github.com/jetthoughts/rails/commit/0aa95a71b04f2893921c58a7c1d9fca60dbdcbc2
@@ -14,9 +13,6 @@ class IpAddressFormatValidator < ActiveModel::EachValidator
# So this validator doesn't actually do anything anymore.
# But let's keep it in case a future version of rails fixes the problem and allows
# validators to work on inet and cidr columns.
- if record.ip_address.nil?
- record.errors.add(attribute, :invalid)
- end
+ record.errors.add(attribute, :invalid) if record.ip_address.nil?
end
-
end
diff --git a/lib/validators/markdown_linkify_tlds_validator.rb b/lib/validators/markdown_linkify_tlds_validator.rb
index fbde2026226..84e616d7441 100644
--- a/lib/validators/markdown_linkify_tlds_validator.rb
+++ b/lib/validators/markdown_linkify_tlds_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class MarkdownLinkifyTldsValidator
-
def initialize(opts = {})
@opts = opts
end
diff --git a/lib/validators/max_emojis_validator.rb b/lib/validators/max_emojis_validator.rb
index 87d6b10b749..4471ba296b7 100644
--- a/lib/validators/max_emojis_validator.rb
+++ b/lib/validators/max_emojis_validator.rb
@@ -1,13 +1,15 @@
# frozen_string_literal: true
class MaxEmojisValidator < ActiveModel::EachValidator
-
def validate_each(record, attribute, value)
- unescaped_title = PrettyText.unescape_emoji(Emoji.unicode_unescape(CGI::escapeHTML(value)))
- if unescaped_title.present? && unescaped_title.scan(/<img.+?class\s*=\s*'(emoji|emoji emoji-custom)'/).size > SiteSetting.max_emojis_in_title
+ unescaped_title = PrettyText.unescape_emoji(Emoji.unicode_unescape(CGI.escapeHTML(value)))
+ if unescaped_title.present? &&
+ unescaped_title.scan(/<img.+?class\s*=\s*'(emoji|emoji emoji-custom)'/).size >
+ SiteSetting.max_emojis_in_title
record.errors.add(
- attribute, SiteSetting.max_emojis_in_title > 0 ? :max_emojis : :emojis_disabled,
- max_emojis_count: SiteSetting.max_emojis_in_title
+ attribute,
+ SiteSetting.max_emojis_in_title > 0 ? :max_emojis : :emojis_disabled,
+ max_emojis_count: SiteSetting.max_emojis_in_title,
)
end
end
diff --git a/lib/validators/max_username_length_validator.rb b/lib/validators/max_username_length_validator.rb
index 0ee1990fe1c..fe29824f834 100644
--- a/lib/validators/max_username_length_validator.rb
+++ b/lib/validators/max_username_length_validator.rb
@@ -13,13 +13,17 @@ class MaxUsernameLengthValidator
return false
end
return false if value < SiteSetting.min_username_length
- @username = User.where('length(username) > ?', value).pluck_first(:username)
+ @username = User.where("length(username) > ?", value).pluck_first(:username)
@username.blank?
end
def error_message
if @max_range_violation
- I18n.t('site_settings.errors.invalid_integer_min_max', min: MAX_USERNAME_LENGTH_RANGE.begin, max: MAX_USERNAME_LENGTH_RANGE.end)
+ I18n.t(
+ "site_settings.errors.invalid_integer_min_max",
+ min: MAX_USERNAME_LENGTH_RANGE.begin,
+ max: MAX_USERNAME_LENGTH_RANGE.end,
+ )
elsif @username.blank?
I18n.t("site_settings.errors.max_username_length_range")
else
diff --git a/lib/validators/min_username_length_validator.rb b/lib/validators/min_username_length_validator.rb
index cee43b8a4f6..1ae9342fef1 100644
--- a/lib/validators/min_username_length_validator.rb
+++ b/lib/validators/min_username_length_validator.rb
@@ -13,13 +13,17 @@ class MinUsernameLengthValidator
return false
end
return false if value > SiteSetting.max_username_length
- @username = User.where('length(username) < ?', value).pluck_first(:username)
+ @username = User.where("length(username) < ?", value).pluck_first(:username)
@username.blank?
end
def error_message
if @min_length_violation
- I18n.t('site_settings.errors.invalid_integer_min_max', min: MIN_USERNAME_LENGTH_RANGE.begin, max: MIN_USERNAME_LENGTH_RANGE.end)
+ I18n.t(
+ "site_settings.errors.invalid_integer_min_max",
+ min: MIN_USERNAME_LENGTH_RANGE.begin,
+ max: MIN_USERNAME_LENGTH_RANGE.end,
+ )
elsif @username.blank?
I18n.t("site_settings.errors.min_username_length_range")
else
diff --git a/lib/validators/not_username_validator.rb b/lib/validators/not_username_validator.rb
index d34d4ffed91..aa7c938b96b 100644
--- a/lib/validators/not_username_validator.rb
+++ b/lib/validators/not_username_validator.rb
@@ -10,6 +10,6 @@ class NotUsernameValidator
end
def error_message
- I18n.t('site_settings.errors.valid_username')
+ I18n.t("site_settings.errors.valid_username")
end
end
diff --git a/lib/validators/password_validator.rb b/lib/validators/password_validator.rb
index 4c3e8813312..dbbda201943 100644
--- a/lib/validators/password_validator.rb
+++ b/lib/validators/password_validator.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
class PasswordValidator < ActiveModel::EachValidator
-
def validate_each(record, attribute, value)
return unless record.password_validation_required?
if value.nil?
record.errors.add(attribute, :blank)
- elsif value.length < SiteSetting.min_admin_password_length && (record.admin? || is_developer?(record.email))
+ elsif value.length < SiteSetting.min_admin_password_length &&
+ (record.admin? || is_developer?(record.email))
record.errors.add(attribute, :too_short, count: SiteSetting.min_admin_password_length)
elsif value.length < SiteSetting.min_password_length
record.errors.add(attribute, :too_short, count: SiteSetting.min_password_length)
@@ -27,7 +27,7 @@ class PasswordValidator < ActiveModel::EachValidator
end
def is_developer?(value)
- Rails.configuration.respond_to?(:developer_emails) && Rails.configuration.developer_emails.include?(value)
+ Rails.configuration.respond_to?(:developer_emails) &&
+ Rails.configuration.developer_emails.include?(value)
end
-
end
diff --git a/lib/validators/personal_message_enabled_groups_validator.rb b/lib/validators/personal_message_enabled_groups_validator.rb
index 8def3bc3e5d..d3fc92785af 100644
--- a/lib/validators/personal_message_enabled_groups_validator.rb
+++ b/lib/validators/personal_message_enabled_groups_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class PersonalMessageEnabledGroupsValidator
-
def initialize(opts = {})
@opts = opts
end
diff --git a/lib/validators/pop3_polling_enabled_setting_validator.rb b/lib/validators/pop3_polling_enabled_setting_validator.rb
index 47fdda4b0e1..d56f5ae6d82 100644
--- a/lib/validators/pop3_polling_enabled_setting_validator.rb
+++ b/lib/validators/pop3_polling_enabled_setting_validator.rb
@@ -3,7 +3,6 @@
require "net/pop"
class POP3PollingEnabledSettingValidator
-
def initialize(opts = {})
@opts = opts
end
@@ -12,10 +11,8 @@ class POP3PollingEnabledSettingValidator
# only validate when enabling polling
return true if val == "f"
# ensure we can authenticate
- SiteSetting.pop3_polling_host.present? &&
- SiteSetting.pop3_polling_username.present? &&
- SiteSetting.pop3_polling_password.present? &&
- authentication_works?
+ SiteSetting.pop3_polling_host.present? && SiteSetting.pop3_polling_username.present? &&
+ SiteSetting.pop3_polling_password.present? && authentication_works?
end
def error_message
@@ -33,19 +30,20 @@ class POP3PollingEnabledSettingValidator
private
def authentication_works?
- @authentication_works ||= begin
- EmailSettingsValidator.validate_pop3(
- host: SiteSetting.pop3_polling_host,
- port: SiteSetting.pop3_polling_port,
- ssl: SiteSetting.pop3_polling_ssl,
- username: SiteSetting.pop3_polling_username,
- password: SiteSetting.pop3_polling_password,
- openssl_verify: SiteSetting.pop3_polling_openssl_verify
- )
- rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS => err
- false
- else
- true
- end
+ @authentication_works ||=
+ begin
+ EmailSettingsValidator.validate_pop3(
+ host: SiteSetting.pop3_polling_host,
+ port: SiteSetting.pop3_polling_port,
+ ssl: SiteSetting.pop3_polling_ssl,
+ username: SiteSetting.pop3_polling_username,
+ password: SiteSetting.pop3_polling_password,
+ openssl_verify: SiteSetting.pop3_polling_openssl_verify,
+ )
+ rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS => err
+ false
+ else
+ true
+ end
end
end
diff --git a/lib/validators/post_validator.rb b/lib/validators/post_validator.rb
index 461ac8913fc..737c37c1dbf 100644
--- a/lib/validators/post_validator.rb
+++ b/lib/validators/post_validator.rb
@@ -1,12 +1,13 @@
# frozen_string_literal: true
class PostValidator < ActiveModel::Validator
-
def validate(record)
presence(record)
return if record.acting_user.try(:staged?)
- return if record.acting_user.try(:admin?) && Discourse.static_doc_topic_ids.include?(record.topic_id)
+ if record.acting_user.try(:admin?) && Discourse.static_doc_topic_ids.include?(record.topic_id)
+ return
+ end
post_body_validator(record)
max_posts_validator(record)
@@ -23,9 +24,7 @@ class PostValidator < ActiveModel::Validator
post.errors.add(:topic_id, :blank, **options) if post.topic_id.blank?
end
- if post.new_record? && post.user_id.nil?
- post.errors.add(:user_id, :blank, **options)
- end
+ post.errors.add(:user_id, :blank, **options) if post.new_record? && post.user_id.nil?
end
def post_body_validator(post)
@@ -36,16 +35,21 @@ class PostValidator < ActiveModel::Validator
end
def stripped_length(post)
- range = if private_message?(post)
- # private message
- SiteSetting.private_message_post_length
- elsif post.is_first_post? || (post.topic.present? && post.topic.posts_count == 0)
- # creating/editing first post
- post.topic&.featured_link&.present? ? (0..SiteSetting.max_post_length) : SiteSetting.first_post_length
- else
- # regular post
- SiteSetting.post_length
- end
+ range =
+ if private_message?(post)
+ # private message
+ SiteSetting.private_message_post_length
+ elsif post.is_first_post? || (post.topic.present? && post.topic.posts_count == 0)
+ # creating/editing first post
+ if post.topic&.featured_link&.present?
+ (0..SiteSetting.max_post_length)
+ else
+ SiteSetting.first_post_length
+ end
+ else
+ # regular post
+ SiteSetting.post_length
+ end
StrippedLengthValidator.validate(post, :raw, post.raw, range)
end
@@ -60,15 +64,31 @@ class PostValidator < ActiveModel::Validator
return if post.acting_user.try(:staff?)
if acting_user_is_trusted?(post) || private_message?(post)
- add_error_if_count_exceeded(post, :no_mentions_allowed, :too_many_mentions, post.raw_mentions.size, SiteSetting.max_mentions_per_post)
+ add_error_if_count_exceeded(
+ post,
+ :no_mentions_allowed,
+ :too_many_mentions,
+ post.raw_mentions.size,
+ SiteSetting.max_mentions_per_post,
+ )
else
- add_error_if_count_exceeded(post, :no_mentions_allowed_newuser, :too_many_mentions_newuser, post.raw_mentions.size, SiteSetting.newuser_max_mentions_per_post)
+ add_error_if_count_exceeded(
+ post,
+ :no_mentions_allowed_newuser,
+ :too_many_mentions_newuser,
+ post.raw_mentions.size,
+ SiteSetting.newuser_max_mentions_per_post,
+ )
end
end
def max_posts_validator(post)
- if post.new_record? && post.acting_user.present? && post.acting_user.posted_too_much_in_topic?(post.topic_id)
- post.errors.add(:base, I18n.t(:too_many_replies, count: SiteSetting.newuser_max_replies_per_topic))
+ if post.new_record? && post.acting_user.present? &&
+ post.acting_user.posted_too_much_in_topic?(post.topic_id)
+ post.errors.add(
+ :base,
+ I18n.t(:too_many_replies, count: SiteSetting.newuser_max_replies_per_topic),
+ )
end
end
@@ -82,7 +102,7 @@ class PostValidator < ActiveModel::Validator
:no_embedded_media_allowed_trust,
:no_embedded_media_allowed_trust,
post.embedded_media_count,
- 0
+ 0,
)
elsif post.acting_user.trust_level == TrustLevel[0]
add_error_if_count_exceeded(
@@ -90,7 +110,7 @@ class PostValidator < ActiveModel::Validator
:no_embedded_media_allowed,
:too_many_embedded_media,
post.embedded_media_count,
- SiteSetting.newuser_max_embedded_media
+ SiteSetting.newuser_max_embedded_media,
)
end
end
@@ -98,7 +118,13 @@ class PostValidator < ActiveModel::Validator
# Ensure new users can not put too many attachments in a post
def max_attachments_validator(post)
return if acting_user_is_trusted?(post) || private_message?(post)
- add_error_if_count_exceeded(post, :no_attachments_allowed, :too_many_attachments, post.attachment_count, SiteSetting.newuser_max_attachments)
+ add_error_if_count_exceeded(
+ post,
+ :no_attachments_allowed,
+ :too_many_attachments,
+ post.attachment_count,
+ SiteSetting.newuser_max_attachments,
+ )
end
def can_post_links_validator(post)
@@ -117,7 +143,13 @@ class PostValidator < ActiveModel::Validator
# Ensure new users can not put too many links in a post
def newuser_links_validator(post)
return if acting_user_is_trusted?(post) || private_message?(post)
- add_error_if_count_exceeded(post, :no_links_allowed, :too_many_links, post.link_count, SiteSetting.newuser_max_links)
+ add_error_if_count_exceeded(
+ post,
+ :no_links_allowed,
+ :too_many_links,
+ post.link_count,
+ SiteSetting.newuser_max_links,
+ )
end
# Stop us from posting the same thing too quickly
@@ -129,13 +161,14 @@ class PostValidator < ActiveModel::Validator
# If the post is empty, default to the validates_presence_of
return if post.raw.blank?
- if post.matches_recent_post?
- post.errors.add(:raw, I18n.t(:just_posted_that))
- end
+ post.errors.add(:raw, I18n.t(:just_posted_that)) if post.matches_recent_post?
end
def force_edit_last_validator(post)
- return if SiteSetting.max_consecutive_replies == 0 || post.id || post.acting_user&.staff? || private_message?(post)
+ if SiteSetting.max_consecutive_replies == 0 || post.id || post.acting_user&.staff? ||
+ private_message?(post)
+ return
+ end
topic = post.topic
return if topic&.ordered_posts&.first&.user == post.user
@@ -143,7 +176,9 @@ class PostValidator < ActiveModel::Validator
guardian = Guardian.new(post.acting_user)
return if guardian.is_category_group_moderator?(post.topic&.category)
- last_posts_count = DB.query_single(<<~SQL, topic_id: post.topic_id, user_id: post.acting_user.id, max_replies: SiteSetting.max_consecutive_replies).first
+ last_posts_count =
+ DB.query_single(
+ <<~SQL,
SELECT COUNT(*)
FROM (
SELECT user_id
@@ -156,10 +191,17 @@ class PostValidator < ActiveModel::Validator
) c
WHERE c.user_id = :user_id
SQL
+ topic_id: post.topic_id,
+ user_id: post.acting_user.id,
+ max_replies: SiteSetting.max_consecutive_replies,
+ ).first
return if last_posts_count < SiteSetting.max_consecutive_replies
if guardian.can_edit?(topic.ordered_posts.last)
- post.errors.add(:base, I18n.t(:max_consecutive_replies, count: SiteSetting.max_consecutive_replies))
+ post.errors.add(
+ :base,
+ I18n.t(:max_consecutive_replies, count: SiteSetting.max_consecutive_replies),
+ )
end
end
@@ -173,7 +215,13 @@ class PostValidator < ActiveModel::Validator
post.topic.try(:private_message?)
end
- def add_error_if_count_exceeded(post, not_allowed_translation_key, limit_translation_key, current_count, max_count)
+ def add_error_if_count_exceeded(
+ post,
+ not_allowed_translation_key,
+ limit_translation_key,
+ current_count,
+ max_count
+ )
if current_count > max_count
if max_count == 0
post.errors.add(:base, I18n.t(not_allowed_translation_key))
diff --git a/lib/validators/quality_title_validator.rb b/lib/validators/quality_title_validator.rb
index 2fa95624392..84196a4b567 100644
--- a/lib/validators/quality_title_validator.rb
+++ b/lib/validators/quality_title_validator.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'text_sentinel'
-require 'text_cleaner'
+require "text_sentinel"
+require "text_cleaner"
class QualityTitleValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
diff --git a/lib/validators/regex_setting_validation.rb b/lib/validators/regex_setting_validation.rb
index 2dd738d0a8d..285aa66923c 100644
--- a/lib/validators/regex_setting_validation.rb
+++ b/lib/validators/regex_setting_validation.rb
@@ -1,10 +1,9 @@
# frozen_string_literal: true
module RegexSettingValidation
-
def initialize_regex_opts(opts = {})
@regex = Regexp.new(opts[:regex]) if opts[:regex]
- @regex_error = opts[:regex_error] || 'site_settings.errors.regex_mismatch'
+ @regex_error = opts[:regex_error] || "site_settings.errors.regex_mismatch"
end
def regex_match?(val)
@@ -15,5 +14,4 @@ module RegexSettingValidation
true
end
-
end
diff --git a/lib/validators/regex_setting_validator.rb b/lib/validators/regex_setting_validator.rb
index a0d85b9e5ee..1437733487b 100644
--- a/lib/validators/regex_setting_validator.rb
+++ b/lib/validators/regex_setting_validator.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
class RegexSettingValidator
-
- LOREM = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget sem non elit tincidunt rhoncus.'
+ LOREM =
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget sem non elit tincidunt rhoncus."
def initialize(opts = {})
@opts = opts
@@ -17,11 +17,11 @@ class RegexSettingValidator
r = Regexp.new(val)
matches = r.match(LOREM)
matches.nil? || matches[0].length < (LOREM.length - 10)
- rescue
+ rescue StandardError
false
end
def error_message
- I18n.t('site_settings.errors.invalid_regex')
+ I18n.t("site_settings.errors.invalid_regex")
end
end
diff --git a/lib/validators/regexp_list_validator.rb b/lib/validators/regexp_list_validator.rb
index dd35f31e958..23ddfc39bf4 100644
--- a/lib/validators/regexp_list_validator.rb
+++ b/lib/validators/regexp_list_validator.rb
@@ -5,18 +5,24 @@ class RegexpListValidator
end
def valid_value?(value)
- value.split("|").all? do |regexp|
- begin
- Regexp.new(regexp)
- rescue RegexpError => e
- @regexp = regexp
- @error_message = e.message
- false
+ value
+ .split("|")
+ .all? do |regexp|
+ begin
+ Regexp.new(regexp)
+ rescue RegexpError => e
+ @regexp = regexp
+ @error_message = e.message
+ false
+ end
end
- end
end
def error_message
- I18n.t("site_settings.errors.invalid_regex_with_message", regex: @regexp, message: @error_message)
+ I18n.t(
+ "site_settings.errors.invalid_regex_with_message",
+ regex: @regexp,
+ message: @error_message,
+ )
end
end
diff --git a/lib/validators/reply_by_email_address_validator.rb b/lib/validators/reply_by_email_address_validator.rb
index a5ab973f811..5fac83eb414 100644
--- a/lib/validators/reply_by_email_address_validator.rb
+++ b/lib/validators/reply_by_email_address_validator.rb
@@ -6,7 +6,7 @@ class ReplyByEmailAddressValidator
end
def valid_value?(val)
- return true if val.blank?
+ return true if val.blank?
return false if !EmailAddressValidator.valid_value?(val)
if SiteSetting.find_related_post_with_key
@@ -18,6 +18,6 @@ class ReplyByEmailAddressValidator
end
def error_message
- I18n.t('site_settings.errors.invalid_reply_by_email_address')
+ I18n.t("site_settings.errors.invalid_reply_by_email_address")
end
end
diff --git a/lib/validators/reply_by_email_enabled_validator.rb b/lib/validators/reply_by_email_enabled_validator.rb
index cd3886ed70c..ce5e53b8954 100644
--- a/lib/validators/reply_by_email_enabled_validator.rb
+++ b/lib/validators/reply_by_email_enabled_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class ReplyByEmailEnabledValidator
-
def initialize(opts = {})
@opts = opts
end
@@ -10,8 +9,7 @@ class ReplyByEmailEnabledValidator
# only validate when enabling reply by email
return true if val == "f"
# ensure reply_by_email_address is configured && polling is working
- SiteSetting.reply_by_email_address.present? &&
- SiteSetting.email_polling_enabled?
+ SiteSetting.reply_by_email_address.present? && SiteSetting.email_polling_enabled?
end
def error_message
@@ -21,5 +19,4 @@ class ReplyByEmailEnabledValidator
I18n.t("site_settings.errors.email_polling_disabled")
end
end
-
end
diff --git a/lib/validators/selectable_avatars_mode_validator.rb b/lib/validators/selectable_avatars_mode_validator.rb
index dcf46e7d21a..4393020cdf0 100644
--- a/lib/validators/selectable_avatars_mode_validator.rb
+++ b/lib/validators/selectable_avatars_mode_validator.rb
@@ -10,6 +10,6 @@ class SelectableAvatarsModeValidator
end
def error_message
- I18n.t('site_settings.errors.empty_selectable_avatars')
+ I18n.t("site_settings.errors.empty_selectable_avatars")
end
end
diff --git a/lib/validators/sso_overrides_email_validator.rb b/lib/validators/sso_overrides_email_validator.rb
index fd53f4fa2da..d823a342c6b 100644
--- a/lib/validators/sso_overrides_email_validator.rb
+++ b/lib/validators/sso_overrides_email_validator.rb
@@ -6,14 +6,12 @@ class SsoOverridesEmailValidator
end
def valid_value?(val)
- return true if val == 'f'
+ return true if val == "f"
return false if SiteSetting.email_editable?
true
end
def error_message
- if SiteSetting.email_editable?
- I18n.t('site_settings.errors.email_editable_enabled')
- end
+ I18n.t("site_settings.errors.email_editable_enabled") if SiteSetting.email_editable?
end
end
diff --git a/lib/validators/string_setting_validator.rb b/lib/validators/string_setting_validator.rb
index 567ee6c6ff7..bbc271b5217 100644
--- a/lib/validators/string_setting_validator.rb
+++ b/lib/validators/string_setting_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class StringSettingValidator
-
include RegexSettingValidation
def initialize(opts = {})
@@ -12,7 +11,8 @@ class StringSettingValidator
def valid_value?(val)
return true if !val.present?
- if (@opts[:min] && @opts[:min].to_i > (val.length)) || (@opts[:max] && @opts[:max].to_i < (val.length))
+ if (@opts[:min] && @opts[:min].to_i > (val.length)) ||
+ (@opts[:max] && @opts[:max].to_i < (val.length))
@length_fail = true
return false
end
@@ -39,16 +39,16 @@ class StringSettingValidator
I18n.t(@regex_error)
elsif @length_fail
if @opts[:min] && @opts[:max]
- I18n.t('site_settings.errors.invalid_string_min_max', min: @opts[:min], max: @opts[:max])
+ I18n.t("site_settings.errors.invalid_string_min_max", min: @opts[:min], max: @opts[:max])
elsif @opts[:min]
- I18n.t('site_settings.errors.invalid_string_min', min: @opts[:min])
+ I18n.t("site_settings.errors.invalid_string_min", min: @opts[:min])
else
- I18n.t('site_settings.errors.invalid_string_max', max: @opts[:max])
+ I18n.t("site_settings.errors.invalid_string_max", max: @opts[:max])
end
elsif @json_fail
- I18n.t('site_settings.errors.invalid_json')
+ I18n.t("site_settings.errors.invalid_json")
else
- I18n.t('site_settings.errors.invalid_string')
+ I18n.t("site_settings.errors.invalid_string")
end
end
end
diff --git a/lib/validators/stripped_length_validator.rb b/lib/validators/stripped_length_validator.rb
index 631feb9d58f..ee79d2ca70a 100644
--- a/lib/validators/stripped_length_validator.rb
+++ b/lib/validators/stripped_length_validator.rb
@@ -3,14 +3,19 @@
class StrippedLengthValidator < ActiveModel::EachValidator
def self.validate(record, attribute, value, range)
if value.nil?
- record.errors.add attribute, I18n.t('errors.messages.blank')
+ record.errors.add attribute, I18n.t("errors.messages.blank")
elsif value.length > range.end
- record.errors.add attribute, I18n.t('errors.messages.too_long_validation', max: range.end, length: value.length)
+ record.errors.add attribute,
+ I18n.t(
+ "errors.messages.too_long_validation",
+ max: range.end,
+ length: value.length,
+ )
else
value = get_sanitized_value(value)
if value.length < range.begin
- record.errors.add attribute, I18n.t('errors.messages.too_short', count: range.begin)
+ record.errors.add attribute, I18n.t("errors.messages.too_short", count: range.begin)
end
end
end
@@ -23,10 +28,10 @@ class StrippedLengthValidator < ActiveModel::EachValidator
def self.get_sanitized_value(value)
value = value.dup
- value.gsub!(/<!--(.*?)-->/, '') # strip HTML comments
+ value.gsub!(/<!--(.*?)-->/, "") # strip HTML comments
value.gsub!(/:\w+(:\w+)?:/, "X") # replace emojis with a single character
- value.gsub!(/\.{2,}/, '…') # replace multiple ... with …
- value.gsub!(/\,{2,}/, ',') # replace multiple ,,, with ,
+ value.gsub!(/\.{2,}/, "…") # replace multiple ... with …
+ value.gsub!(/\,{2,}/, ",") # replace multiple ,,, with ,
value.strip
end
end
diff --git a/lib/validators/timezone_validator.rb b/lib/validators/timezone_validator.rb
index 93ff1a2d78a..d94c83b8a77 100644
--- a/lib/validators/timezone_validator.rb
+++ b/lib/validators/timezone_validator.rb
@@ -13,10 +13,6 @@ class TimezoneValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return if value.blank? || TimezoneValidator.valid?(value)
- record.errors.add(
- attribute,
- :timezone,
- message: TimezoneValidator.error_message(value)
- )
+ record.errors.add(attribute, :timezone, message: TimezoneValidator.error_message(value))
end
end
diff --git a/lib/validators/topic_title_length_validator.rb b/lib/validators/topic_title_length_validator.rb
index cf74ab25991..5db13316121 100644
--- a/lib/validators/topic_title_length_validator.rb
+++ b/lib/validators/topic_title_length_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class TopicTitleLengthValidator < ActiveModel::EachValidator
-
def validate_each(record, attribute, value)
title_validator(record).validate_each(record, attribute, value)
end
@@ -18,7 +17,10 @@ class TopicTitleLengthValidator < ActiveModel::EachValidator
SiteSetting.topic_title_length
end
- ActiveModel::Validations::LengthValidator.new(attributes: :title, in: length_range, allow_blank: true)
+ ActiveModel::Validations::LengthValidator.new(
+ attributes: :title,
+ in: length_range,
+ allow_blank: true,
+ )
end
-
end
diff --git a/lib/validators/unicode_username_allowlist_validator.rb b/lib/validators/unicode_username_allowlist_validator.rb
index f47d37b92f5..824e5e43442 100644
--- a/lib/validators/unicode_username_allowlist_validator.rb
+++ b/lib/validators/unicode_username_allowlist_validator.rb
@@ -9,13 +9,15 @@ class UnicodeUsernameAllowlistValidator
@error_message = nil
return true if value.blank?
- if value.match?(/^\/.*\/[imxo]*$/)
- @error_message = I18n.t("site_settings.errors.allowed_unicode_usernames.leading_trailing_slash")
+ if value.match?(%r{^/.*/[imxo]*$})
+ @error_message =
+ I18n.t("site_settings.errors.allowed_unicode_usernames.leading_trailing_slash")
else
begin
Regexp.new(value)
rescue RegexpError => e
- @error_message = I18n.t("site_settings.errors.allowed_unicode_usernames.regex_invalid", error: e.message)
+ @error_message =
+ I18n.t("site_settings.errors.allowed_unicode_usernames.regex_invalid", error: e.message)
end
end
diff --git a/lib/validators/unique_among_validator.rb b/lib/validators/unique_among_validator.rb
index d9c63516eb8..85d91b66241 100644
--- a/lib/validators/unique_among_validator.rb
+++ b/lib/validators/unique_among_validator.rb
@@ -3,17 +3,13 @@
class UniqueAmongValidator < ActiveRecord::Validations::UniquenessValidator
def validate_each(record, attribute, value)
old_errors = []
- record.errors.each do |error|
- old_errors << error if error.attribute == attribute
- end
+ record.errors.each { |error| old_errors << error if error.attribute == attribute }
# look for any duplicates at all
super
new_errors = []
- record.errors.each do |error|
- new_errors << error if error.attribute == attribute
- end
+ record.errors.each { |error| new_errors << error if error.attribute == attribute }
# do nothing further unless there were some duplicates.
if new_errors.size - old_errors.size != 0
@@ -24,15 +20,8 @@ class UniqueAmongValidator < ActiveRecord::Validations::UniquenessValidator
# pop off the error, if it was a false positive
if !dupes.exists?
record.errors.delete(attribute)
- old_errors.each do |error|
- record.errors.add(
- error.attribute,
- error.type,
- **error.options
- )
- end
+ old_errors.each { |error| record.errors.add(error.attribute, error.type, **error.options) }
end
end
end
-
end
diff --git a/lib/validators/upload_validator.rb b/lib/validators/upload_validator.rb
index 5fb084c8354..0e79784ac9c 100644
--- a/lib/validators/upload_validator.rb
+++ b/lib/validators/upload_validator.rb
@@ -16,16 +16,12 @@ class UploadValidator < ActiveModel::Validator
extension = File.extname(upload.original_filename)[1..-1] || ""
- if upload.for_site_setting &&
- upload.user&.staff? &&
- FileHelper.is_supported_image?(upload.original_filename)
-
+ if upload.for_site_setting && upload.user&.staff? &&
+ FileHelper.is_supported_image?(upload.original_filename)
return true
end
- if upload.for_gravatar &&
- FileHelper.supported_gravatar_extensions.include?(extension)
-
+ if upload.for_gravatar && FileHelper.supported_gravatar_extensions.include?(extension)
maximum_image_file_size(upload)
return true
end
@@ -47,9 +43,9 @@ class UploadValidator < ActiveModel::Validator
# upload.update_secure_status being run outside of the creation flow,
# where some cases e.g. have exemptions on the extension enforcement
def changing_upload_security?(upload)
- !upload.new_record? && \
+ !upload.new_record? &&
upload.changed_attributes.keys.all? do |attribute|
- %w(secure security_last_changed_at security_last_changed_reason).include?(attribute)
+ %w[secure security_last_changed_at security_last_changed_reason].include?(attribute)
end
end
@@ -88,13 +84,14 @@ class UploadValidator < ActiveModel::Validator
end
def authorized_extensions(upload)
- extensions = if upload.for_theme
- SiteSetting.theme_authorized_extensions
- elsif upload.for_export
- SiteSetting.export_authorized_extensions
- else
- SiteSetting.authorized_extensions
- end
+ extensions =
+ if upload.for_theme
+ SiteSetting.theme_authorized_extensions
+ elsif upload.for_export
+ SiteSetting.export_authorized_extensions
+ else
+ SiteSetting.authorized_extensions
+ end
extensions_to_set(extensions)
end
@@ -110,13 +107,14 @@ class UploadValidator < ActiveModel::Validator
if upload.user&.staff?
return true if SiteSetting.authorized_extensions_for_staff.include?("*")
end
- extensions = if upload.for_theme
- SiteSetting.theme_authorized_extensions
- elsif upload.for_export
- SiteSetting.export_authorized_extensions
- else
- SiteSetting.authorized_extensions
- end
+ extensions =
+ if upload.for_theme
+ SiteSetting.theme_authorized_extensions
+ elsif upload.for_export
+ SiteSetting.export_authorized_extensions
+ else
+ SiteSetting.authorized_extensions
+ end
extensions.include?("*")
end
@@ -130,7 +128,11 @@ class UploadValidator < ActiveModel::Validator
end
unless authorized = extensions.include?(extension.downcase)
- message = I18n.t("upload.unauthorized", authorized_extensions: (extensions | staff_extensions).to_a.join(", "))
+ message =
+ I18n.t(
+ "upload.unauthorized",
+ authorized_extensions: (extensions | staff_extensions).to_a.join(", "),
+ )
upload.errors.add(:original_filename, message)
end
@@ -140,19 +142,21 @@ class UploadValidator < ActiveModel::Validator
def maximum_file_size(upload, type)
return if !upload.validate_file_size
- max_size_kb = if upload.for_export
- SiteSetting.max_export_file_size_kb
- else
- SiteSetting.get("max_#{type}_size_kb")
- end
+ max_size_kb =
+ if upload.for_export
+ SiteSetting.max_export_file_size_kb
+ else
+ SiteSetting.get("max_#{type}_size_kb")
+ end
max_size_bytes = max_size_kb.kilobytes
if upload.filesize > max_size_bytes
- message = I18n.t(
- "upload.#{type}s.too_large_humanized",
- max_size: ActiveSupport::NumberHelper.number_to_human_size(max_size_bytes)
- )
+ message =
+ I18n.t(
+ "upload.#{type}s.too_large_humanized",
+ max_size: ActiveSupport::NumberHelper.number_to_human_size(max_size_bytes),
+ )
upload.errors.add(:filesize, message)
end
end
diff --git a/lib/validators/url_validator.rb b/lib/validators/url_validator.rb
index be60a57354e..f43e637fd0f 100644
--- a/lib/validators/url_validator.rb
+++ b/lib/validators/url_validator.rb
@@ -17,7 +17,7 @@ class UrlValidator < ActiveModel::EachValidator
end
unless valid
- record.errors.add(attribute, options[:message] || I18n.t('errors.messages.invalid'))
+ record.errors.add(attribute, options[:message] || I18n.t("errors.messages.invalid"))
end
end
end
diff --git a/lib/validators/user_full_name_validator.rb b/lib/validators/user_full_name_validator.rb
index df1777a1a90..04e1f557c32 100644
--- a/lib/validators/user_full_name_validator.rb
+++ b/lib/validators/user_full_name_validator.rb
@@ -1,10 +1,7 @@
# frozen_string_literal: true
class UserFullNameValidator < ActiveModel::EachValidator
-
def validate_each(record, attribute, value)
- if SiteSetting.full_name_required && !record.name.present?
- record.errors.add(attribute, :blank)
- end
+ record.errors.add(attribute, :blank) if SiteSetting.full_name_required && !record.name.present?
end
end
diff --git a/lib/validators/username_setting_validator.rb b/lib/validators/username_setting_validator.rb
index 22d2b9cb399..3d21bbaf862 100644
--- a/lib/validators/username_setting_validator.rb
+++ b/lib/validators/username_setting_validator.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class UsernameSettingValidator
-
include RegexSettingValidation
def initialize(opts = {})
@@ -17,7 +16,7 @@ class UsernameSettingValidator
if @regex_fail
I18n.t(@regex_error)
else
- I18n.t('site_settings.errors.invalid_username')
+ I18n.t("site_settings.errors.invalid_username")
end
end
end
diff --git a/lib/validators/watched_words_validator.rb b/lib/validators/watched_words_validator.rb
index 4174e514af1..cacb168b601 100644
--- a/lib/validators/watched_words_validator.rb
+++ b/lib/validators/watched_words_validator.rb
@@ -4,11 +4,11 @@ class WatchedWordsValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if matches = WordWatcher.new(value).should_block?.presence
if matches.size == 1
- key = 'contains_blocked_word'
+ key = "contains_blocked_word"
translation_args = { word: CGI.escapeHTML(matches[0]) }
else
- key = 'contains_blocked_words'
- translation_args = { words: CGI.escapeHTML(matches.join(', ')) }
+ key = "contains_blocked_words"
+ translation_args = { words: CGI.escapeHTML(matches.join(", ")) }
end
record.errors.add(:base, I18n.t(key, translation_args))
end
diff --git a/lib/vary_header.rb b/lib/vary_header.rb
index c80eb7a9b8d..3f76411b578 100644
--- a/lib/vary_header.rb
+++ b/lib/vary_header.rb
@@ -2,6 +2,6 @@
module VaryHeader
def ensure_vary_header
- response.headers['Vary'] ||= 'Accept' if !params[:format]
+ response.headers["Vary"] ||= "Accept" if !params[:format]
end
end
diff --git a/lib/version.rb b/lib/version.rb
index 5337f516d0e..ec7562d897b 100644
--- a/lib/version.rb
+++ b/lib/version.rb
@@ -5,18 +5,19 @@ module Discourse
VERSION_COMPATIBILITY_FILENAME ||= ".discourse-compatibility"
# work around reloader
- unless defined? ::Discourse::VERSION
+ unless defined?(::Discourse::VERSION)
module VERSION #:nodoc:
MAJOR = 3
MINOR = 0
- TINY = 0
- PRE = 'beta16'
+ TINY = 0
+ PRE = "beta16"
- STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
end
- class InvalidVersionListError < StandardError; end
+ class InvalidVersionListError < StandardError
+ end
def self.has_needed_version?(current, needed)
Gem::Version.new(current) >= Gem::Version.new(needed)
@@ -57,7 +58,10 @@ module Discourse
return if checkout_version.nil?
begin
- Discourse::Utils.execute_command "git", "check-ref-format", "--allow-onelevel", checkout_version
+ Discourse::Utils.execute_command "git",
+ "check-ref-format",
+ "--allow-onelevel",
+ checkout_version
rescue RuntimeError
raise InvalidVersionListError, "Invalid ref name: #{checkout_version}"
end
@@ -68,7 +72,10 @@ module Discourse
# Find a compatible resource from a git repo
def self.find_compatible_git_resource(path)
return unless File.directory?("#{path}/.git")
- compat_resource, std_error, s = Open3.capture3("git -C '#{path}' show HEAD@{upstream}:#{Discourse::VERSION_COMPATIBILITY_FILENAME}")
+ compat_resource, std_error, s =
+ Open3.capture3(
+ "git -C '#{path}' show HEAD@{upstream}:#{Discourse::VERSION_COMPATIBILITY_FILENAME}",
+ )
Discourse.find_compatible_resource(compat_resource) if s.success?
rescue InvalidVersionListError => e
$stderr.puts "Invalid version list in #{path}"
diff --git a/lib/webauthn.rb b/lib/webauthn.rb
index 089913f31cf..ef47bd9960d 100644
--- a/lib/webauthn.rb
+++ b/lib/webauthn.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-require 'webauthn/challenge_generator'
-require 'webauthn/security_key_base_validation_service'
-require 'webauthn/security_key_registration_service'
-require 'webauthn/security_key_authentication_service'
+require "webauthn/challenge_generator"
+require "webauthn/security_key_base_validation_service"
+require "webauthn/security_key_registration_service"
+require "webauthn/security_key_authentication_service"
module Webauthn
ACCEPTABLE_REGISTRATION_TYPE = "webauthn.create"
@@ -11,23 +11,37 @@ module Webauthn
# -7 - ES256
# -257 - RS256 (Windows Hello supported alg.)
SUPPORTED_ALGORITHMS = COSE::Algorithm.registered_algorithm_ids.freeze
- VALID_ATTESTATION_FORMATS = ['none', 'packed', 'fido-u2f'].freeze
+ VALID_ATTESTATION_FORMATS = %w[none packed fido-u2f].freeze
- class SecurityKeyError < StandardError; end
+ class SecurityKeyError < StandardError
+ end
- class InvalidOriginError < SecurityKeyError; end
- class InvalidRelyingPartyIdError < SecurityKeyError; end
- class UserVerificationError < SecurityKeyError; end
- class ChallengeMismatchError < SecurityKeyError; end
- class InvalidTypeError < SecurityKeyError; end
- class UnsupportedPublicKeyAlgorithmError < SecurityKeyError; end
- class UnsupportedAttestationFormatError < SecurityKeyError; end
- class CredentialIdInUseError < SecurityKeyError; end
- class MalformedAttestationError < SecurityKeyError; end
- class NotFoundError < SecurityKeyError; end
- class OwnershipError < SecurityKeyError; end
- class PublicKeyError < SecurityKeyError; end
- class UnknownCOSEAlgorithmError < SecurityKeyError; end
+ class InvalidOriginError < SecurityKeyError
+ end
+ class InvalidRelyingPartyIdError < SecurityKeyError
+ end
+ class UserVerificationError < SecurityKeyError
+ end
+ class ChallengeMismatchError < SecurityKeyError
+ end
+ class InvalidTypeError < SecurityKeyError
+ end
+ class UnsupportedPublicKeyAlgorithmError < SecurityKeyError
+ end
+ class UnsupportedAttestationFormatError < SecurityKeyError
+ end
+ class CredentialIdInUseError < SecurityKeyError
+ end
+ class MalformedAttestationError < SecurityKeyError
+ end
+ class NotFoundError < SecurityKeyError
+ end
+ class OwnershipError < SecurityKeyError
+ end
+ class PublicKeyError < SecurityKeyError
+ end
+ class UnknownCOSEAlgorithmError < SecurityKeyError
+ end
##
# Usage:
@@ -45,9 +59,8 @@ module Webauthn
credential_ids = user.second_factor_security_key_credential_ids
{
allowed_credential_ids: credential_ids,
- challenge: secure_session[
- Webauthn::ChallengeGenerator::ChallengeSession.session_challenge_key(user)
- ]
+ challenge:
+ secure_session[Webauthn::ChallengeGenerator::ChallengeSession.session_challenge_key(user)],
}
end
diff --git a/lib/webauthn/challenge_generator.rb b/lib/webauthn/challenge_generator.rb
index b35c95d5cf7..cd08e06593c 100644
--- a/lib/webauthn/challenge_generator.rb
+++ b/lib/webauthn/challenge_generator.rb
@@ -35,7 +35,7 @@ module Webauthn
ChallengeSession.new(
challenge: SecureRandom.hex(30),
rp_id: Discourse.current_hostname,
- rp_name: SiteSetting.title
+ rp_name: SiteSetting.title,
)
end
end
diff --git a/lib/webauthn/security_key_authentication_service.rb b/lib/webauthn/security_key_authentication_service.rb
index e33c4d8f0bb..5da5b6b5a7c 100644
--- a/lib/webauthn/security_key_authentication_service.rb
+++ b/lib/webauthn/security_key_authentication_service.rb
@@ -1,21 +1,24 @@
# frozen_string_literal: true
-require 'cose'
+require "cose"
module Webauthn
class SecurityKeyAuthenticationService < SecurityKeyBaseValidationService
-
##
# See https://w3c.github.io/webauthn/#sctn-verifying-assertion for
# the steps followed here. Memoized methods are called in their
# place in the step flow to make the process clearer.
def authenticate_security_key
- return false if @params.blank? || ([email protected]_a?(Hash) && [email protected]_a?(ActionController::Parameters))
+ if @params.blank? || ([email protected]_a?(Hash) && [email protected]_a?(ActionController::Parameters))
+ return false
+ end
# 3. Identify the user being authenticated and verify that this user is the
# owner of the public key credential source credentialSource identified by credential.id:
security_key = UserSecurityKey.find_by(credential_id: @params[:credentialId])
- raise(NotFoundError, I18n.t('webauthn.validation.not_found_error')) if security_key.blank?
- raise(OwnershipError, I18n.t('webauthn.validation.ownership_error')) if security_key.user != @current_user
+ raise(NotFoundError, I18n.t("webauthn.validation.not_found_error")) if security_key.blank?
+ if security_key.user != @current_user
+ raise(OwnershipError, I18n.t("webauthn.validation.ownership_error"))
+ end
# 4. Using credential.id (or credential.rawId, if base64url encoding is inappropriate for your use case),
# look up the corresponding credential public key and let credentialPublicKey be that credential public key.
@@ -67,18 +70,24 @@ module Webauthn
cose_algorithm = COSE::Algorithm.find(cose_key.alg)
if cose_algorithm.blank?
- Rails.logger.error("Unknown COSE algorithm encountered. alg: #{cose_key.alg}. user_id: #{@current_user.id}. params: #{@params.inspect}")
- raise(UnknownCOSEAlgorithmError, I18n.t('webauthn.validation.unknown_cose_algorithm_error'))
+ Rails.logger.error(
+ "Unknown COSE algorithm encountered. alg: #{cose_key.alg}. user_id: #{@current_user.id}. params: #{@params.inspect}",
+ )
+ raise(UnknownCOSEAlgorithmError, I18n.t("webauthn.validation.unknown_cose_algorithm_error"))
end
- if !cose_key.to_pkey.verify(cose_algorithm.hash_function, signature, auth_data + client_data_hash)
- raise(PublicKeyError, I18n.t('webauthn.validation.public_key_error'))
+ if !cose_key.to_pkey.verify(
+ cose_algorithm.hash_function,
+ signature,
+ auth_data + client_data_hash,
+ )
+ raise(PublicKeyError, I18n.t("webauthn.validation.public_key_error"))
end
# Success! Update the last used at time for the key.
security_key.update(last_used: Time.zone.now)
rescue OpenSSL::PKey::PKeyError
- raise(PublicKeyError, I18n.t('webauthn.validation.public_key_error'))
+ raise(PublicKeyError, I18n.t("webauthn.validation.public_key_error"))
end
private
diff --git a/lib/webauthn/security_key_base_validation_service.rb b/lib/webauthn/security_key_base_validation_service.rb
index e5900876f17..5af6a52529f 100644
--- a/lib/webauthn/security_key_base_validation_service.rb
+++ b/lib/webauthn/security_key_base_validation_service.rb
@@ -9,29 +9,32 @@ module Webauthn
end
def validate_webauthn_type(type_to_check)
- return if client_data['type'] == type_to_check
- raise(InvalidTypeError, I18n.t('webauthn.validation.invalid_type_error'))
+ return if client_data["type"] == type_to_check
+ raise(InvalidTypeError, I18n.t("webauthn.validation.invalid_type_error"))
end
def validate_challenge
return if challenge_match?
- raise(ChallengeMismatchError, I18n.t('webauthn.validation.challenge_mismatch_error'))
+ raise(ChallengeMismatchError, I18n.t("webauthn.validation.challenge_mismatch_error"))
end
def validate_origin
return if origin_match?
- raise(InvalidOriginError, I18n.t('webauthn.validation.invalid_origin_error'))
+ raise(InvalidOriginError, I18n.t("webauthn.validation.invalid_origin_error"))
end
def validate_rp_id_hash
return if rp_id_hash_match?
- raise(InvalidRelyingPartyIdError, I18n.t('webauthn.validation.invalid_relying_party_id_error'))
+ raise(
+ InvalidRelyingPartyIdError,
+ I18n.t("webauthn.validation.invalid_relying_party_id_error"),
+ )
end
def validate_user_verification
- flags = auth_data[32].unpack("b*")[0].split('')
- return if flags[0] == '1'
- raise(UserVerificationError, I18n.t('webauthn.validation.user_verification_error'))
+ flags = auth_data[32].unpack("b*")[0].split("")
+ return if flags[0] == "1"
+ raise(UserVerificationError, I18n.t("webauthn.validation.user_verification_error"))
end
private
@@ -49,11 +52,11 @@ module Webauthn
end
def challenge_match?
- Base64.decode64(client_data['challenge']) == @challenge_params[:challenge]
+ Base64.decode64(client_data["challenge"]) == @challenge_params[:challenge]
end
def origin_match?
- client_data['origin'] == @challenge_params[:origin]
+ client_data["origin"] == @challenge_params[:origin]
end
def rp_id_hash_match?
diff --git a/lib/webauthn/security_key_registration_service.rb b/lib/webauthn/security_key_registration_service.rb
index ff8544f1ac5..1695fddf232 100644
--- a/lib/webauthn/security_key_registration_service.rb
+++ b/lib/webauthn/security_key_registration_service.rb
@@ -1,10 +1,9 @@
# frozen_string_literal: true
-require 'cbor'
-require 'cose'
+require "cbor"
+require "cose"
module Webauthn
class SecurityKeyRegistrationService < SecurityKeyBaseValidationService
-
##
# See https://w3c.github.io/webauthn/#sctn-registering-a-new-credential for
# the registration steps followed here. Memoized methods are called in their
@@ -50,8 +49,14 @@ module Webauthn
# https://w3c.github.io/webauthn/#table-attestedCredentialData
# See https://www.iana.org/assignments/cose/cose.xhtml#algorithms for supported algorithm
# codes.
- credential_public_key, credential_public_key_bytes, credential_id = extract_public_key_and_credential_from_attestation(auth_data)
- raise(UnsupportedPublicKeyAlgorithmError, I18n.t('webauthn.validation.unsupported_public_key_algorithm_error')) if ::Webauthn::SUPPORTED_ALGORITHMS.exclude?(credential_public_key.alg)
+ credential_public_key, credential_public_key_bytes, credential_id =
+ extract_public_key_and_credential_from_attestation(auth_data)
+ if ::Webauthn::SUPPORTED_ALGORITHMS.exclude?(credential_public_key.alg)
+ raise(
+ UnsupportedPublicKeyAlgorithmError,
+ I18n.t("webauthn.validation.unsupported_public_key_algorithm_error"),
+ )
+ end
# 14. Verify that the values of the client extension outputs in clientExtensionResults and the authenticator
# extension outputs in the extensions in authData are as expected, considering the client extension input
@@ -67,8 +72,12 @@ module Webauthn
# name [WebAuthn-Registries].
# 16. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature,
# by using the attestation statement format fmt’s verification procedure given attStmt, authData and hash.
- if ::Webauthn::VALID_ATTESTATION_FORMATS.exclude?(attestation['fmt']) || attestation['fmt'] != 'none'
- raise(UnsupportedAttestationFormatError, I18n.t('webauthn.validation.unsupported_attestation_format_error'))
+ if ::Webauthn::VALID_ATTESTATION_FORMATS.exclude?(attestation["fmt"]) ||
+ attestation["fmt"] != "none"
+ raise(
+ UnsupportedAttestationFormatError,
+ I18n.t("webauthn.validation.unsupported_attestation_format_error"),
+ )
end
#==================================================
@@ -92,7 +101,9 @@ module Webauthn
# the registration, e.g. while deleting the older registration.
encoded_credential_id = Base64.strict_encode64(credential_id)
endcoded_public_key = Base64.strict_encode64(credential_public_key_bytes)
- raise(CredentialIdInUseError, I18n.t('webauthn.validation.credential_id_in_use_error')) if UserSecurityKey.exists?(credential_id: encoded_credential_id)
+ if UserSecurityKey.exists?(credential_id: encoded_credential_id)
+ raise(CredentialIdInUseError, I18n.t("webauthn.validation.credential_id_in_use_error"))
+ end
# 20. If the attestation statement attStmt verified successfully and is found to be trustworthy,
# then register the new credential with the account that was denoted in options.user, by
@@ -103,10 +114,10 @@ module Webauthn
credential_id: encoded_credential_id,
public_key: endcoded_public_key,
name: @params[:name],
- factor_type: UserSecurityKey.factor_types[:second_factor]
+ factor_type: UserSecurityKey.factor_types[:second_factor],
)
rescue CBOR::UnpackError, CBOR::TypeError, CBOR::MalformedFormatError, CBOR::StackError
- raise MalformedAttestationError, I18n.t('webauthn.validation.malformed_attestation_error')
+ raise MalformedAttestationError, I18n.t("webauthn.validation.malformed_attestation_error")
end
private
@@ -116,7 +127,7 @@ module Webauthn
end
def auth_data
- @auth_data ||= attestation['authData']
+ @auth_data ||= attestation["authData"]
end
def extract_public_key_and_credential_from_attestation(auth_data)
@@ -128,9 +139,12 @@ module Webauthn
attested_credential_data_start_position = rp_id_length + flags_length + sign_count_length # 37
attested_credential_data_length = auth_data.size - attested_credential_data_start_position
- attested_credential_data = auth_data[
- attested_credential_data_start_position..(attested_credential_data_start_position + attested_credential_data_length - 1)
- ]
+ attested_credential_data =
+ auth_data[
+ attested_credential_data_start_position..(
+ attested_credential_data_start_position + attested_credential_data_length - 1
+ )
+ ]
# see https://w3c.github.io/webauthn/#attested-credential-data for lengths
# of data for extraction
@@ -139,9 +153,10 @@ module Webauthn
credential_id = attested_credential_data[18..(18 + credential_id_length - 1)]
public_key_start_position = 18 + credential_id_length
- public_key_bytes = attested_credential_data[
- public_key_start_position..(public_key_start_position + attested_credential_data.size - 1)
- ]
+ public_key_bytes =
+ attested_credential_data[
+ public_key_start_position..(public_key_start_position + attested_credential_data.size - 1)
+ ]
public_key = COSE::Key.deserialize(public_key_bytes)
[public_key, public_key_bytes, credential_id]
diff --git a/lib/wizard.rb b/lib/wizard.rb
index 534f361660c..f85d9f008ab 100644
--- a/lib/wizard.rb
+++ b/lib/wizard.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class Wizard
-
attr_reader :steps, :user
attr_accessor :max_topics_to_require_completion
@@ -64,15 +63,14 @@ class Wizard
end
def start
- completed = UserHistory.where(
- action: UserHistory.actions[:wizard_step],
- context: steps_with_fields.map(&:id)
- ).uniq.pluck(:context)
+ completed =
+ UserHistory
+ .where(action: UserHistory.actions[:wizard_step], context: steps_with_fields.map(&:id))
+ .uniq
+ .pluck(:context)
# First uncompleted step
- steps_with_fields.each do |s|
- return s unless completed.include?(s.id)
- end
+ steps_with_fields.each { |s| return s unless completed.include?(s.id) }
@first_step
end
@@ -89,10 +87,12 @@ class Wizard
def completed_steps?(steps)
steps = [steps].flatten.uniq
- completed = UserHistory.where(
- action: UserHistory.actions[:wizard_step],
- context: steps
- ).distinct.order(:context).pluck(:context)
+ completed =
+ UserHistory
+ .where(action: UserHistory.actions[:wizard_step], context: steps)
+ .distinct
+ .order(:context)
+ .pluck(:context)
steps.sort == completed
end
@@ -116,5 +116,4 @@ class Wizard
def self.user_requires_completion?(user)
self.new(user).requires_completion?
end
-
end
diff --git a/lib/wizard/builder.rb b/lib/wizard/builder.rb
index b7927fb6ed9..ebfef200260 100644
--- a/lib/wizard/builder.rb
+++ b/lib/wizard/builder.rb
@@ -2,7 +2,6 @@
class Wizard
class Builder
-
def initialize(user)
@wizard = Wizard.new(user)
end
@@ -10,18 +9,31 @@ class Wizard
def build
return @wizard unless SiteSetting.wizard_enabled? && @wizard.user.try(:staff?)
- @wizard.append_step('introduction') do |step|
+ @wizard.append_step("introduction") do |step|
step.banner = "welcome-illustration"
step.emoji = "wave"
step.description_vars = { base_path: Discourse.base_path }
- step.add_field(id: 'title', type: 'text', required: true, value: SiteSetting.title == SiteSetting.defaults[:title] ? "" : SiteSetting.title)
- step.add_field(id: 'site_description', type: 'text', required: false, value: SiteSetting.site_description)
+ step.add_field(
+ id: "title",
+ type: "text",
+ required: true,
+ value: SiteSetting.title == SiteSetting.defaults[:title] ? "" : SiteSetting.title,
+ )
+ step.add_field(
+ id: "site_description",
+ type: "text",
+ required: false,
+ value: SiteSetting.site_description,
+ )
- languages = step.add_field(id: 'default_locale',
- type: 'dropdown',
- required: false,
- value: SiteSetting.default_locale)
+ languages =
+ step.add_field(
+ id: "default_locale",
+ type: "dropdown",
+ required: false,
+ value: SiteSetting.default_locale,
+ )
LocaleSiteSetting.values.each do |locale|
languages.add_choice(locale[:value], label: locale[:name])
@@ -30,9 +42,7 @@ class Wizard
step.on_update do |updater|
updater.ensure_changed(:title)
- if updater.errors.blank?
- updater.apply_settings(:title, :site_description)
- end
+ updater.apply_settings(:title, :site_description) if updater.errors.blank?
old_locale = SiteSetting.default_locale
updater.apply_setting(:default_locale)
@@ -48,44 +58,44 @@ class Wizard
end
end
- @wizard.append_step('privacy') do |step|
+ @wizard.append_step("privacy") do |step|
step.banner = "members-illustration"
step.emoji = "hugs"
step.add_field(
- id: 'login_required',
- type: 'checkbox',
- icon: 'unlock',
- value: SiteSetting.login_required
+ id: "login_required",
+ type: "checkbox",
+ icon: "unlock",
+ value: SiteSetting.login_required,
)
step.add_field(
- id: 'invite_only',
- type: 'checkbox',
- icon: 'user-plus',
- value: SiteSetting.invite_only
+ id: "invite_only",
+ type: "checkbox",
+ icon: "user-plus",
+ value: SiteSetting.invite_only,
)
step.add_field(
- id: 'must_approve_users',
- type: 'checkbox',
- icon: 'user-shield',
- value: SiteSetting.must_approve_users
+ id: "must_approve_users",
+ type: "checkbox",
+ icon: "user-shield",
+ value: SiteSetting.must_approve_users,
)
if defined?(::Chat)
step.add_field(
- id: 'chat_enabled',
- type: 'checkbox',
- icon: 'comment',
- value: SiteSetting.chat_enabled
+ id: "chat_enabled",
+ type: "checkbox",
+ icon: "comment",
+ value: SiteSetting.chat_enabled,
)
end
step.add_field(
- id: 'enable_sidebar',
- type: 'checkbox',
- icon: 'bars',
- value: SiteSetting.navigation_menu == NavigationMenuSiteSetting::SIDEBAR
+ id: "enable_sidebar",
+ type: "checkbox",
+ icon: "bars",
+ value: SiteSetting.navigation_menu == NavigationMenuSiteSetting::SIDEBAR,
)
step.on_update do |updater|
@@ -97,27 +107,27 @@ class Wizard
end
end
- @wizard.append_step('ready') do |step|
+ @wizard.append_step("ready") do |step|
# no form on this page, just info.
step.banner = "finished-illustration"
step.emoji = "rocket"
end
- @wizard.append_step('branding') do |step|
+ @wizard.append_step("branding") do |step|
step.emoji = "framed_picture"
- step.add_field(id: 'logo', type: 'image', value: SiteSetting.site_logo_url)
- step.add_field(id: 'logo_small', type: 'image', value: SiteSetting.site_logo_small_url)
+ step.add_field(id: "logo", type: "image", value: SiteSetting.site_logo_url)
+ step.add_field(id: "logo_small", type: "image", value: SiteSetting.site_logo_small_url)
step.on_update do |updater|
if SiteSetting.site_logo_url != updater.fields[:logo] ||
- SiteSetting.site_logo_small_url != updater.fields[:logo_small]
+ SiteSetting.site_logo_small_url != updater.fields[:logo_small]
updater.apply_settings(:logo, :logo_small)
updater.refresh_required = true
end
end
end
- @wizard.append_step('styling') do |step|
+ @wizard.append_step("styling") do |step|
step.emoji = "art"
default_theme = Theme.find_by(id: SiteSetting.default_theme_id)
default_theme_override = SiteSetting.exists?(name: "default_theme_id")
@@ -125,15 +135,17 @@ class Wizard
base_scheme = default_theme&.color_scheme&.base_scheme_id
color_scheme_name = default_theme&.color_scheme&.name
- scheme_id = default_theme_override ? (base_scheme || color_scheme_name) : ColorScheme::LIGHT_THEME_ID
+ scheme_id =
+ default_theme_override ? (base_scheme || color_scheme_name) : ColorScheme::LIGHT_THEME_ID
- themes = step.add_field(
- id: 'color_scheme',
- type: 'dropdown',
- required: !default_theme_override,
- value: scheme_id || ColorScheme::LIGHT_THEME_ID,
- show_in_sidebar: true
- )
+ themes =
+ step.add_field(
+ id: "color_scheme",
+ type: "dropdown",
+ required: !default_theme_override,
+ value: scheme_id || ColorScheme::LIGHT_THEME_ID,
+ show_in_sidebar: true,
+ )
# fix for the case when base_scheme is nil
if scheme_id && default_theme_override && base_scheme.nil?
@@ -145,102 +157,116 @@ class Wizard
themes.add_choice(t[:id], data: { colors: t[:colors] })
end
- body_font = step.add_field(
- id: 'body_font',
- type: 'dropdown',
- value: SiteSetting.base_font,
- show_in_sidebar: true
- )
+ body_font =
+ step.add_field(
+ id: "body_font",
+ type: "dropdown",
+ value: SiteSetting.base_font,
+ show_in_sidebar: true,
+ )
- heading_font = step.add_field(
- id: 'heading_font',
- type: 'dropdown',
- value: SiteSetting.heading_font,
- show_in_sidebar: true
- )
+ heading_font =
+ step.add_field(
+ id: "heading_font",
+ type: "dropdown",
+ value: SiteSetting.heading_font,
+ show_in_sidebar: true,
+ )
DiscourseFonts.fonts.each do |font|
body_font.add_choice(font[:key], label: font[:name])
heading_font.add_choice(font[:key], label: font[:name])
end
- current = SiteSetting.top_menu.starts_with?("categories") ? SiteSetting.desktop_category_page_style : "latest"
- style = step.add_field(id: 'homepage_style', type: 'dropdown', required: false, value: current, show_in_sidebar: true)
- style.add_choice('latest')
- CategoryPageStyle.values.each do |page|
- style.add_choice(page[:value])
- end
+ current =
+ (
+ if SiteSetting.top_menu.starts_with?("categories")
+ SiteSetting.desktop_category_page_style
+ else
+ "latest"
+ end
+ )
+ style =
+ step.add_field(
+ id: "homepage_style",
+ type: "dropdown",
+ required: false,
+ value: current,
+ show_in_sidebar: true,
+ )
+ style.add_choice("latest")
+ CategoryPageStyle.values.each { |page| style.add_choice(page[:value]) }
- step.add_field(
- id: 'styling_preview',
- type: 'component'
- )
+ step.add_field(id: "styling_preview", type: "component")
step.on_update do |updater|
updater.update_setting(:base_font, updater.fields[:body_font])
updater.update_setting(:heading_font, updater.fields[:heading_font])
top_menu = SiteSetting.top_menu.split("|")
- if updater.fields[:homepage_style] == 'latest' && top_menu[0] != "latest"
+ if updater.fields[:homepage_style] == "latest" && top_menu[0] != "latest"
top_menu.delete("latest")
top_menu.insert(0, "latest")
- elsif updater.fields[:homepage_style] != 'latest'
+ elsif updater.fields[:homepage_style] != "latest"
top_menu.delete("categories")
top_menu.insert(0, "categories")
updater.update_setting(:desktop_category_page_style, updater.fields[:homepage_style])
end
updater.update_setting(:top_menu, top_menu.join("|"))
- scheme_name = (
- (updater.fields[:color_scheme] || "") ||
- ColorScheme::LIGHT_THEME_ID
- )
+ scheme_name = ((updater.fields[:color_scheme] || "") || ColorScheme::LIGHT_THEME_ID)
next unless scheme_name.present? && ColorScheme.is_base?(scheme_name)
- name = I18n.t("color_schemes.#{scheme_name.downcase.gsub(' ', '_')}_theme_name")
+ name = I18n.t("color_schemes.#{scheme_name.downcase.gsub(" ", "_")}_theme_name")
scheme = ColorScheme.find_by(base_scheme_id: scheme_name, via_wizard: true)
- scheme ||= ColorScheme.create_from_base(name: name, via_wizard: true, base_scheme_id: scheme_name)
+ scheme ||=
+ ColorScheme.create_from_base(name: name, via_wizard: true, base_scheme_id: scheme_name)
if default_theme
default_theme.color_scheme_id = scheme.id
default_theme.save!
else
- theme = Theme.create!(
- name: I18n.t("color_schemes.default_theme_name"),
- user_id: @wizard.user.id,
- color_scheme_id: scheme.id
- )
+ theme =
+ Theme.create!(
+ name: I18n.t("color_schemes.default_theme_name"),
+ user_id: @wizard.user.id,
+ color_scheme_id: scheme.id,
+ )
theme.set_default!
end
- if scheme.is_dark?
- updater.update_setting(:default_dark_mode_color_scheme_id, -1)
- end
+ updater.update_setting(:default_dark_mode_color_scheme_id, -1) if scheme.is_dark?
updater.refresh_required = true
end
end
- @wizard.append_step('corporate') do |step|
+ @wizard.append_step("corporate") do |step|
step.emoji = "briefcase"
step.description_vars = { base_path: Discourse.base_path }
- step.add_field(id: 'company_name', type: 'text', value: SiteSetting.company_name)
- step.add_field(id: 'governing_law', type: 'text', value: SiteSetting.governing_law)
- step.add_field(id: 'contact_url', type: 'text', value: SiteSetting.contact_url)
- step.add_field(id: 'city_for_disputes', type: 'text', value: SiteSetting.city_for_disputes)
- step.add_field(id: 'contact_email', type: 'text', value: SiteSetting.contact_email)
+ step.add_field(id: "company_name", type: "text", value: SiteSetting.company_name)
+ step.add_field(id: "governing_law", type: "text", value: SiteSetting.governing_law)
+ step.add_field(id: "contact_url", type: "text", value: SiteSetting.contact_url)
+ step.add_field(id: "city_for_disputes", type: "text", value: SiteSetting.city_for_disputes)
+ step.add_field(id: "contact_email", type: "text", value: SiteSetting.contact_email)
step.on_update do |updater|
update_tos do |raw|
- replace_setting_value(updater, raw, 'company_name')
- replace_setting_value(updater, raw, 'governing_law')
- replace_setting_value(updater, raw, 'city_for_disputes')
+ replace_setting_value(updater, raw, "company_name")
+ replace_setting_value(updater, raw, "governing_law")
+ replace_setting_value(updater, raw, "city_for_disputes")
end
if updater.errors.blank?
- updater.apply_settings(:company_name, :governing_law, :city_for_disputes, :contact_url, :contact_email)
+ updater.apply_settings(
+ :company_name,
+ :governing_law,
+ :city_for_disputes,
+ :contact_url,
+ :contact_email,
+ )
end
end
end
@@ -262,7 +288,7 @@ class Wizard
end
def reserved_usernames
- @reserved_usernames ||= SiteSetting.defaults[:reserved_usernames].split('|')
+ @reserved_usernames ||= SiteSetting.defaults[:reserved_usernames].split("|")
end
def update_tos
diff --git a/lib/wizard/field.rb b/lib/wizard/field.rb
index 0fccefb9a88..9f47b5cbdf2 100644
--- a/lib/wizard/field.rb
+++ b/lib/wizard/field.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
class Wizard
-
class Choice
attr_reader :id, :label, :icon, :data, :extra_label
attr_accessor :field
@@ -39,6 +38,5 @@ class Wizard
@choices << choice
choice
end
-
end
end
diff --git a/lib/wizard/step_updater.rb b/lib/wizard/step_updater.rb
index a3e7d79f5ab..078a208b029 100644
--- a/lib/wizard/step_updater.rb
+++ b/lib/wizard/step_updater.rb
@@ -34,11 +34,18 @@ class Wizard
value = value.strip if value.is_a?(String)
if !value.is_a?(Upload) && SiteSetting.type_supervisor.get_type(id) == :upload
- value = Upload.get_from_url(value) || ''
+ value = Upload.get_from_url(value) || ""
end
if id == :navigation_menu
- value = value.to_s == "true" ? NavigationMenuSiteSetting::SIDEBAR : NavigationMenuSiteSetting::HEADER_DROPDOWN
+ value =
+ (
+ if value.to_s == "true"
+ NavigationMenuSiteSetting::SIDEBAR
+ else
+ NavigationMenuSiteSetting::HEADER_DROPDOWN
+ end
+ )
end
SiteSetting.set_and_log(id, value, @current_user) if SiteSetting.get(id) != value
@@ -51,12 +58,11 @@ class Wizard
end
def ensure_changed(id)
- errors.add(id, '') if @fields[id] == SiteSetting.defaults[id]
+ errors.add(id, "") if @fields[id] == SiteSetting.defaults[id]
end
def apply_settings(*ids)
ids.each { |id| apply_setting(id) }
end
-
end
end