post_status_service.rb 6.3 KB

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