You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

192 lines
6.0 KiB

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