1
0

post_status_service.rb 7.1 KB

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