post_status_service.rb 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 postprocess_status!
  77. process_hashtags_service.call(@status)
  78. process_mentions_service.call(@status)
  79. Trends.tags.register(@status)
  80. LinkCrawlWorker.perform_async(@status.id)
  81. DistributionWorker.perform_async(@status.id)
  82. ActivityPub::DistributionWorker.perform_async(@status.id)
  83. PollExpirationNotifyWorker.perform_at(@status.poll.expires_at, @status.poll.id) if @status.poll
  84. end
  85. def validate_media!
  86. if @options[:media_ids].blank? || !@options[:media_ids].is_a?(Enumerable)
  87. @media = []
  88. return
  89. end
  90. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.too_many') if @options[:media_ids].size > 4 || @options[:poll].present?
  91. @media = @account.media_attachments.where(status_id: nil).where(id: @options[:media_ids].take(4).map(&:to_i))
  92. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if @media.size > 1 && @media.find(&:audio_or_video?)
  93. raise Mastodon::ValidationError, I18n.t('media_attachments.validations.not_ready') if @media.any?(&:not_processed?)
  94. end
  95. def process_mentions_service
  96. ProcessMentionsService.new
  97. end
  98. def process_hashtags_service
  99. ProcessHashtagsService.new
  100. end
  101. def scheduled?
  102. @scheduled_at.present?
  103. end
  104. def idempotency_key
  105. "idempotency:status:#{@account.id}:#{@options[:idempotency]}"
  106. end
  107. def idempotency_given?
  108. @options[:idempotency].present?
  109. end
  110. def idempotency_duplicate
  111. if scheduled?
  112. @account.schedule_statuses.find(@idempotency_duplicate)
  113. else
  114. @account.statuses.find(@idempotency_duplicate)
  115. end
  116. end
  117. def idempotency_duplicate?
  118. @idempotency_duplicate = redis.get(idempotency_key)
  119. end
  120. def scheduled_in_the_past?
  121. @scheduled_at.present? && @scheduled_at <= Time.now.utc + MIN_SCHEDULE_OFFSET
  122. end
  123. def bump_potential_friendship!
  124. return if !@status.reply? || @account.id == @status.in_reply_to_account_id
  125. ActivityTracker.increment('activity:interactions')
  126. return if @account.following?(@status.in_reply_to_account_id)
  127. PotentialFriendshipTracker.record(@account.id, @status.in_reply_to_account_id, :reply)
  128. end
  129. def status_attributes
  130. {
  131. text: @text,
  132. media_attachments: @media || [],
  133. ordered_media_attachment_ids: (@options[:media_ids] || []).map(&:to_i) & @media.map(&:id),
  134. thread: @in_reply_to,
  135. poll_attributes: poll_attributes,
  136. sensitive: @sensitive,
  137. spoiler_text: @options[:spoiler_text] || '',
  138. visibility: @visibility,
  139. language: valid_locale_cascade(@options[:language], @account.user&.preferred_posting_language, I18n.default_locale),
  140. application: @options[:application],
  141. rate_limit: @options[:with_rate_limit],
  142. }.compact
  143. end
  144. def scheduled_status_attributes
  145. {
  146. scheduled_at: @scheduled_at,
  147. media_attachments: @media || [],
  148. params: scheduled_options,
  149. }
  150. end
  151. def poll_attributes
  152. return if @options[:poll].blank?
  153. @options[:poll].merge(account: @account, voters_count: 0)
  154. end
  155. def scheduled_options
  156. @options.tap do |options_hash|
  157. options_hash[:in_reply_to_id] = options_hash.delete(:thread)&.id
  158. options_hash[:application_id] = options_hash.delete(:application)&.id
  159. options_hash[:scheduled_at] = nil
  160. options_hash[:idempotency] = nil
  161. options_hash[:with_rate_limit] = false
  162. end
  163. end
  164. end