post_status_service.rb 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. end
  35. redis.setex(idempotency_key, 3_600, @status.id) if idempotency_given?
  36. unless scheduled?
  37. postprocess_status!
  38. bump_potential_friendship!
  39. end
  40. @status
  41. end
  42. private
  43. def preprocess_attributes!
  44. @sensitive = (@options[:sensitive].nil? ? @account.user&.setting_default_sensitive : @options[:sensitive]) || @options[:spoiler_text].present?
  45. @text = @options.delete(:spoiler_text) if @text.blank? && @options[:spoiler_text].present?
  46. @visibility = @options[:visibility] || @account.user&.setting_default_privacy
  47. @visibility = :unlisted if @visibility&.to_sym == :public && @account.silenced?
  48. @scheduled_at = @options[:scheduled_at]&.to_datetime
  49. @scheduled_at = nil if scheduled_in_the_past?
  50. rescue ArgumentError
  51. raise ActiveRecord::RecordInvalid
  52. end
  53. def process_status!
  54. # The following transaction block is needed to wrap the UPDATEs to
  55. # the media attachments when the status is created
  56. ApplicationRecord.transaction do
  57. @status = @account.statuses.create!(status_attributes)
  58. end
  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. process_hashtags_service.call(@status)
  96. process_mentions_service.call(@status)
  97. Trends.tags.register(@status)
  98. LinkCrawlWorker.perform_async(@status.id)
  99. DistributionWorker.perform_async(@status.id)
  100. unless @status.local_only?
  101. ActivityPub::DistributionWorker.perform_async(@status.id)
  102. end
  103. PollExpirationNotifyWorker.perform_at(@status.poll.expires_at, @status.poll.id) if @status.poll
  104. end
  105. def validate_media!
  106. if @options[:media_ids].blank? || !@options[:media_ids].is_a?(Enumerable)
  107. @media = []
  108. return
  109. end
  110. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.too_many') if @options[:media_ids].size > 4 || @options[:poll].present?
  111. @media = @account.media_attachments.where(status_id: nil).where(id: @options[:media_ids].take(4).map(&:to_i))
  112. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if @media.size > 1 && @media.find(&:audio_or_video?)
  113. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.not_ready') if @media.any?(&:not_processed?)
  114. end
  115. def process_mentions_service
  116. ProcessMentionsService.new
  117. end
  118. def process_hashtags_service
  119. ProcessHashtagsService.new
  120. end
  121. def scheduled?
  122. @scheduled_at.present?
  123. end
  124. def idempotency_key
  125. "idempotency:status:#{@account.id}:#{@options[:idempotency]}"
  126. end
  127. def idempotency_given?
  128. @options[:idempotency].present?
  129. end
  130. def idempotency_duplicate
  131. if scheduled?
  132. @account.schedule_statuses.find(@idempotency_duplicate)
  133. else
  134. @account.statuses.find(@idempotency_duplicate)
  135. end
  136. end
  137. def idempotency_duplicate?
  138. @idempotency_duplicate = redis.get(idempotency_key)
  139. end
  140. def scheduled_in_the_past?
  141. @scheduled_at.present? && @scheduled_at <= Time.now.utc + MIN_SCHEDULE_OFFSET
  142. end
  143. def bump_potential_friendship!
  144. return if !@status.reply? || @account.id == @status.in_reply_to_account_id
  145. ActivityTracker.increment('activity:interactions')
  146. return if @account.following?(@status.in_reply_to_account_id)
  147. PotentialFriendshipTracker.record(@account.id, @status.in_reply_to_account_id, :reply)
  148. end
  149. def status_attributes
  150. {
  151. text: @text,
  152. media_attachments: @media || [],
  153. ordered_media_attachment_ids: (@options[:media_ids] || []).map(&:to_i) & @media.map(&:id),
  154. thread: @in_reply_to,
  155. poll_attributes: poll_attributes,
  156. sensitive: @sensitive,
  157. spoiler_text: @options[:spoiler_text] || '',
  158. visibility: @visibility,
  159. language: valid_locale_cascade(@options[:language], @account.user&.preferred_posting_language, I18n.default_locale),
  160. application: @options[:application],
  161. rate_limit: @options[:with_rate_limit],
  162. local_only: local_only_option(@options[:local_only], @in_reply_to, @account.user&.setting_default_federation, @text, @options[:spoiler_text]),
  163. }.compact
  164. end
  165. def scheduled_status_attributes
  166. {
  167. scheduled_at: @scheduled_at,
  168. media_attachments: @media || [],
  169. params: scheduled_options,
  170. }
  171. end
  172. def poll_attributes
  173. return if @options[:poll].blank?
  174. @options[:poll].merge(account: @account, voters_count: 0)
  175. end
  176. def scheduled_options
  177. @options.tap do |options_hash|
  178. options_hash[:in_reply_to_id] = options_hash.delete(:thread)&.id
  179. options_hash[:application_id] = options_hash.delete(:application)&.id
  180. options_hash[:scheduled_at] = nil
  181. options_hash[:idempotency] = nil
  182. options_hash[:with_rate_limit] = false
  183. end
  184. end
  185. end