post_status_service.rb 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # frozen_string_literal: true
  2. class PostStatusService < BaseService
  3. include Redisable
  4. include LanguagesHelper
  5. class UnexpectedMentionsError < StandardError
  6. attr_reader :accounts
  7. def initialize(message, accounts)
  8. super(message)
  9. @accounts = accounts
  10. end
  11. end
  12. # Post a text status update, fetch and notify remote users mentioned
  13. # @param [Account] account Account from which to post
  14. # @param [Hash] options
  15. # @option [String] :text Message
  16. # @option [Status] :thread Optional status to reply to
  17. # @option [Boolean] :sensitive
  18. # @option [String] :visibility
  19. # @option [String] :spoiler_text
  20. # @option [String] :language
  21. # @option [String] :scheduled_at
  22. # @option [Hash] :poll Optional poll to attach
  23. # @option [Enumerable] :media_ids Optional array of media IDs to attach
  24. # @option [Doorkeeper::Application] :application
  25. # @option [String] :idempotency Optional idempotency key
  26. # @option [Boolean] :with_rate_limit
  27. # @option [Enumerable] :allowed_mentions Optional array of expected mentioned account IDs, raises `UnexpectedMentionsError` if unexpected accounts end up in mentions
  28. # @return [Status]
  29. def call(account, options = {})
  30. @account = account
  31. @options = options
  32. @text = @options[:text] || ''
  33. @in_reply_to = @options[:thread]
  34. return idempotency_duplicate if idempotency_given? && idempotency_duplicate?
  35. validate_media!
  36. preprocess_attributes!
  37. if scheduled?
  38. schedule_status!
  39. else
  40. process_status!
  41. end
  42. redis.setex(idempotency_key, 3_600, @status.id) if idempotency_given?
  43. unless scheduled?
  44. postprocess_status!
  45. bump_potential_friendship!
  46. end
  47. @status
  48. end
  49. private
  50. def preprocess_attributes!
  51. @sensitive = (@options[:sensitive].nil? ? @account.user&.setting_default_sensitive : @options[:sensitive]) || @options[:spoiler_text].present?
  52. @text = @options.delete(:spoiler_text) if @text.blank? && @options[:spoiler_text].present?
  53. @visibility = @options[:visibility] || @account.user&.setting_default_privacy
  54. @visibility = :unlisted if @visibility&.to_sym == :public && @account.silenced?
  55. @scheduled_at = @options[:scheduled_at]&.to_datetime
  56. @scheduled_at = nil if scheduled_in_the_past?
  57. rescue ArgumentError
  58. raise ActiveRecord::RecordInvalid
  59. end
  60. def process_status!
  61. @status = @account.statuses.new(status_attributes)
  62. process_mentions_service.call(@status, save_records: false)
  63. safeguard_mentions!(@status)
  64. # The following transaction block is needed to wrap the UPDATEs to
  65. # the media attachments when the status is created
  66. ApplicationRecord.transaction do
  67. @status.save!
  68. end
  69. end
  70. def safeguard_mentions!(status)
  71. return if @options[:allowed_mentions].nil?
  72. expected_account_ids = @options[:allowed_mentions].map(&:to_i)
  73. unexpected_accounts = status.mentions.map(&:account).to_a.reject { |mentioned_account| expected_account_ids.include?(mentioned_account.id) }
  74. return if unexpected_accounts.empty?
  75. raise UnexpectedMentionsError.new('Post would be sent to unexpected accounts', unexpected_accounts)
  76. end
  77. def schedule_status!
  78. status_for_validation = @account.statuses.build(status_attributes)
  79. if status_for_validation.valid?
  80. # Marking the status as destroyed is necessary to prevent the status from being
  81. # persisted when the associated media attachments get updated when creating the
  82. # scheduled status.
  83. status_for_validation.destroy
  84. # The following transaction block is needed to wrap the UPDATEs to
  85. # the media attachments when the scheduled status is created
  86. ApplicationRecord.transaction do
  87. @status = @account.scheduled_statuses.create!(scheduled_status_attributes)
  88. end
  89. else
  90. raise ActiveRecord::RecordInvalid
  91. end
  92. end
  93. def postprocess_status!
  94. process_hashtags_service.call(@status)
  95. Trends.tags.register(@status)
  96. LinkCrawlWorker.perform_async(@status.id)
  97. DistributionWorker.perform_async(@status.id)
  98. ActivityPub::DistributionWorker.perform_async(@status.id)
  99. PollExpirationNotifyWorker.perform_at(@status.poll.expires_at, @status.poll.id) if @status.poll
  100. end
  101. def validate_media!
  102. if @options[:media_ids].blank? || !@options[:media_ids].is_a?(Enumerable)
  103. @media = []
  104. return
  105. end
  106. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.too_many') if @options[:media_ids].size > Status::MEDIA_ATTACHMENTS_LIMIT || @options[:poll].present?
  107. @media = @account.media_attachments.where(status_id: nil).where(id: @options[:media_ids].take(Status::MEDIA_ATTACHMENTS_LIMIT).map(&:to_i))
  108. not_found_ids = @options[:media_ids].map(&:to_i) - @media.map(&:id)
  109. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.not_found', ids: not_found_ids.join(', ')) if not_found_ids.any?
  110. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if @media.size > 1 && @media.find(&:audio_or_video?)
  111. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.not_ready') if @media.any?(&:not_processed?)
  112. end
  113. def process_mentions_service
  114. ProcessMentionsService.new
  115. end
  116. def process_hashtags_service
  117. ProcessHashtagsService.new
  118. end
  119. def scheduled?
  120. @scheduled_at.present?
  121. end
  122. def idempotency_key
  123. "idempotency:status:#{@account.id}:#{@options[:idempotency]}"
  124. end
  125. def idempotency_given?
  126. @options[:idempotency].present?
  127. end
  128. def idempotency_duplicate
  129. if scheduled?
  130. @account.scheduled_statuses.find(@idempotency_duplicate)
  131. else
  132. @account.statuses.find(@idempotency_duplicate)
  133. end
  134. end
  135. def idempotency_duplicate?
  136. @idempotency_duplicate = redis.get(idempotency_key)
  137. end
  138. def scheduled_in_the_past?
  139. @scheduled_at.present? && @scheduled_at <= Time.now.utc
  140. end
  141. def bump_potential_friendship!
  142. return if !@status.reply? || @account.id == @status.in_reply_to_account_id
  143. ActivityTracker.increment('activity:interactions')
  144. end
  145. def status_attributes
  146. {
  147. text: @text,
  148. media_attachments: @media || [],
  149. ordered_media_attachment_ids: (@options[:media_ids] || []).map(&:to_i) & @media.map(&:id),
  150. thread: @in_reply_to,
  151. poll_attributes: poll_attributes,
  152. sensitive: @sensitive,
  153. spoiler_text: @options[:spoiler_text] || '',
  154. visibility: @visibility,
  155. language: valid_locale_cascade(@options[:language], @account.user&.preferred_posting_language, I18n.default_locale),
  156. application: @options[:application],
  157. rate_limit: @options[:with_rate_limit],
  158. }.compact
  159. end
  160. def scheduled_status_attributes
  161. {
  162. scheduled_at: @scheduled_at,
  163. media_attachments: @media || [],
  164. params: scheduled_options,
  165. }
  166. end
  167. def poll_attributes
  168. return if @options[:poll].blank?
  169. @options[:poll].merge(account: @account, voters_count: 0)
  170. end
  171. def scheduled_options
  172. @options.dup.tap do |options_hash|
  173. options_hash[:in_reply_to_id] = options_hash.delete(:thread)&.id
  174. options_hash[:application_id] = options_hash.delete(:application)&.id
  175. options_hash[:scheduled_at] = nil
  176. options_hash[:idempotency] = nil
  177. options_hash[:with_rate_limit] = false
  178. end
  179. end
  180. end