mirror of https://framagit.org/tykayn/mastodon
Add support for editing for published statuses (#16697)
* Add support for editing for published statuses * Fix references to stripped-out code * Various fixes and improvements * Further fixes and improvements * Fix updates being potentially sent to unauthorized recipients * Various fixes and improvements * Fix wrong words in test * Fix notifying accounts that were tagged but were not in the audience * Fix mistakemaster
parent
2d1f082bb6
commit
1060666c58
|
@ -0,0 +1,21 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class Api::V1::Statuses::HistoriesController < Api::BaseController
|
||||
include Authorization
|
||||
|
||||
before_action -> { authorize_if_got_token! :read, :'read:statuses' }
|
||||
before_action :set_status
|
||||
|
||||
def show
|
||||
render json: @status.edits, each_serializer: REST::StatusEditSerializer
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_status
|
||||
@status = Status.find(params[:status_id])
|
||||
authorize @status, :show?
|
||||
rescue Mastodon::NotPermittedError
|
||||
not_found
|
||||
end
|
||||
end
|
|
@ -0,0 +1,21 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class Api::V1::Statuses::SourcesController < Api::BaseController
|
||||
include Authorization
|
||||
|
||||
before_action -> { doorkeeper_authorize! :read, :'read:statuses' }
|
||||
before_action :set_status
|
||||
|
||||
def show
|
||||
render json: @status, serializer: REST::StatusSourceSerializer
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_status
|
||||
@status = Status.find(params[:status_id])
|
||||
authorize @status, :show?
|
||||
rescue Mastodon::NotPermittedError
|
||||
not_found
|
||||
end
|
||||
end
|
|
@ -34,7 +34,13 @@ module JsonLdHelper
|
|||
end
|
||||
|
||||
def as_array(value)
|
||||
value.is_a?(Array) ? value : [value]
|
||||
if value.nil?
|
||||
[]
|
||||
elsif value.is_a?(Array)
|
||||
value
|
||||
else
|
||||
[value]
|
||||
end
|
||||
end
|
||||
|
||||
def value_or_id(value)
|
||||
|
|
|
@ -54,9 +54,10 @@ export function normalizeStatus(status, normalOldStatus) {
|
|||
normalStatus.poll = status.poll.id;
|
||||
}
|
||||
|
||||
// Only calculate these values when status first encountered
|
||||
// Otherwise keep the ones already in the reducer
|
||||
if (normalOldStatus) {
|
||||
// Only calculate these values when status first encountered and
|
||||
// when the underlying values change. Otherwise keep the ones
|
||||
// already in the reducer
|
||||
if (normalOldStatus && normalOldStatus.get('content') === normalStatus.content && normalOldStatus.get('spoiler_text') === normalStatus.spoiler_text) {
|
||||
normalStatus.search_index = normalOldStatus.get('search_index');
|
||||
normalStatus.contentHtml = normalOldStatus.get('contentHtml');
|
||||
normalStatus.spoilerHtml = normalOldStatus.get('spoilerHtml');
|
||||
|
|
|
@ -131,6 +131,9 @@ export function deleteStatusFail(id, error) {
|
|||
};
|
||||
};
|
||||
|
||||
export const updateStatus = status => dispatch =>
|
||||
dispatch(importFetchedStatus(status));
|
||||
|
||||
export function fetchContext(id) {
|
||||
return (dispatch, getState) => {
|
||||
dispatch(fetchContextRequest(id));
|
||||
|
|
|
@ -10,6 +10,7 @@ import {
|
|||
} from './timelines';
|
||||
import { updateNotifications, expandNotifications } from './notifications';
|
||||
import { updateConversations } from './conversations';
|
||||
import { updateStatus } from './statuses';
|
||||
import {
|
||||
fetchAnnouncements,
|
||||
updateAnnouncements,
|
||||
|
@ -75,6 +76,9 @@ export const connectTimelineStream = (timelineId, channelName, params = {}, opti
|
|||
case 'update':
|
||||
dispatch(updateTimeline(timelineId, JSON.parse(data.payload), options.accept));
|
||||
break;
|
||||
case 'status.update':
|
||||
dispatch(updateStatus(JSON.parse(data.payload)));
|
||||
break;
|
||||
case 'delete':
|
||||
dispatch(deleteFromTimelines(data.payload));
|
||||
break;
|
||||
|
|
|
@ -57,6 +57,7 @@ const messages = defineMessages({
|
|||
unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' },
|
||||
private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' },
|
||||
direct_short: { id: 'privacy.direct.short', defaultMessage: 'Direct' },
|
||||
edited: { id: 'status.edited', defaultMessage: 'Edited {date}' },
|
||||
});
|
||||
|
||||
export default @injectIntl
|
||||
|
@ -483,7 +484,7 @@ class Status extends ImmutablePureComponent {
|
|||
<div className='status__info'>
|
||||
<a onClick={this.handleClick} href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener noreferrer'>
|
||||
<span className='status__visibility-icon'><Icon id={visibilityIcon.icon} title={visibilityIcon.text} /></span>
|
||||
<RelativeTimestamp timestamp={status.get('created_at')} />
|
||||
<RelativeTimestamp timestamp={status.get('created_at')} />{status.get('edited_at') && <abbr title={intl.formatMessage(messages.edited, { date: intl.formatDate(status.get('edited_at'), { hour12: false, year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) })}> *</abbr>}
|
||||
</a>
|
||||
|
||||
<a onClick={this.handleAccountClick} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name' target='_blank' rel='noopener noreferrer'>
|
||||
|
|
|
@ -6,7 +6,7 @@ import DisplayName from '../../../components/display_name';
|
|||
import StatusContent from '../../../components/status_content';
|
||||
import MediaGallery from '../../../components/media_gallery';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { injectIntl, defineMessages, FormattedDate } from 'react-intl';
|
||||
import { injectIntl, defineMessages, FormattedDate, FormattedMessage } from 'react-intl';
|
||||
import Card from './card';
|
||||
import ImmutablePureComponent from 'react-immutable-pure-component';
|
||||
import Video from '../../video';
|
||||
|
@ -116,6 +116,7 @@ class DetailedStatus extends ImmutablePureComponent {
|
|||
let reblogLink = '';
|
||||
let reblogIcon = 'retweet';
|
||||
let favouriteLink = '';
|
||||
let edited = '';
|
||||
|
||||
if (this.props.measureHeight) {
|
||||
outerStyle.height = `${this.state.height}px`;
|
||||
|
@ -237,6 +238,15 @@ class DetailedStatus extends ImmutablePureComponent {
|
|||
);
|
||||
}
|
||||
|
||||
if (status.get('edited_at')) {
|
||||
edited = (
|
||||
<React.Fragment>
|
||||
<React.Fragment> · </React.Fragment>
|
||||
<FormattedMessage id='status.edited' defaultMessage='Edited {date}' values={{ date: intl.formatDate(status.get('edited_at'), { hour12: false, month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) }} />
|
||||
</React.Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={outerStyle}>
|
||||
<div ref={this.setRef} className={classNames('detailed-status', `detailed-status-${status.get('visibility')}`, { compact })}>
|
||||
|
@ -252,7 +262,7 @@ class DetailedStatus extends ImmutablePureComponent {
|
|||
<div className='detailed-status__meta'>
|
||||
<a className='detailed-status__datetime' href={status.get('url')} target='_blank' rel='noopener noreferrer'>
|
||||
<FormattedDate value={new Date(status.get('created_at'))} hour12={false} year='numeric' month='short' day='2-digit' hour='2-digit' minute='2-digit' />
|
||||
</a>{visibilityLink}{applicationLink}{reblogLink} · {favouriteLink}
|
||||
</a>{edited}{visibilityLink}{applicationLink}{reblogLink} · {favouriteLink}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -967,6 +967,17 @@
|
|||
}
|
||||
}
|
||||
|
||||
.status__content__edited-label {
|
||||
display: block;
|
||||
cursor: default;
|
||||
font-size: 15px;
|
||||
line-height: 20px;
|
||||
padding: 0;
|
||||
padding-top: 8px;
|
||||
color: $dark-text-color;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.status__content__spoiler-link {
|
||||
display: inline-block;
|
||||
border-radius: 2px;
|
||||
|
|
|
@ -94,49 +94,6 @@ class ActivityPub::Activity
|
|||
equals_or_includes_any?(@object['type'], CONVERTED_TYPES)
|
||||
end
|
||||
|
||||
def distribute(status)
|
||||
crawl_links(status)
|
||||
|
||||
notify_about_reblog(status) if reblog_of_local_account?(status) && !reblog_by_following_group_account?(status)
|
||||
notify_about_mentions(status)
|
||||
|
||||
# Only continue if the status is supposed to have arrived in real-time.
|
||||
# Note that if @options[:override_timestamps] isn't set, the status
|
||||
# may have a lower snowflake id than other existing statuses, potentially
|
||||
# "hiding" it from paginated API calls
|
||||
return unless @options[:override_timestamps] || status.within_realtime_window?
|
||||
|
||||
distribute_to_followers(status)
|
||||
end
|
||||
|
||||
def reblog_of_local_account?(status)
|
||||
status.reblog? && status.reblog.account.local?
|
||||
end
|
||||
|
||||
def reblog_by_following_group_account?(status)
|
||||
status.reblog? && status.account.group? && status.reblog.account.following?(status.account)
|
||||
end
|
||||
|
||||
def notify_about_reblog(status)
|
||||
NotifyService.new.call(status.reblog.account, :reblog, status)
|
||||
end
|
||||
|
||||
def notify_about_mentions(status)
|
||||
status.active_mentions.includes(:account).each do |mention|
|
||||
next unless mention.account.local? && audience_includes?(mention.account)
|
||||
NotifyService.new.call(mention.account, :mention, mention)
|
||||
end
|
||||
end
|
||||
|
||||
def crawl_links(status)
|
||||
# Spread out crawling randomly to avoid DDoSing the link
|
||||
LinkCrawlWorker.perform_in(rand(1..59).seconds, status.id)
|
||||
end
|
||||
|
||||
def distribute_to_followers(status)
|
||||
::DistributionWorker.perform_async(status.id)
|
||||
end
|
||||
|
||||
def delete_arrived_first?(uri)
|
||||
redis.exists?("delete_upon_arrival:#{@account.id}:#{uri}")
|
||||
end
|
||||
|
|
|
@ -25,7 +25,7 @@ class ActivityPub::Activity::Announce < ActivityPub::Activity
|
|||
Trends.tags.register(@status)
|
||||
Trends.links.register(@status)
|
||||
|
||||
distribute(@status)
|
||||
distribute
|
||||
end
|
||||
|
||||
@status
|
||||
|
@ -33,6 +33,22 @@ class ActivityPub::Activity::Announce < ActivityPub::Activity
|
|||
|
||||
private
|
||||
|
||||
def distribute
|
||||
# Notify the author of the original status if that status is local
|
||||
NotifyService.new.call(@status.reblog.account, :reblog, @status) if reblog_of_local_account?(@status) && !reblog_by_following_group_account?(@status)
|
||||
|
||||
# Distribute into home and list feeds
|
||||
::DistributionWorker.perform_async(@status.id) if @options[:override_timestamps] || @status.within_realtime_window?
|
||||
end
|
||||
|
||||
def reblog_of_local_account?(status)
|
||||
status.reblog? && status.reblog.account.local?
|
||||
end
|
||||
|
||||
def reblog_by_following_group_account?(status)
|
||||
status.reblog? && status.account.group? && status.reblog.account.following?(status.account)
|
||||
end
|
||||
|
||||
def audience_to
|
||||
as_array(@json['to']).map { |x| value_or_id(x) }
|
||||
end
|
||||
|
|
|
@ -69,9 +69,10 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
end
|
||||
|
||||
def process_status
|
||||
@tags = []
|
||||
@mentions = []
|
||||
@params = {}
|
||||
@tags = []
|
||||
@mentions = []
|
||||
@silenced_account_ids = []
|
||||
@params = {}
|
||||
|
||||
process_status_params
|
||||
process_tags
|
||||
|
@ -84,10 +85,18 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
|
||||
resolve_thread(@status)
|
||||
fetch_replies(@status)
|
||||
distribute(@status)
|
||||
distribute
|
||||
forward_for_reply
|
||||
end
|
||||
|
||||
def distribute
|
||||
# Spread out crawling randomly to avoid DDoSing the link
|
||||
LinkCrawlWorker.perform_in(rand(1..59).seconds, @status.id)
|
||||
|
||||
# Distribute into home and list feeds and notify mentioned accounts
|
||||
::DistributionWorker.perform_async(@status.id, silenced_account_ids: @silenced_account_ids) if @options[:override_timestamps] || @status.within_realtime_window?
|
||||
end
|
||||
|
||||
def find_existing_status
|
||||
status = status_from_uri(object_uri)
|
||||
status ||= Status.find_by(uri: @object['atomUri']) if @object['atomUri'].present?
|
||||
|
@ -95,19 +104,22 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
end
|
||||
|
||||
def process_status_params
|
||||
@status_parser = ActivityPub::Parser::StatusParser.new(@json, followers_collection: @account.followers_url)
|
||||
|
||||
@params = begin
|
||||
{
|
||||
uri: object_uri,
|
||||
url: object_url || object_uri,
|
||||
uri: @status_parser.uri,
|
||||
url: @status_parser.url || @status_parser.uri,
|
||||
account: @account,
|
||||
text: text_from_content || '',
|
||||
language: detected_language,
|
||||
spoiler_text: converted_object_type? ? '' : (text_from_summary || ''),
|
||||
created_at: @object['published'],
|
||||
text: converted_object_type? ? converted_text : (@status_parser.text || ''),
|
||||
language: @status_parser.language || detected_language,
|
||||
spoiler_text: converted_object_type? ? '' : (@status_parser.spoiler_text || ''),
|
||||
created_at: @status_parser.created_at,
|
||||
edited_at: @status_parser.edited_at,
|
||||
override_timestamps: @options[:override_timestamps],
|
||||
reply: @object['inReplyTo'].present?,
|
||||
sensitive: @account.sensitized? || @object['sensitive'] || false,
|
||||
visibility: visibility_from_audience,
|
||||
reply: @status_parser.reply,
|
||||
sensitive: @account.sensitized? || @status_parser.sensitive || false,
|
||||
visibility: @status_parser.visibility,
|
||||
thread: replied_to_status,
|
||||
conversation: conversation_from_uri(@object['conversation']),
|
||||
media_attachment_ids: process_attachments.take(4).map(&:id),
|
||||
|
@ -117,42 +129,40 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
end
|
||||
|
||||
def process_audience
|
||||
(audience_to + audience_cc).uniq.each do |audience|
|
||||
next if ActivityPub::TagManager.instance.public_collection?(audience)
|
||||
# Unlike with tags, there is no point in resolving accounts we don't already
|
||||
# know here, because silent mentions would only be used for local access control anyway
|
||||
accounts_in_audience = (audience_to + audience_cc).uniq.filter_map do |audience|
|
||||
account_from_uri(audience) unless ActivityPub::TagManager.instance.public_collection?(audience)
|
||||
end
|
||||
|
||||
# Unlike with tags, there is no point in resolving accounts we don't already
|
||||
# know here, because silent mentions would only be used for local access
|
||||
# control anyway
|
||||
account = account_from_uri(audience)
|
||||
# If the payload was delivered to a specific inbox, the inbox owner must have
|
||||
# access to it, unless they already have access to it anyway
|
||||
if @options[:delivered_to_account_id]
|
||||
accounts_in_audience << delivered_to_account
|
||||
accounts_in_audience.uniq!
|
||||
end
|
||||
|
||||
next if account.nil? || @mentions.any? { |mention| mention.account_id == account.id }
|
||||
accounts_in_audience.each do |account|
|
||||
# This runs after tags are processed, and those translate into non-silent
|
||||
# mentions, which take precedence
|
||||
next if @mentions.any? { |mention| mention.account_id == account.id }
|
||||
|
||||
@mentions << Mention.new(account: account, silent: true)
|
||||
|
||||
# If there is at least one silent mention, then the status can be considered
|
||||
# as a limited-audience status, and not strictly a direct message, but only
|
||||
# if we considered a direct message in the first place
|
||||
next unless @params[:visibility] == :direct
|
||||
|
||||
@params[:visibility] = :limited
|
||||
@params[:visibility] = :limited if @params[:visibility] == :direct
|
||||
end
|
||||
|
||||
# If the payload was delivered to a specific inbox, the inbox owner must have
|
||||
# access to it, unless they already have access to it anyway
|
||||
return if @options[:delivered_to_account_id].nil? || @mentions.any? { |mention| mention.account_id == @options[:delivered_to_account_id] }
|
||||
|
||||
@mentions << Mention.new(account_id: @options[:delivered_to_account_id], silent: true)
|
||||
|
||||
return unless @params[:visibility] == :direct
|
||||
|
||||
@params[:visibility] = :limited
|
||||
# Accounts that are tagged but are not in the audience are not
|
||||
# supposed to be notified explicitly
|
||||
@silenced_account_ids = @mentions.map(&:account_id) - accounts_in_audience.map(&:id)
|
||||
end
|
||||
|
||||
def postprocess_audience_and_deliver
|
||||
return if @status.mentions.find_by(account_id: @options[:delivered_to_account_id])
|
||||
|
||||
delivered_to_account = Account.find(@options[:delivered_to_account_id])
|
||||
|
||||
@status.mentions.create(account: delivered_to_account, silent: true)
|
||||
@status.update(visibility: :limited) if @status.direct_visibility?
|
||||
|
||||
|
@ -161,6 +171,10 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
FeedInsertWorker.perform_async(@status.id, delivered_to_account.id, :home)
|
||||
end
|
||||
|
||||
def delivered_to_account
|
||||
@delivered_to_account ||= Account.find(@options[:delivered_to_account_id])
|
||||
end
|
||||
|
||||
def attach_tags(status)
|
||||
@tags.each do |tag|
|
||||
status.tags << tag
|
||||
|
@ -215,21 +229,22 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
|
||||
def process_emoji(tag)
|
||||
return if skip_download?
|
||||
return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
|
||||
|
||||
shortcode = tag['name'].delete(':')
|
||||
image_url = tag['icon']['url']
|
||||
uri = tag['id']
|
||||
updated = tag['updated']
|
||||
emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
|
||||
custom_emoji_parser = ActivityPub::Parser::CustomEmojiParser.new(tag)
|
||||
|
||||
return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
|
||||
return if custom_emoji_parser.shortcode.blank? || custom_emoji_parser.image_remote_url.blank?
|
||||
|
||||
emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
|
||||
emoji.image_remote_url = image_url
|
||||
emoji.save
|
||||
rescue Seahorse::Client::NetworkingError => e
|
||||
Rails.logger.warn "Error storing emoji: #{e}"
|
||||
emoji = CustomEmoji.find_by(shortcode: custom_emoji_parser.shortcode, domain: @account.domain)
|
||||
|
||||
return unless emoji.nil? || custom_emoji_parser.image_remote_url != emoji.image_remote_url || (custom_emoji_parser.updated_at && custom_emoji_parser.updated_at >= emoji.updated_at)
|
||||
|
||||
begin
|
||||
emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: custom_emoji_parser.shortcode, uri: custom_emoji_parser.uri)
|
||||
emoji.image_remote_url = custom_emoji_parser.image_remote_url
|
||||
emoji.save
|
||||
rescue Seahorse::Client::NetworkingError => e
|
||||
Rails.logger.warn "Error storing emoji: #{e}"
|
||||
end
|
||||
end
|
||||
|
||||
def process_attachments
|
||||
|
@ -238,14 +253,23 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
media_attachments = []
|
||||
|
||||
as_array(@object['attachment']).each do |attachment|
|
||||
next if attachment['url'].blank? || media_attachments.size >= 4
|
||||
media_attachment_parser = ActivityPub::Parser::MediaAttachmentParser.new(attachment)
|
||||
|
||||
next if media_attachment_parser.remote_url.blank? || media_attachments.size >= 4
|
||||
|
||||
begin
|
||||
href = Addressable::URI.parse(attachment['url']).normalize.to_s
|
||||
media_attachment = MediaAttachment.create(account: @account, remote_url: href, thumbnail_remote_url: icon_url_from_attachment(attachment), description: attachment['summary'].presence || attachment['name'].presence, focus: attachment['focalPoint'], blurhash: supported_blurhash?(attachment['blurhash']) ? attachment['blurhash'] : nil)
|
||||
media_attachment = MediaAttachment.create(
|
||||
account: @account,
|
||||
remote_url: media_attachment_parser.remote_url,
|
||||
thumbnail_remote_url: media_attachment_parser.thumbnail_remote_url,
|
||||
description: media_attachment_parser.description,
|
||||
focus: media_attachment_parser.focus,
|
||||
blurhash: media_attachment_parser.blurhash
|
||||
)
|
||||
|
||||
media_attachments << media_attachment
|
||||
|
||||
next if unsupported_media_type?(attachment['mediaType']) || skip_download?
|
||||
next if unsupported_media_type?(media_attachment_parser.file_content_type) || skip_download?
|
||||
|
||||
media_attachment.download_file!
|
||||
media_attachment.download_thumbnail!
|
||||
|
@ -263,42 +287,17 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
media_attachments
|
||||
end
|
||||
|
||||
def icon_url_from_attachment(attachment)
|
||||
url = attachment['icon'].is_a?(Hash) ? attachment['icon']['url'] : attachment['icon']
|
||||
Addressable::URI.parse(url).normalize.to_s if url.present?
|
||||
rescue Addressable::URI::InvalidURIError
|
||||
nil
|
||||
end
|
||||
|
||||
def process_poll
|
||||
return unless @object['type'] == 'Question' && (@object['anyOf'].is_a?(Array) || @object['oneOf'].is_a?(Array))
|
||||
poll_parser = ActivityPub::Parser::PollParser.new(@object)
|
||||
|
||||
expires_at = begin
|
||||
if @object['closed'].is_a?(String)
|
||||
@object['closed']
|
||||
elsif !@object['closed'].nil? && !@object['closed'].is_a?(FalseClass)
|
||||
Time.now.utc
|
||||
else
|
||||
@object['endTime']
|
||||
end
|
||||
end
|
||||
|
||||
if @object['anyOf'].is_a?(Array)
|
||||
multiple = true
|
||||
items = @object['anyOf']
|
||||
else
|
||||
multiple = false
|
||||
items = @object['oneOf']
|
||||
end
|
||||
|
||||
voters_count = @object['votersCount']
|
||||
return unless poll_parser.valid?
|
||||
|
||||
@account.polls.new(
|
||||
multiple: multiple,
|
||||
expires_at: expires_at,
|
||||
options: items.map { |item| item['name'].presence || item['content'] }.compact,
|
||||
cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 },
|
||||
voters_count: voters_count
|
||||
multiple: poll_parser.multiple,
|
||||
expires_at: poll_parser.expires_at,
|
||||
options: poll_parser.options,
|
||||
cached_tallies: poll_parser.cached_tallies,
|
||||
voters_count: poll_parser.voters_count
|
||||
)
|
||||
end
|
||||
|
||||
|
@ -351,23 +350,6 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
end
|
||||
end
|
||||
|
||||
def visibility_from_audience
|
||||
if audience_to.any? { |to| ActivityPub::TagManager.instance.public_collection?(to) }
|
||||
:public
|
||||
elsif audience_cc.any? { |cc| ActivityPub::TagManager.instance.public_collection?(cc) }
|
||||
:unlisted
|
||||
elsif audience_to.include?(@account.followers_url)
|
||||
:private
|
||||
else
|
||||
:direct
|
||||
end
|
||||
end
|
||||
|
||||
def audience_includes?(account)
|
||||
uri = ActivityPub::TagManager.instance.uri_for(account)
|
||||
audience_to.include?(uri) || audience_cc.include?(uri)
|
||||
end
|
||||
|
||||
def replied_to_status
|
||||
return @replied_to_status if defined?(@replied_to_status)
|
||||
|
||||
|
@ -384,81 +366,18 @@ class ActivityPub::Activity::Create < ActivityPub::Activity
|
|||
value_or_id(@object['inReplyTo'])
|
||||
end
|
||||
|
||||
def text_from_content
|
||||
return Formatter.instance.linkify([[text_from_name, text_from_summary.presence].compact.join("\n\n"), object_url || object_uri].join(' ')) if converted_object_type?
|
||||
|
||||
if @object['content'].present?
|
||||
@object['content']
|
||||
elsif content_language_map?
|
||||
@object['contentMap'].values.first
|
||||
end
|
||||
end
|
||||
|
||||
def text_from_summary
|
||||
if @object['summary'].present?
|
||||
@object['summary']
|
||||
elsif summary_language_map?
|
||||
@object['summaryMap'].values.first
|
||||
end
|
||||
end
|
||||
|
||||
def text_from_name
|
||||
if @object['name'].present?
|
||||
@object['name']
|
||||
elsif name_language_map?
|
||||
@object['nameMap'].values.first
|
||||
end
|
||||
def converted_text
|
||||
Formatter.instance.linkify([@status_parser.title.presence, @status_parser.spoiler_text.presence, @status_parser.url || @status_parser.uri].compact.join("\n\n"))
|
||||
end
|
||||
|
||||
def detected_language
|
||||
if content_language_map?
|
||||
@object['contentMap'].keys.first
|
||||
elsif name_language_map?
|
||||
@object['nameMap'].keys.first
|
||||
elsif summary_language_map?
|
||||
@object['summaryMap'].keys.first
|
||||
elsif supported_object_type?
|
||||
LanguageDetector.instance.detect(text_from_content, @account)
|
||||
end
|
||||
end
|
||||
|
||||
def object_url
|
||||
return if @object['url'].blank?
|
||||
|
||||
url_candidate = url_to_href(@object['url'], 'text/html')
|
||||
|
||||
if invalid_origin?(url_candidate)
|
||||
nil
|
||||
else
|
||||
url_candidate
|
||||
end
|
||||
end
|
||||
|
||||
def summary_language_map?
|
||||
@object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
|
||||
end
|
||||
|
||||
def content_language_map?
|
||||
@object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
|
||||
end
|
||||
|
||||
def name_language_map?
|
||||
@object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
|
||||
LanguageDetector.instance.detect(@status_parser.text, @account) if supported_object_type?
|
||||
end
|
||||
|
||||
def unsupported_media_type?(mime_type)
|
||||
mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
|
||||
end
|
||||
|
||||
def supported_blurhash?(blurhash)
|
||||
components = blurhash.blank? || !blurhash_valid_chars?(blurhash) ? nil : Blurhash.components(blurhash)
|
||||
components.present? && components.none? { |comp| comp > 5 }
|
||||
end
|
||||
|
||||
def blurhash_valid_chars?(blurhash)
|
||||
/^[\w#$%*+-.:;=?@\[\]^{|}~]+$/.match?(blurhash)
|
||||
end
|
||||
|
||||
def skip_download?
|
||||
return @skip_download if defined?(@skip_download)
|
||||
|
||||
|
|
|
@ -1,32 +1,31 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::Activity::Update < ActivityPub::Activity
|
||||
SUPPORTED_TYPES = %w(Application Group Organization Person Service).freeze
|
||||
|
||||
def perform
|
||||
dereference_object!
|
||||
|
||||
if equals_or_includes_any?(@object['type'], SUPPORTED_TYPES)
|
||||
if equals_or_includes_any?(@object['type'], %w(Application Group Organization Person Service))
|
||||
update_account
|
||||
elsif equals_or_includes_any?(@object['type'], %w(Question))
|
||||
update_poll
|
||||
elsif equals_or_includes_any?(@object['type'], %w(Note Question))
|
||||
update_status
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def update_account
|
||||
return if @account.uri != object_uri
|
||||
return reject_payload! if @account.uri != object_uri
|
||||
|
||||
ActivityPub::ProcessAccountService.new.call(@account.username, @account.domain, @object, signed_with_known_key: true)
|
||||
end
|
||||
|
||||
def update_poll
|
||||
def update_status
|
||||
return reject_payload! if invalid_origin?(@object['id'])
|
||||
|
||||
status = Status.find_by(uri: object_uri, account_id: @account.id)
|
||||
return if status.nil? || status.preloadable_poll.nil?
|
||||
|
||||
ActivityPub::ProcessPollService.new.call(status.preloadable_poll, @object)
|
||||
return if status.nil?
|
||||
|
||||
ActivityPub::ProcessStatusUpdateService.new.call(status, @object)
|
||||
end
|
||||
end
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::Parser::CustomEmojiParser
|
||||
include JsonLdHelper
|
||||
|
||||
def initialize(json)
|
||||
@json = json
|
||||
end
|
||||
|
||||
def uri
|
||||
@json['id']
|
||||
end
|
||||
|
||||
def shortcode
|
||||
@json['name']&.delete(':')
|
||||
end
|
||||
|
||||
def image_remote_url
|
||||
@json.dig('icon', 'url')
|
||||
end
|
||||
|
||||
def updated_at
|
||||
@json['updated']&.to_datetime
|
||||
rescue ArgumentError
|
||||
nil
|
||||
end
|
||||
end
|
|
@ -0,0 +1,58 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::Parser::MediaAttachmentParser
|
||||
include JsonLdHelper
|
||||
|
||||
def initialize(json)
|
||||
@json = json
|
||||
end
|
||||
|
||||
# @param [MediaAttachment] previous_record
|
||||
def significantly_changes?(previous_record)
|
||||
remote_url != previous_record.remote_url ||
|
||||
thumbnail_remote_url != previous_record.thumbnail_remote_url ||
|
||||
description != previous_record.description
|
||||
end
|
||||
|
||||
def remote_url
|
||||
Addressable::URI.parse(@json['url'])&.normalize&.to_s
|
||||
rescue Addressable::URI::InvalidURIError
|
||||
nil
|
||||
end
|
||||
|
||||
def thumbnail_remote_url
|
||||
Addressable::URI.parse(@json['icon'].is_a?(Hash) ? @json['icon']['url'] : @json['icon'])&.normalize&.to_s
|
||||
rescue Addressable::URI::InvalidURIError
|
||||
nil
|
||||
end
|
||||
|
||||
def description
|
||||
@json['summary'].presence || @json['name'].presence
|
||||
end
|
||||
|
||||
def focus
|
||||
@json['focalPoint']
|
||||
end
|
||||
|
||||
def blurhash
|
||||
supported_blurhash? ? @json['blurhash'] : nil
|
||||
end
|
||||
|
||||
def file_content_type
|
||||
@json['mediaType']
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def supported_blurhash?
|
||||
components = begin
|
||||
blurhash = @json['blurhash']
|
||||
|
||||
if blurhash.present? && /^[\w#$%*+-.:;=?@\[\]^{|}~]+$/.match?(blurhash)
|
||||
Blurhash.components(blurhash)
|
||||
end
|
||||
end
|
||||
|
||||
components.present? && components.none? { |comp| comp > 5 }
|
||||
end
|
||||
end
|
|
@ -0,0 +1,53 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::Parser::PollParser
|
||||
include JsonLdHelper
|
||||
|
||||
def initialize(json)
|
||||
@json = json
|
||||
end
|
||||
|
||||
def valid?
|
||||
equals_or_includes?(@json['type'], 'Question') && items.is_a?(Array)
|
||||
end
|
||||
|
||||
# @param [Poll] previous_record
|
||||
def significantly_changes?(previous_record)
|
||||
options != previous_record.options ||
|
||||
multiple != previous_record.multiple
|
||||
end
|
||||
|
||||
def options
|
||||
items.filter_map { |item| item['name'].presence || item['content'] }
|
||||
end
|
||||
|
||||
def multiple
|
||||
@json['anyOf'].is_a?(Array)
|
||||
end
|
||||
|
||||
def expires_at
|
||||
if @json['closed'].is_a?(String)
|
||||
@json['closed'].to_datetime
|
||||
elsif !@json['closed'].nil? && !@json['closed'].is_a?(FalseClass)
|
||||
Time.now.utc
|
||||
else
|
||||
@json['endTime']&.to_datetime
|
||||
end
|
||||
rescue ArgumentError
|
||||
nil
|
||||
end
|
||||
|
||||
def voters_count
|
||||
@json['votersCount']
|
||||
end
|
||||
|
||||
def cached_tallies
|
||||
items.map { |item| item.dig('replies', 'totalItems') || 0 }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def items
|
||||
@json['anyOf'] || @json['oneOf']
|
||||
end
|
||||
end
|
|
@ -0,0 +1,118 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::Parser::StatusParser
|
||||
include JsonLdHelper
|
||||
|
||||
# @param [Hash] json
|
||||
# @param [Hash] magic_values
|
||||
# @option magic_values [String] :followers_collection
|
||||
def initialize(json, magic_values = {})
|
||||
@json = json
|
||||
@object = json['object'] || json
|
||||
@magic_values = magic_values
|
||||
end
|
||||
|
||||
def uri
|
||||
id = @object['id']
|
||||
|
||||
if id&.start_with?('bear:')
|
||||
Addressable::URI.parse(id).query_values['u']
|
||||
else
|
||||
id
|
||||
end
|
||||
rescue Addressable::URI::InvalidURIError
|
||||
id
|
||||
end
|
||||
|
||||
def url
|
||||
url_to_href(@object['url'], 'text/html') if @object['url'].present?
|
||||
end
|
||||
|
||||
def text
|
||||
if @object['content'].present?
|
||||
@object['content']
|
||||
elsif content_language_map?
|
||||
@object['contentMap'].values.first
|
||||
end
|
||||
end
|
||||
|
||||
def spoiler_text
|
||||
if @object['summary'].present?
|
||||
@object['summary']
|
||||
elsif summary_language_map?
|
||||
@object['summaryMap'].values.first
|
||||
end
|
||||
end
|
||||
|
||||
def title
|
||||
if @object['name'].present?
|
||||
@object['name']
|
||||
elsif name_language_map?
|
||||
@object['nameMap'].values.first
|
||||
end
|
||||
end
|
||||
|
||||
def created_at
|
||||
@object['published']&.to_datetime
|
||||
rescue ArgumentError
|
||||
nil
|
||||
end
|
||||
|
||||
def edited_at
|
||||
@object['updated']&.to_datetime
|
||||
rescue ArgumentError
|
||||
nil
|
||||
end
|
||||
|
||||
def reply
|
||||
@object['inReplyTo'].present?
|
||||
end
|
||||
|
||||
def sensitive
|
||||
@object['sensitive']
|
||||
end
|
||||
|
||||
def visibility
|
||||
if audience_to.any? { |to| ActivityPub::TagManager.instance.public_collection?(to) }
|
||||
:public
|
||||
elsif audience_cc.any? { |cc| ActivityPub::TagManager.instance.public_collection?(cc) }
|
||||
:unlisted
|
||||
elsif audience_to.include?(@magic_values[:followers_collection])
|
||||
:private
|
||||
else
|
||||
:direct
|
||||
end
|
||||
end
|
||||
|
||||
def language
|
||||
if content_language_map?
|
||||
@object['contentMap'].keys.first
|
||||
elsif name_language_map?
|
||||
@object['nameMap'].keys.first
|
||||
elsif summary_language_map?
|
||||
@object['summaryMap'].keys.first
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def audience_to
|
||||
as_array(@object['to'] || @json['to']).map { |x| value_or_id(x) }
|
||||
end
|
||||
|
||||
def audience_cc
|
||||
as_array(@object['cc'] || @json['cc']).map { |x| value_or_id(x) }
|
||||
end
|
||||
|
||||
def summary_language_map?
|
||||
@object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
|
||||
end
|
||||
|
||||
def content_language_map?
|
||||
@object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
|
||||
end
|
||||
|
||||
def name_language_map?
|
||||
@object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
|
||||
end
|
||||
end
|
|
@ -53,46 +53,50 @@ class FeedManager
|
|||
# Add a status to a home feed and send a streaming API update
|
||||
# @param [Account] account
|
||||
# @param [Status] status
|
||||
# @param [Boolean] update
|
||||
# @return [Boolean]
|
||||
def push_to_home(account, status)
|
||||
def push_to_home(account, status, update: false)
|
||||
return false unless add_to_feed(:home, account.id, status, account.user&.aggregates_reblogs?)
|
||||
|
||||
trim(:home, account.id)
|
||||
PushUpdateWorker.perform_async(account.id, status.id, "timeline:#{account.id}") if push_update_required?("timeline:#{account.id}")
|
||||
PushUpdateWorker.perform_async(account.id, status.id, "timeline:#{account.id}", update: update) if push_update_required?("timeline:#{account.id}")
|
||||
true
|
||||
end
|
||||
|
||||
# Remove a status from a home feed and send a streaming API update
|
||||
# @param [Account] account
|
||||
# @param [Status] status
|
||||
# @param [Boolean] update
|
||||
# @return [Boolean]
|
||||
def unpush_from_home(account, status)
|
||||
def unpush_from_home(account, status, update: false)
|
||||
return false unless remove_from_feed(:home, account.id, status, account.user&.aggregates_reblogs?)
|
||||
|
||||
redis.publish("timeline:#{account.id}", Oj.dump(event: :delete, payload: status.id.to_s))
|
||||
redis.publish("timeline:#{account.id}", Oj.dump(event: :delete, payload: status.id.to_s)) unless update
|
||||
true
|
||||
end
|
||||
|
||||
# Add a status to a list feed and send a streaming API update
|
||||
# @param [List] list
|
||||
# @param [Status] status
|
||||
# @param [Boolean] update
|
||||
# @return [Boolean]
|
||||
def push_to_list(list, status)
|
||||
def push_to_list(list, status, update: false)
|
||||
return false if filter_from_list?(status, list) || !add_to_feed(:list, list.id, status, list.account.user&.aggregates_reblogs?)
|
||||
|
||||
trim(:list, list.id)
|
||||
PushUpdateWorker.perform_async(list.account_id, status.id, "timeline:list:#{list.id}") if push_update_required?("timeline:list:#{list.id}")
|
||||
PushUpdateWorker.perform_async(list.account_id, status.id, "timeline:list:#{list.id}", update: update) if push_update_required?("timeline:list:#{list.id}")
|
||||
true
|
||||
end
|
||||
|
||||
# Remove a status from a list feed and send a streaming API update
|
||||
# @param [List] list
|
||||
# @param [Status] status
|
||||
# @param [Boolean] update
|
||||
# @return [Boolean]
|
||||
def unpush_from_list(list, status)
|
||||
def unpush_from_list(list, status, update: false)
|
||||
return false unless remove_from_feed(:list, list.id, status, list.account.user&.aggregates_reblogs?)
|
||||
|
||||
redis.publish("timeline:list:#{list.id}", Oj.dump(event: :delete, payload: status.id.to_s))
|
||||
redis.publish("timeline:list:#{list.id}", Oj.dump(event: :delete, payload: status.id.to_s)) unless update
|
||||
true
|
||||
end
|
||||
|
||||
|
|
|
@ -1,8 +1,12 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class StatusReachFinder
|
||||
def initialize(status)
|
||||
@status = status
|
||||
# @param [Status] status
|
||||
# @param [Hash] options
|
||||
# @option options [Boolean] :unsafe
|
||||
def initialize(status, options = {})
|
||||
@status = status
|
||||
@options = options
|
||||
end
|
||||
|
||||
def inboxes
|
||||
|
@ -38,7 +42,7 @@ class StatusReachFinder
|
|||
end
|
||||
|
||||
def replied_to_account_id
|
||||
@status.in_reply_to_account_id
|
||||
@status.in_reply_to_account_id if distributable?
|
||||
end
|
||||
|
||||
def reblog_of_account_id
|
||||
|
@ -49,21 +53,26 @@ class StatusReachFinder
|
|||
@status.mentions.pluck(:account_id)
|
||||
end
|
||||
|
||||
# Beware: Reblogs can be created without the author having had access to the status
|
||||
def reblogs_account_ids
|
||||
@status.reblogs.pluck(:account_id)
|
||||
@status.reblogs.pluck(:account_id) if distributable? || unsafe?
|
||||
end
|
||||
|
||||
# Beware: Favourites can be created without the author having had access to the status
|
||||
def favourites_account_ids
|
||||
@status.favourites.pluck(:account_id)
|
||||
@status.favourites.pluck(:account_id) if distributable? || unsafe?
|
||||
end
|
||||
|
||||
# Beware: Replies can be created without the author having had access to the status
|
||||
def replies_account_ids
|
||||
@status.replies.pluck(:account_id)
|
||||
@status.replies.pluck(:account_id) if distributable? || unsafe?
|
||||
end
|
||||
|
||||
def followers_inboxes
|
||||
if @status.in_reply_to_local_account? && @status.distributable?
|
||||
if @status.in_reply_to_local_account? && distributable?
|
||||
@status.account.followers.or(@status.thread.account.followers).inboxes
|
||||
elsif @status.direct_visibility? || @status.limited_visibility?
|
||||
[]
|
||||
else
|
||||
@status.account.followers.inboxes
|
||||
end
|
||||
|
@ -76,4 +85,12 @@ class StatusReachFinder
|
|||
[]
|
||||
end
|
||||
end
|
||||
|
||||
def distributable?
|
||||
@status.public_visibility? || @status.unlisted_visibility?
|
||||
end
|
||||
|
||||
def unsafe?
|
||||
@options[:unsafe]
|
||||
end
|
||||
end
|
||||
|
|
|
@ -26,6 +26,7 @@ class Poll < ApplicationRecord
|
|||
belongs_to :status
|
||||
|
||||
has_many :votes, class_name: 'PollVote', inverse_of: :poll, dependent: :delete_all
|
||||
has_many :voters, -> { group('accounts.id') }, through: :votes, class_name: 'Account', source: :account
|
||||
|
||||
has_many :notifications, as: :activity, dependent: :destroy
|
||||
|
||||
|
|
|
@ -23,6 +23,7 @@
|
|||
# in_reply_to_account_id :bigint(8)
|
||||
# poll_id :bigint(8)
|
||||
# deleted_at :datetime
|
||||
# edited_at :datetime
|
||||
#
|
||||
|
||||
class Status < ApplicationRecord
|
||||
|
@ -56,6 +57,8 @@ class Status < ApplicationRecord
|
|||
belongs_to :thread, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :replies, optional: true
|
||||
belongs_to :reblog, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblogs, optional: true
|
||||
|
||||
has_many :edits, class_name: 'StatusEdit', inverse_of: :status, dependent: :destroy
|
||||
|
||||
has_many :favourites, inverse_of: :status, dependent: :destroy
|
||||
has_many :bookmarks, inverse_of: :status, dependent: :destroy
|
||||
has_many :reblogs, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblog, dependent: :destroy
|
||||
|
@ -209,6 +212,10 @@ class Status < ApplicationRecord
|
|||
public_visibility? || unlisted_visibility?
|
||||
end
|
||||
|
||||
def edited?
|
||||
edited_at.present?
|
||||
end
|
||||
|
||||
alias sign? distributable?
|
||||
|
||||
def with_media?
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
# frozen_string_literal: true
|
||||
# == Schema Information
|
||||
#
|
||||
# Table name: status_edits
|
||||
#
|
||||
# id :bigint(8) not null, primary key
|
||||
# status_id :bigint(8) not null
|
||||
# account_id :bigint(8)
|
||||
# text :text default(""), not null
|
||||
# spoiler_text :text default(""), not null
|
||||
# media_attachments_changed :boolean default(FALSE), not null
|
||||
# created_at :datetime not null
|
||||
# updated_at :datetime not null
|
||||
#
|
||||
|
||||
class StatusEdit < ApplicationRecord
|
||||
belongs_to :status
|
||||
belongs_to :account, optional: true
|
||||
|
||||
default_scope { order(id: :asc) }
|
||||
|
||||
delegate :local?, to: :status
|
||||
end
|
|
@ -11,6 +11,7 @@ class ActivityPub::NoteSerializer < ActivityPub::Serializer
|
|||
|
||||
attribute :content
|
||||
attribute :content_map, if: :language?
|
||||
attribute :updated, if: :edited?
|
||||
|
||||
has_many :media_attachments, key: :attachment
|
||||
has_many :virtual_tags, key: :tag
|
||||
|
@ -65,6 +66,8 @@ class ActivityPub::NoteSerializer < ActivityPub::Serializer
|
|||
object.language.present?
|
||||
end
|
||||
|
||||
delegate :edited?, to: :object
|
||||
|
||||
def in_reply_to
|
||||
return unless object.reply? && !object.thread.nil?
|
||||
|
||||
|
@ -79,6 +82,10 @@ class ActivityPub::NoteSerializer < ActivityPub::Serializer
|
|||
object.created_at.iso8601
|
||||
end
|
||||
|
||||
def updated
|
||||
object.edited_at.iso8601
|
||||
end
|
||||
|
||||
def url
|
||||
ActivityPub::TagManager.instance.url_for(object)
|
||||
end
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class REST::StatusEditSerializer < ActiveModel::Serializer
|
||||
attributes :text, :spoiler_text, :media_attachments_changed,
|
||||
:created_at
|
||||
end
|
|
@ -4,7 +4,7 @@ class REST::StatusSerializer < ActiveModel::Serializer
|
|||
attributes :id, :created_at, :in_reply_to_id, :in_reply_to_account_id,
|
||||
:sensitive, :spoiler_text, :visibility, :language,
|
||||
:uri, :url, :replies_count, :reblogs_count,
|
||||
:favourites_count
|
||||
:favourites_count, :edited_at
|
||||
|
||||
attribute :favourited, if: :current_user?
|
||||
attribute :reblogged, if: :current_user?
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class REST::StatusSourceSerializer < ActiveModel::Serializer
|
||||
attributes :id, :text, :spoiler_text
|
||||
|
||||
def id
|
||||
object.id.to_s
|
||||
end
|
||||
end
|
|
@ -8,6 +8,6 @@ class ActivityPub::FetchRemotePollService < BaseService
|
|||
|
||||
return unless supported_context?(json)
|
||||
|
||||
ActivityPub::ProcessPollService.new.call(poll, json)
|
||||
ActivityPub::ProcessStatusUpdateService.new.call(poll.status, json)
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,64 +0,0 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::ProcessPollService < BaseService
|
||||
include JsonLdHelper
|
||||
|
||||
def call(poll, json)
|
||||
@json = json
|
||||
|
||||
return unless expected_type?
|
||||
|
||||
previous_expires_at = poll.expires_at
|
||||
|
||||
expires_at = begin
|
||||
if @json['closed'].is_a?(String)
|
||||
@json['closed']
|
||||
elsif !@json['closed'].nil? && !@json['closed'].is_a?(FalseClass)
|
||||
Time.now.utc
|
||||
else
|
||||
@json['endTime']
|
||||
end
|
||||
end
|
||||
|
||||
items = begin
|
||||
if @json['anyOf'].is_a?(Array)
|
||||
@json['anyOf']
|
||||
else
|
||||
@json['oneOf']
|
||||
end
|
||||
end
|
||||
|
||||
voters_count = @json['votersCount']
|
||||
|
||||
latest_options = items.filter_map { |item| item['name'].presence || item['content'] }
|
||||
|
||||
# If for some reasons the options were changed, it invalidates all previous
|
||||
# votes, so we need to remove them
|
||||
poll.votes.delete_all if latest_options != poll.options
|
||||
|
||||
begin
|
||||
poll.update!(
|
||||
last_fetched_at: Time.now.utc,
|
||||
expires_at: expires_at,
|
||||
options: latest_options,
|
||||
cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 },
|
||||
voters_count: voters_count
|
||||
)
|
||||
rescue ActiveRecord::StaleObjectError
|
||||
poll.reload
|
||||
retry
|
||||
end
|
||||
|
||||
# If the poll had no expiration date set but now has, and people have voted,
|
||||
# schedule a notification.
|
||||
if previous_expires_at.nil? && poll.expires_at.present? && poll.votes.exists?
|
||||
PollExpirationNotifyWorker.perform_at(poll.expires_at + 5.minutes, poll.id)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def expected_type?
|
||||
equals_or_includes_any?(@json['type'], %w(Question))
|
||||
end
|
||||
end
|
|
@ -0,0 +1,275 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::ProcessStatusUpdateService < BaseService
|
||||
include JsonLdHelper
|
||||
|
||||
def call(status, json)
|
||||
@json = json
|
||||
@status_parser = ActivityPub::Parser::StatusParser.new(@json)
|
||||
@uri = @status_parser.uri
|
||||
@status = status
|
||||
@account = status.account
|
||||
@media_attachments_changed = false
|
||||
|
||||
# Only native types can be updated at the moment
|
||||
return if !expected_type? || already_updated_more_recently?
|
||||
|
||||
# Only allow processing one create/update per status at a time
|
||||
RedisLock.acquire(lock_options) do |lock|
|
||||
if lock.acquired?
|
||||
Status.transaction do
|
||||
create_previous_edit!
|
||||
update_media_attachments!
|
||||
update_poll!
|
||||
update_immediate_attributes!
|
||||
update_metadata!
|
||||
create_edit!
|
||||
end
|
||||
|
||||
queue_poll_notifications!
|
||||
reset_preview_card!
|
||||
broadcast_updates!
|
||||
else
|
||||
raise Mastodon::RaceConditionError
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def update_media_attachments!
|
||||
previous_media_attachments = @status.media_attachments.to_a
|
||||