Merge upstream (#81)
commit
f48f42598f
@ -0,0 +1,28 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::OutboxesController < Api::BaseController
|
||||
before_action :set_account
|
||||
|
||||
def show
|
||||
@statuses = @account.statuses.permitted_for(@account, current_account).paginate_by_max_id(20, params[:max_id], params[:since_id])
|
||||
@statuses = cache_collection(@statuses, Status)
|
||||
|
||||
render json: outbox_presenter, serializer: ActivityPub::CollectionSerializer, adapter: ActivityPub::Adapter
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_account
|
||||
@account = Account.find_local!(params[:account_username])
|
||||
end
|
||||
|
||||
def outbox_presenter
|
||||
ActivityPub::CollectionPresenter.new(
|
||||
id: account_outbox_url(@account),
|
||||
type: :ordered,
|
||||
current: account_outbox_url(@account),
|
||||
size: @account.statuses_count,
|
||||
items: @statuses
|
||||
)
|
||||
end
|
||||
end
|
@ -1,27 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Api::ActivityPub::ActivitiesController < Api::BaseController
|
||||
include Authorization
|
||||
|
||||
# before_action :set_follow, only: [:show_follow]
|
||||
before_action :set_status, only: [:show_status]
|
||||
|
||||
respond_to :activitystreams2
|
||||
|
||||
# Show a status in AS2 format, as either an Announce (reblog) or a Create (post) activity.
|
||||
def show_status
|
||||
authorize @status, :show?
|
||||
|
||||
if @status.reblog?
|
||||
render :show_status_announce
|
||||
else
|
||||
render :show_status_create
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_status
|
||||
@status = Status.find(params[:id])
|
||||
end
|
||||
end
|
@ -1,19 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Api::ActivityPub::NotesController < Api::BaseController
|
||||
include Authorization
|
||||
|
||||
before_action :set_status
|
||||
|
||||
respond_to :activitystreams2
|
||||
|
||||
def show
|
||||
authorize @status, :show?
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_status
|
||||
@status = Status.find(params[:id])
|
||||
end
|
||||
end
|
@ -1,69 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Api::ActivityPub::OutboxController < Api::BaseController
|
||||
before_action :set_account
|
||||
|
||||
respond_to :activitystreams2
|
||||
|
||||
def show
|
||||
if params[:max_id] || params[:since_id]
|
||||
show_outbox_page
|
||||
else
|
||||
show_base_outbox
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def show_base_outbox
|
||||
@statuses = Status.as_outbox_timeline(@account)
|
||||
@statuses = cache_collection(@statuses)
|
||||
|
||||
set_maps(@statuses)
|
||||
|
||||
set_first_last_page(@statuses)
|
||||
|
||||
render :show
|
||||
end
|
||||
|
||||
def show_outbox_page
|
||||
all_statuses = Status.as_outbox_timeline(@account)
|
||||
@statuses = all_statuses.paginate_by_max_id(limit_param(DEFAULT_STATUSES_LIMIT), params[:max_id], params[:since_id])
|
||||
|
||||
all_statuses = cache_collection(all_statuses)
|
||||
@statuses = cache_collection(@statuses)
|
||||
|
||||
set_maps(@statuses)
|
||||
|
||||
set_first_last_page(all_statuses)
|
||||
|
||||
@next_page_url = api_activitypub_outbox_url(pagination_params(max_id: @statuses.last.id)) unless @statuses.empty?
|
||||
@prev_page_url = api_activitypub_outbox_url(pagination_params(since_id: @statuses.first.id)) unless @statuses.empty?
|
||||
|
||||
@paginated = @next_page_url || @prev_page_url
|
||||
@part_of_url = api_activitypub_outbox_url
|
||||
|
||||
set_pagination_headers(@next_page_url, @prev_page_url)
|
||||
|
||||
render :show_page
|
||||
end
|
||||
|
||||
def cache_collection(raw)
|
||||
super(raw, Status)
|
||||
end
|
||||
|
||||
def set_account
|
||||
@account = Account.find(params[:id])
|
||||
end
|
||||
|
||||
def set_first_last_page(statuses) # rubocop:disable Style/AccessorMethodName
|
||||
return if statuses.empty?
|
||||
|
||||
@first_page_url = api_activitypub_outbox_url(max_id: statuses.first.id + 1)
|
||||
@last_page_url = api_activitypub_outbox_url(since_id: statuses.last.id - 1)
|
||||
end
|
||||
|
||||
def pagination_params(core_params)
|
||||
params.permit(:local, :limit).merge(core_params)
|
||||
end
|
||||
end
|
@ -0,0 +1,39 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Api::Web::PushSubscriptionsController < Api::BaseController
|
||||
respond_to :json
|
||||
|
||||
before_action :require_user!
|
||||
|
||||
def create
|
||||
params.require(:data).require(:endpoint)
|
||||
params.require(:data).require(:keys).require([:auth, :p256dh])
|
||||
|
||||
active_session = current_session
|
||||
|
||||
unless active_session.web_push_subscription.nil?
|
||||
active_session.web_push_subscription.destroy!
|
||||
active_session.update!(web_push_subscription: nil)
|
||||
end
|
||||
|
||||
web_subscription = ::Web::PushSubscription.create!(
|
||||
endpoint: params[:data][:endpoint],
|
||||
key_p256dh: params[:data][:keys][:p256dh],
|
||||
key_auth: params[:data][:keys][:auth]
|
||||
)
|
||||
|
||||
active_session.update!(web_push_subscription: web_subscription)
|
||||
|
||||
render json: web_subscription.as_payload
|
||||
end
|
||||
|
||||
def update
|
||||
params.require([:id, :data])
|
||||
|
||||
web_subscription = ::Web::PushSubscription.find(params[:id])
|
||||
|
||||
web_subscription.update!(data: params[:data])
|
||||
|
||||
render json: web_subscription.as_payload
|
||||
end
|
||||
end
|
@ -0,0 +1,87 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# Implemented according to HTTP signatures (Draft 6)
|
||||
# <https://tools.ietf.org/html/draft-cavage-http-signatures-06>
|
||||
module SignatureVerification
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
def signed_request?
|
||||
request.headers['Signature'].present?
|
||||
end
|
||||
|
||||
def signed_request_account
|
||||
return @signed_request_account if defined?(@signed_request_account)
|
||||
|
||||
unless signed_request?
|
||||
@signed_request_account = nil
|
||||
return
|
||||
end
|
||||
|
||||
raw_signature = request.headers['Signature']
|
||||
signature_params = {}
|
||||
|
||||
raw_signature.split(',').each do |part|
|
||||
parsed_parts = part.match(/([a-z]+)="([^"]+)"/i)
|
||||
next if parsed_parts.nil? || parsed_parts.size != 3
|
||||
signature_params[parsed_parts[1]] = parsed_parts[2]
|
||||
end
|
||||
|
||||
if incompatible_signature?(signature_params)
|
||||
@signed_request_account = nil
|
||||
return
|
||||
end
|
||||
|
||||
account = ResolveRemoteAccountService.new.call(signature_params['keyId'].gsub(/\Aacct:/, ''))
|
||||
|
||||
if account.nil?
|
||||
@signed_request_account = nil
|
||||
return
|
||||
end
|
||||
|
||||
signature = Base64.decode64(signature_params['signature'])
|
||||
compare_signed_string = build_signed_string(signature_params['headers'])
|
||||
|
||||
if account.keypair.public_key.verify(OpenSSL::Digest::SHA256.new, signature, compare_signed_string)
|
||||
@signed_request_account = account
|
||||
@signed_request_account
|
||||
else
|
||||
@signed_request_account = nil
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_signed_string(signed_headers)
|
||||
signed_headers = 'date' if signed_headers.blank?
|
||||
|
||||
signed_headers.split(' ').map do |signed_header|
|
||||
if signed_header == Request::REQUEST_TARGET
|
||||
"#{Request::REQUEST_TARGET}: #{request.method.downcase} #{request.path}"
|
||||
else
|
||||
"#{signed_header}: #{request.headers[to_header_name(signed_header)]}"
|
||||
end
|
||||
end.join("\n")
|
||||
end
|
||||
|
||||
def matches_time_window?
|
||||
begin
|
||||
time_sent = DateTime.httpdate(request.headers['Date'])
|
||||
rescue ArgumentError
|
||||
return false
|
||||
end
|
||||
|
||||
(Time.now.utc - time_sent).abs <= 30
|
||||
end
|
||||
|
||||
def to_header_name(name)
|
||||
name.split(/-/).map(&:capitalize).join('-')
|
||||
end
|
||||
|
||||
def incompatible_signature?(signature_params)
|
||||
signature_params['keyId'].blank? ||
|
||||
signature_params['signature'].blank? ||
|
||||
signature_params['algorithm'].blank? ||
|
||||
signature_params['algorithm'] != 'rsa-sha256' ||
|
||||
!signature_params['keyId'].start_with?('acct:')
|
||||
end
|
||||
end
|
@ -1,8 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Activitystreams2BuilderHelper
|
||||
# Gets a usable name for an account, using display name or username.
|
||||
def account_name(account)
|
||||
account.display_name.presence || account.username
|
||||
end
|
||||
end
|
@ -0,0 +1,19 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module EmojiHelper
|
||||
EMOJI_PATTERN = /(?<=[^[:alnum:]:]|\n|^):([\w+-]+):(?=[^[:alnum:]:]|$)/x
|
||||
|
||||
def emojify(text)
|
||||
return text if text.blank?
|
||||
|
||||
text.gsub(EMOJI_PATTERN) do |match|
|
||||
emoji = Emoji.find_by_alias($1) # rubocop:disable Rails/DynamicFindBy,Style/PerlBackrefs
|
||||
|
||||
if emoji
|
||||
emoji.raw
|
||||
else
|
||||
match
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
@ -1,17 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module HttpHelper
|
||||
def http_client(options = {})
|
||||
timeout = { write: 10, connect: 10, read: 10 }.merge(options)
|
||||
|
||||
HTTP.headers(user_agent: user_agent)
|
||||
.timeout(:per_operation, timeout)
|
||||
.follow
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def user_agent
|
||||
@user_agent ||= "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::Version}; +http://#{Rails.configuration.x.local_domain}/)"
|
||||
end
|
||||
end
|
@ -0,0 +1,52 @@
|
||||
import axios from 'axios';
|
||||
|
||||
export const SET_BROWSER_SUPPORT = 'PUSH_NOTIFICATIONS_SET_BROWSER_SUPPORT';
|
||||
export const SET_SUBSCRIPTION = 'PUSH_NOTIFICATIONS_SET_SUBSCRIPTION';
|
||||
export const CLEAR_SUBSCRIPTION = 'PUSH_NOTIFICATIONS_CLEAR_SUBSCRIPTION';
|
||||
export const ALERTS_CHANGE = 'PUSH_NOTIFICATIONS_ALERTS_CHANGE';
|
||||
|
||||
export function setBrowserSupport (value) {
|
||||
return {
|
||||
type: SET_BROWSER_SUPPORT,
|
||||
value,
|
||||
};
|
||||
}
|
||||
|
||||
export function setSubscription (subscription) {
|
||||
return {
|
||||
type: SET_SUBSCRIPTION,
|
||||
subscription,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearSubscription () {
|
||||
return {
|
||||
type: CLEAR_SUBSCRIPTION,
|
||||
};
|
||||
}
|
||||
|
||||
export function changeAlerts(key, value) {
|
||||
return dispatch => {
|
||||
dispatch({
|
||||
type: ALERTS_CHANGE,
|
||||
key,
|
||||
value,
|
||||
});
|
||||
|
||||
dispatch(saveSettings());
|
||||
};
|
||||
}
|
||||
|
||||
export function saveSettings() {
|
||||
return (_, getState) => {
|
||||
const state = getState().get('push_notifications');
|
||||
const subscription = state.get('subscription');
|
||||
const alerts = state.get('alerts');
|
||||
|
||||
axios.put(`/api/web/push_subscriptions/${subscription.get('id')}`, {
|
||||
data: {
|
||||
alerts,
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
// @preval
|
||||
// Force tree shaking on emojione by exposing just a subset of its functionality
|
||||
|
||||
const emojione = require('emojione');
|
||||
|
||||
const mappedUnicode = emojione.mapUnicodeToShort();
|
||||
|
||||
module.exports.unicodeToFilename = Object.keys(emojione.jsEscapeMap)
|
||||
.map(unicodeStr => [unicodeStr, mappedUnicode[emojione.jsEscapeMap[unicodeStr]]])
|
||||
.map(([unicodeStr, shortCode]) => ({ [unicodeStr]: emojione.emojioneList[shortCode].fname }))
|
||||
.reduce((x, y) => Object.assign(x, y), { });
|
@ -1,2 +1,5 @@
|
||||
import 'intersection-observer';
|
||||
import 'requestidlecallback';
|
||||
import objectFitImages from 'object-fit-images';
|
||||
|
||||
objectFitImages();
|
||||
|
@ -0,0 +1,7 @@
|
||||
export default function ready(loaded) {
|
||||
if (['interactive', 'complete'].includes(document.readyState)) {
|
||||
loaded();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', loaded);
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
import { STORE_HYDRATE } from '../actions/store';
|
||||
import { SET_BROWSER_SUPPORT, SET_SUBSCRIPTION, CLEAR_SUBSCRIPTION, ALERTS_CHANGE } from '../actions/push_notifications';
|
||||
import Immutable from 'immutable';
|
||||
|
||||
const initialState = Immutable.Map({
|
||||
subscription: null,
|
||||
alerts: new Immutable.Map({
|
||||
follow: false,
|
||||
favourite: false,
|
||||
reblog: false,
|
||||
mention: false,
|
||||
}),
|
||||
isSubscribed: false,
|
||||
browserSupport: false,
|
||||
});
|
||||
|
||||
export default function push_subscriptions(state = initialState, action) {
|
||||
switch(action.type) {
|
||||
case STORE_HYDRATE: {
|
||||
const push_subscription = action.state.get('push_subscription');
|
||||
|
||||
if (push_subscription) {
|
||||
return state
|
||||
.set('subscription', new Immutable.Map({
|
||||
id: push_subscription.get('id'),
|
||||
endpoint: push_subscription.get('endpoint'),
|
||||
}))
|
||||
.set('alerts', push_subscription.get('alerts') || initialState.get('alerts'))
|
||||
.set('isSubscribed', true);
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
case SET_SUBSCRIPTION:
|
||||
return state
|
||||
.set('subscription', new Immutable.Map({
|
||||
id: action.subscription.id,
|
||||
endpoint: action.subscription.endpoint,
|
||||
}))
|
||||
.set('alerts', new Immutable.Map(action.subscription.alerts))
|
||||
.set('isSubscribed', true);
|
||||
case SET_BROWSER_SUPPORT:
|
||||
return state.set('browserSupport', action.value);
|
||||
case CLEAR_SUBSCRIPTION:
|
||||
return initialState;
|
||||
case ALERTS_CHANGE:
|
||||
return state.setIn(action.key, action.value);
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
@ -0,0 +1 @@
|
||||
import './web_push_notifications';
|
@ -0,0 +1,86 @@
|
||||
const handlePush = (event) => {
|
||||
const options = event.data.json();
|
||||
|
||||
options.body = options.data.nsfw || options.data.content;
|
||||
options.image = options.image || undefined; // Null results in a network request (404)
|
||||
options.timestamp = options.timestamp && new Date(options.timestamp);
|
||||
|
||||
const expandAction = options.data.actions.find(action => action.todo === 'expand');
|
||||
|
||||
if (expandAction) {
|
||||
options.actions = [expandAction];
|
||||
options.hiddenActions = options.data.actions.filter(action => action !== expandAction);
|
||||
|
||||
options.data.hiddenImage = options.image;
|
||||
options.image = undefined;
|
||||
} else {
|
||||
options.actions = options.data.actions;
|
||||
}
|
||||
|
||||
event.waitUntil(self.registration.showNotification(options.title, options));
|
||||
};
|
||||
|
||||
const cloneNotification = (notification) => {
|
||||
const clone = { };
|
||||
|
||||
for(var k in notification) {
|
||||
clone[k] = notification[k];
|
||||
}
|
||||
|
||||
return clone;
|
||||
};
|
||||
|
||||
const expandNotification = (notification) => {
|
||||
const nextNotification = cloneNotification(notification);
|
||||
|
||||
nextNotification.body = notification.data.content;
|
||||
nextNotification.image = notification.data.hiddenImage;
|
||||
nextNotification.actions = notification.data.actions.filter(action => action.todo !== 'expand');
|
||||
|
||||
return self.registration.showNotification(nextNotification.title, nextNotification);
|
||||
};
|
||||
|
||||
const makeRequest = (notification, action) =>
|
||||
fetch(action.action, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${notification.data.access_token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
method: action.method,
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
const removeActionFromNotification = (notification, action) => {
|
||||
const actions = notification.actions.filter(act => act.action !== action.action);
|
||||
|
||||
const nextNotification = cloneNotification(notification);
|
||||
|
||||
nextNotification.actions = actions;
|
||||
|
||||
return self.registration.showNotification(nextNotification.title, nextNotification);
|
||||
};
|
||||
|
||||
const handleNotificationClick = (event) => {
|
||||
const reactToNotificationClick = new Promise((resolve, reject) => {
|
||||
if (event.action) {
|
||||
const action = event.notification.data.actions.find(({ action }) => action === event.action);
|
||||
|
||||
if (action.todo === 'expand') {
|
||||
resolve(expandNotification(event.notification));
|
||||
} else if (action.todo === 'request') {
|
||||
resolve(makeRequest(event.notification, action)
|
||||
.then(() => removeActionFromNotification(event.notification, action)));
|
||||
} else {
|
||||
reject(`Unknown action: ${action.todo}`);
|
||||
}
|
||||
} else {
|
||||
event.notification.close();
|
||||
resolve(self.clients.openWindow(event.notification.data.url));
|
||||
}
|
||||
});
|
||||
|
||||
event.waitUntil(reactToNotificationClick);
|
||||
};
|
||||
|
||||
self.addEventListener('push', handlePush);
|
||||
self.addEventListener('notificationclick', handleNotificationClick);
|
@ -0,0 +1,109 @@
|
||||
import axios from 'axios';
|
||||
import { store } from './containers/mastodon';
|
||||
import { setBrowserSupport, setSubscription, clearSubscription } from './actions/push_notifications';
|
||||
|
||||
// Taken from https://www.npmjs.com/package/web-push
|
||||
const urlBase64ToUint8Array = (base64String) => {
|
||||
const padding = '='.repeat((4 - base64String.length % 4) % 4);
|
||||
const base64 = (base64String + padding)
|
||||
.replace(/\-/g, '+')
|
||||
.replace(/_/g, '/');
|
||||
|
||||
const rawData = window.atob(base64);
|
||||
const outputArray = new Uint8Array(rawData.length);
|
||||
|
||||
for (let i = 0; i < rawData.length; ++i) {
|
||||
outputArray[i] = rawData.charCodeAt(i);
|
||||
}
|
||||
return outputArray;
|
||||
};
|
||||
|
||||
const getApplicationServerKey = () => document.querySelector('[name="applicationServerKey"]').getAttribute('content');
|
||||
|
||||
const getRegistration = () => navigator.serviceWorker.ready;
|
||||
|
||||
const getPushSubscription = (registration) =>
|
||||
registration.pushManager.getSubscription()
|
||||
.then(subscription => ({ registration, subscription }));
|
||||
|
||||
const subscribe = (registration) =>
|
||||
registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(getApplicationServerKey()),
|
||||
});
|
||||
|
||||
const unsubscribe = ({ registration, subscription }) =>
|
||||
subscription ? subscription.unsubscribe().then(() => registration) : registration;
|
||||
|
||||
const sendSubscriptionToBackend = (subscription) =>
|
||||
axios.post('/api/web/push_subscriptions', {
|
||||
data: subscription,
|
||||
}).then(response => response.data);
|
||||
|
||||
// Last one checks for payload support: https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/#no-payload
|
||||
const supportsPushNotifications = ('serviceWorker' in navigator && 'PushManager' in window && 'getKey' in PushSubscription.prototype);
|
||||
|
||||
export function register () {
|
||||
store.dispatch(setBrowserSupport(supportsPushNotifications));
|
||||
|
||||
if (supportsPushNotifications) {
|
||||
if (!getApplicationServerKey()) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('The VAPID public key is not set. You will not be able to receive Web Push Notifications.');
|
||||
return;
|
||||
}
|
||||
|
||||
getRegistration()
|
||||
.then(getPushSubscription)
|
||||
.then(({ registration, subscription }) => {
|
||||
if (subscription !== null) {
|
||||
// We have a subscription, check if it is still valid
|
||||
const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey)).toString();
|
||||
const subscriptionServerKey = urlBase64ToUint8Array(getApplicationServerKey()).toString();
|
||||
const serverEndpoint = store.getState().getIn(['push_notifications', 'subscription', 'endpoint']);
|
||||
|
||||
// If the VAPID public key did not change and the endpoint corresponds
|
||||
// to the endpoint saved in the backend, the subscription is valid
|
||||
if (subscriptionServerKey === currentServerKey && subscription.endpoint === serverEndpoint) {
|
||||
return subscription;
|
||||
} else {
|
||||
// Something went wrong, try to subscribe again
|
||||
return unsubscribe({ registration, subscription }).then(subscribe).then(sendSubscriptionToBackend);
|
||||
}
|
||||
}
|
||||
|
||||
// No subscription, try to subscribe
|
||||
return subscribe(registration).then(sendSubscriptionToBackend);
|
||||
})
|
||||
.then(subscription => {
|
||||
// If we got a PushSubscription (and not a subscription object from the backend)
|
||||
// it means that the backend subscription is valid (and was set during hydration)
|
||||
if (!(subscription instanceof PushSubscription)) {
|
||||
store.dispatch(setSubscription(subscription));
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (error.code === 20 && error.name === 'AbortError') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('Your browser supports Web Push Notifications, but does not seem to implement the VAPID protocol.');
|
||||
} else if (error.code === 5 && error.name === 'InvalidCharacterError') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('The VAPID public key seems to be invalid:', getApplicationServerKey());
|
||||
}
|
||||
|
||||
// Clear alerts and hide UI settings
|
||||
store.dispatch(clearSubscription());
|
||||
|
||||
try {
|
||||
getRegistration()
|
||||
.then(getPushSubscription)
|
||||
.then(unsubscribe);
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('Your browser does not support Web Push Notifications.');
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
import TimelineContainer from '../mastodon/containers/timeline_container';
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import loadPolyfills from '../mastodon/load_polyfills';
|
||||
import ready from '../mastodon/ready';
|
||||
|
||||
require.context('../images/', true);
|
||||
|
||||
function loaded() {
|
||||
const mountNode = document.getElementById('mastodon-timeline');
|
||||
|
||||
if (mountNode !== null) {
|
||||
const props = JSON.parse(mountNode.getAttribute('data-props'));
|
||||
ReactDOM.render(<TimelineContainer {...props} />, mountNode);
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
ready(loaded);
|
||||
}
|
||||
|
||||
loadPolyfills().then(main).catch(error => {
|
||||
console.error(error);
|
||||
});
|
@ -0,0 +1,13 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class ActivityPub::Adapter < ActiveModelSerializers::Adapter::Base
|
||||
def self.default_key_transform
|
||||
:camel_lower
|
||||
end
|
||||
|
||||
def serializable_hash(options = nil)
|
||||
options = serialization_options(options)
|
||||
serialized_hash = { '@context': 'https://www.w3.org/ns/activitystreams' }.merge(ActiveModelSerializers::Adapter::Attributes.new(serializer, instance_options).serializable_hash(options))
|
||||
self.class.transform_key_casing!(serialized_hash, instance_options)
|
||||
end
|
||||
end
|
@ -0,0 +1,69 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'singleton'
|
||||
|
||||
class ActivityPub::TagManager
|
||||
include Singleton
|
||||
include RoutingHelper
|
||||
|
||||
COLLECTIONS = {
|
||||
public: 'https://www.w3.org/ns/activitystreams#Public',
|
||||
}.freeze
|
||||
|
||||
def url_for(target)
|
||||
return target.url if target.respond_to?(:local?) && !target.local?
|
||||
|
||||
case target.object_type
|
||||
when :person
|
||||
short_account_url(target)
|
||||
when :note, :comment, :activity
|
||||
short_account_status_url(target.account, target)
|
||||
end
|
||||
end
|
||||
|
||||
def uri_for(target)
|
||||
return target.uri if target.respond_to?(:local?) && !target.local?
|
||||
|
||||
case target.object_type
|
||||
when :person
|
||||
account_url(target)
|
||||
when :note, :comment, :activity
|
||||
account_status_url(target.account, target)
|
||||
end
|
||||
end
|
||||
|
||||
# Primary audience of a status
|
||||
# Public statuses go out to primarily the public collection
|
||||
# Unlisted and private statuses go out primarily to the followers collection
|
||||
# Others go out only to the people they mention
|
||||
def to(status)
|
||||
case status.visibility
|
||||
when 'public'
|
||||
[COLLECTIONS[:public]]
|
||||
when 'unlisted', 'private'
|
||||
[account_followers_url(status.account)]
|
||||
when 'direct'
|
||||
status.mentions.map { |mention| uri_for(mention.account) }
|
||||
end
|
||||
end
|
||||
|
||||
# Secondary audience of a status
|
||||
# Public statuses go out to followers as well
|
||||
# Unlisted statuses go to the public as well
|
||||
# Both of those and private statuses also go to the people mentioned in them
|
||||
# Direct ones don't have a secondary audience
|
||||
def cc(status)
|
||||
cc = []
|
||||
|
||||
case status.visibility
|
||||
when 'public'
|
||||
cc << account_followers_url(status.account)
|
||||
when 'unlisted'
|
||||
cc << COLLECTIONS[:public]
|
||||
end
|
||||
|
||||
cc.concat(status.mentions.map { |mention| uri_for(mention.account) }) unless status.direct_visibility?
|
||||
|
||||
cc
|
||||
end
|
||||
end
|
@ -0,0 +1,70 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class Request
|
||||
REQUEST_TARGET = '(request-target)'
|
||||
|
||||
include RoutingHelper
|
||||
|
||||
def initialize(verb, url, options = {})
|
||||
@verb = verb
|
||||
@url = Addressable::URI.parse(url).normalize
|
||||
@options = options
|
||||
@headers = {}
|
||||
|
||||
set_common_headers!
|
||||
end
|
||||
|
||||
def on_behalf_of(account)
|
||||
raise ArgumentError unless account.local?
|
||||
@account = account
|
||||
end
|
||||
|
||||
def add_headers(new_headers)
|
||||
@headers.merge!(new_headers)
|
||||
end
|
||||
|
||||
def perform
|
||||
http_client.headers(headers).public_send(@verb, @url.to_s, @options)
|
||||
end
|
||||
|
||||
def headers
|
||||
(@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_common_headers!
|
||||
@headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
|
||||
@headers['User-Agent'] = user_agent
|
||||
@headers['Host'] = @url.host
|
||||
@headers['Date'] = Time.now.utc.httpdate
|
||||
end
|
||||
|
||||
def signature
|
||||
key_id = @account.to_webfinger_s
|
||||
algorithm = 'rsa-sha256'
|
||||
signature = Base64.strict_encode64(@account.keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
|
||||
|
||||
"keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers}\",signature=\"#{signature}\""
|
||||
end
|
||||
|
||||
def signed_string
|
||||
@headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
|
||||
end
|
||||
|
||||
def signed_headers
|
||||
@headers.keys.join(' ').downcase
|
||||
end
|
||||
|
||||
def user_agent
|
||||
@user_agent ||= "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::Version}; +#{root_url})"
|
||||
end
|
||||
|
||||
def timeout
|
||||
{ write: 10, connect: 10, read: 10 }
|
||||
end
|
||||
|
||||
def http_client
|
||||
HTTP.timeout(:per_operation, timeout).follow
|
||||
end
|
||||
end
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue