post_status_service.rb 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # frozen_string_literal: true
  2. class PostStatusService < BaseService
  3. include Redisable
  4. include LanguagesHelper
  5. MIN_SCHEDULE_OFFSET = 5.minutes.freeze
  6. # Post a text status update, fetch and notify remote users mentioned
  7. # @param [Account] account Account from which to post
  8. # @param [Hash] options
  9. # @option [String] :text Message
  10. # @option [Status] :thread Optional status to reply to
  11. # @option [Boolean] :sensitive
  12. # @option [String] :visibility
  13. # @option [String] :spoiler_text
  14. # @option [String] :language
  15. # @option [String] :scheduled_at
  16. # @option [Hash] :poll Optional poll to attach
  17. # @option [Enumerable] :media_ids Optional array of media IDs to attach
  18. # @option [Doorkeeper::Application] :application
  19. # @option [String] :idempotency Optional idempotency key
  20. # @option [Boolean] :with_rate_limit
  21. # @return [Status]
  22. def call(account, options = {})
  23. @account = account
  24. @options = options
  25. @text = @options[:text] || ''
  26. @in_reply_to = @options[:thread]
  27. return idempotency_duplicate if idempotency_given? && idempotency_duplicate?
  28. validate_media!
  29. preprocess_attributes!
  30. if scheduled?
  31. schedule_status!
  32. else
  33. process_status!
  34. postprocess_status!
  35. bump_potential_friendship!
  36. end
  37. redis.setex(idempotency_key, 3_600, @status.id) if idempotency_given?
  38. @status
  39. end
  40. private
  41. def preprocess_attributes!
  42. @sensitive = (@options[:sensitive].nil? ? @account.user&.setting_default_sensitive : @options[:sensitive]) || @options[:spoiler_text].present?
  43. @text = @options.delete(:spoiler_text) if @text.blank? && @options[:spoiler_text].present?
  44. @visibility = @options[:visibility] || @account.user&.setting_default_privacy
  45. @visibility = :unlisted if @visibility&.to_sym == :public && @account.silenced?
  46. @scheduled_at = @options[:scheduled_at]&.to_datetime
  47. @scheduled_at = nil if scheduled_in_the_past?
  48. rescue ArgumentError
  49. raise ActiveRecord::RecordInvalid
  50. end
  51. def process_status!
  52. # The following transaction block is needed to wrap the UPDATEs to
  53. # the media attachments when the status is created
  54. ApplicationRecord.transaction do
  55. @status = @account.statuses.create!(status_attributes)
  56. end
  57. process_hashtags_service.call(@status)
  58. process_mentions_service.call(@status)
  59. end
  60. def schedule_status!
  61. status_for_validation = @account.statuses.build(status_attributes)
  62. if status_for_validation.valid?
  63. # Marking the status as destroyed is necessary to prevent the status from being
  64. # persisted when the associated media attachments get updated when creating the
  65. # scheduled status.
  66. status_for_validation.destroy
  67. # The following transaction block is needed to wrap the UPDATEs to
  68. # the media attachments when the scheduled status is created
  69. ApplicationRecord.transaction do
  70. @status = @account.scheduled_statuses.create!(scheduled_status_attributes)
  71. end
  72. else
  73. raise ActiveRecord::RecordInvalid
  74. end
  75. end
  76. def local_only_option(local_only, in_reply_to, federation_setting, text, spoiler_text)
  77. # This is intended for third party clients. The admin can set a custom :local_only:
  78. # emoji that users can append to force a post to be local only.
  79. if text.include?(':local_only:') ||
  80. spoiler_text&.include?(':local_only')
  81. return true
  82. end
  83. if local_only.nil?
  84. if in_reply_to && in_reply_to.local_only
  85. return true
  86. end
  87. if in_reply_to && !in_reply_to.local_only
  88. return false
  89. end
  90. return !federation_setting
  91. end
  92. local_only
  93. end
  94. def postprocess_status!
  95. Trends.tags.register(@status)
  96. LinkCrawlWorker.perform_async(@status.id)
  97. DistributionWorker.perform_async(@status.id)
  98. unless @status.local_only?
  99. ActivityPub::DistributionWorker.perform_async(@status.id)
  100. end
  101. PollExpirationNotifyWorker.perform_at(@status.poll.expires_at, @status.poll.id) if @status.poll
  102. end
  103. def validate_media!
  104. if @options[:media_ids].blank? || !@options[:media_ids].is_a?(Enumerable)
  105. @media = []
  106. return
  107. end
  108. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.too_many') if @options[:media_ids].size > 4 || @options[:poll].present?
  109. @media = @account.media_attachments.where(status_id: nil).where(id: @options[:media_ids].take(4).map(&:to_i))
  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.schedule_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 + MIN_SCHEDULE_OFFSET
  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. return if @account.following?(@status.in_reply_to_account_id)
  145. PotentialFriendshipTracker.record(@account.id, @status.in_reply_to_account_id, :reply)
  146. end
  147. def status_attributes
  148. {
  149. text: @text,
  150. media_attachments: @media || [],
  151. ordered_media_attachment_ids: (@options[:media_ids] || []).map(&:to_i) & @media.map(&:id),
  152. thread: @in_reply_to,
  153. poll_attributes: poll_attributes,
  154. sensitive: @sensitive,
  155. spoiler_text: @options[:spoiler_text] || '',
  156. visibility: @visibility,
  157. language: valid_locale_cascade(@options[:language], @account.user&.preferred_posting_language, I18n.default_locale),
  158. application: @options[:application],
  159. rate_limit: @options[:with_rate_limit],
  160. local_only: local_only_option(@options[:local_only], @in_reply_to, @account.user&.setting_default_federation, @text, @options[:spoiler_text]),
  161. }.compact
  162. end
  163. def scheduled_status_attributes
  164. {
  165. scheduled_at: @scheduled_at,
  166. media_attachments: @media || [],
  167. params: scheduled_options,
  168. }
  169. end
  170. def poll_attributes
  171. return if @options[:poll].blank?
  172. @options[:poll].merge(account: @account, voters_count: 0)
  173. end
  174. def scheduled_options
  175. @options.tap do |options_hash|
  176. options_hash[:in_reply_to_id] = options_hash.delete(:thread)&.id
  177. options_hash[:application_id] = options_hash.delete(:application)&.id
  178. options_hash[:scheduled_at] = nil
  179. options_hash[:idempotency] = nil
  180. options_hash[:with_rate_limit] = false
  181. end
  182. end
  183. end