From e8b42d7e1668679e6a6ee0a7aea1e2ff7f37005b Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 4 Apr 2018 23:12:35 +0900 Subject: [PATCH 01/68] wip --- src/post/create.ts | 107 +++++++++++- src/processor/http/deliver-post.ts | 93 ----------- src/processor/http/process-inbox.ts | 39 ----- src/queue.ts | 10 -- src/queue/index.ts | 37 ++++ .../processors}/db/delete-post-dependents.ts | 0 .../processors}/db/index.ts | 0 src/queue/processors/http/deliver.ts | 17 ++ .../processors}/http/follow.ts | 0 .../processors}/http/index.ts | 0 .../processors}/http/perform-activitypub.ts | 0 src/queue/processors/http/process-inbox.ts | 55 ++++++ .../processors}/http/report-github-failure.ts | 0 .../processors}/http/unfollow.ts | 0 src/{processor => queue/processors}/index.ts | 0 src/remote/activitypub/act/create.ts | 92 +++++++++- src/remote/activitypub/act/index.ts | 44 +++-- src/remote/activitypub/create.ts | 158 ------------------ src/remote/activitypub/resolver.ts | 77 ++++----- src/server/activitypub/inbox.ts | 2 +- 20 files changed, 354 insertions(+), 377 deletions(-) delete mode 100644 src/processor/http/deliver-post.ts delete mode 100644 src/processor/http/process-inbox.ts delete mode 100644 src/queue.ts create mode 100644 src/queue/index.ts rename src/{processor => queue/processors}/db/delete-post-dependents.ts (100%) rename src/{processor => queue/processors}/db/index.ts (100%) create mode 100644 src/queue/processors/http/deliver.ts rename src/{processor => queue/processors}/http/follow.ts (100%) rename src/{processor => queue/processors}/http/index.ts (100%) rename src/{processor => queue/processors}/http/perform-activitypub.ts (100%) create mode 100644 src/queue/processors/http/process-inbox.ts rename src/{processor => queue/processors}/http/report-github-failure.ts (100%) rename src/{processor => queue/processors}/http/unfollow.ts (100%) rename src/{processor => queue/processors}/index.ts (100%) delete mode 100644 src/remote/activitypub/create.ts diff --git a/src/post/create.ts b/src/post/create.ts index ecea37382d..f78bbe7521 100644 --- a/src/post/create.ts +++ b/src/post/create.ts @@ -1,8 +1,14 @@ import parseAcct from '../acct/parse'; -import Post from '../models/post'; -import User from '../models/user'; +import Post, { pack } from '../models/post'; +import User, { isLocalUser, isRemoteUser, IUser } from '../models/user'; +import stream from '../publishers/stream'; +import Following from '../models/following'; +import { createHttp } from '../queue'; +import renderNote from '../remote/activitypub/renderer/note'; +import renderCreate from '../remote/activitypub/renderer/create'; +import context from '../remote/activitypub/renderer/context'; -export default async (post, reply, repost, atMentions) => { +export default async (user: IUser, post, reply, repost, atMentions) => { post.mentions = []; function addMention(mentionee) { @@ -46,5 +52,98 @@ export default async (post, reply, repost, atMentions) => { addMention(_id); })); - return Post.insert(post); + const inserted = await Post.insert(post); + + User.update({ _id: user._id }, { + // Increment my posts count + $inc: { + postsCount: 1 + }, + + $set: { + latestPost: post._id + } + }); + + const postObj = await pack(inserted); + + // タイムラインへの投稿 + if (!post.channelId) { + // Publish event to myself's stream + stream(post.userId, 'post', postObj); + + // Fetch all followers + const followers = await Following.aggregate([{ + $lookup: { + from: 'users', + localField: 'followerId', + foreignField: '_id', + as: 'follower' + } + }, { + $match: { + followeeId: post.userId + } + }], { + _id: false + }); + + const note = await renderNote(user, post); + const content = renderCreate(note); + content['@context'] = context; + + Promise.all(followers.map(({ follower }) => { + if (isLocalUser(follower)) { + // Publish event to followers stream + stream(follower._id, 'post', postObj); + } else { + // フォロワーがリモートユーザーかつ投稿者がローカルユーザーなら投稿を配信 + if (isLocalUser(user)) { + createHttp({ + type: 'deliver', + user, + content, + to: follower.account.inbox + }).save(); + } + } + })); + } + + // チャンネルへの投稿 + /* TODO + if (post.channelId) { + promises.push( + // Increment channel index(posts count) + Channel.update({ _id: post.channelId }, { + $inc: { + index: 1 + } + }), + + // Publish event to channel + promisedPostObj.then(postObj => { + publishChannelStream(post.channelId, 'post', postObj); + }), + + Promise.all([ + promisedPostObj, + + // Get channel watchers + ChannelWatching.find({ + channelId: post.channelId, + // 削除されたドキュメントは除く + deletedAt: { $exists: false } + }) + ]).then(([postObj, watches]) => { + // チャンネルの視聴者(のタイムライン)に配信 + watches.forEach(w => { + stream(w.userId, 'post', postObj); + }); + }) + ); + }*/ + + return Promise.all(promises); + }; diff --git a/src/processor/http/deliver-post.ts b/src/processor/http/deliver-post.ts deleted file mode 100644 index c00ab912c9..0000000000 --- a/src/processor/http/deliver-post.ts +++ /dev/null @@ -1,93 +0,0 @@ -import Channel from '../../models/channel'; -import Following from '../../models/following'; -import ChannelWatching from '../../models/channel-watching'; -import Post, { pack } from '../../models/post'; -import User, { isLocalUser } from '../../models/user'; -import stream, { publishChannelStream } from '../../publishers/stream'; -import context from '../../remote/activitypub/renderer/context'; -import renderCreate from '../../remote/activitypub/renderer/create'; -import renderNote from '../../remote/activitypub/renderer/note'; -import request from '../../remote/request'; - -export default ({ data }) => Post.findOne({ _id: data.id }).then(post => { - const promisedPostObj = pack(post); - const promises = []; - - // タイムラインへの投稿 - if (!post.channelId) { - promises.push( - // Publish event to myself's stream - promisedPostObj.then(postObj => { - stream(post.userId, 'post', postObj); - }), - - Promise.all([ - User.findOne({ _id: post.userId }), - - // Fetch all followers - Following.aggregate([{ - $lookup: { - from: 'users', - localField: 'followerId', - foreignField: '_id', - as: 'follower' - } - }, { - $match: { - followeeId: post.userId - } - }], { - _id: false - }) - ]).then(([user, followers]) => Promise.all(followers.map(following => { - if (isLocalUser(following.follower)) { - // Publish event to followers stream - return promisedPostObj.then(postObj => { - stream(following.followerId, 'post', postObj); - }); - } - - return renderNote(user, post).then(note => { - const create = renderCreate(note); - create['@context'] = context; - return request(user, following.follower[0].account.inbox, create); - }); - }))) - ); - } - - // チャンネルへの投稿 - if (post.channelId) { - promises.push( - // Increment channel index(posts count) - Channel.update({ _id: post.channelId }, { - $inc: { - index: 1 - } - }), - - // Publish event to channel - promisedPostObj.then(postObj => { - publishChannelStream(post.channelId, 'post', postObj); - }), - - Promise.all([ - promisedPostObj, - - // Get channel watchers - ChannelWatching.find({ - channelId: post.channelId, - // 削除されたドキュメントは除く - deletedAt: { $exists: false } - }) - ]).then(([postObj, watches]) => { - // チャンネルの視聴者(のタイムライン)に配信 - watches.forEach(w => { - stream(w.userId, 'post', postObj); - }); - }) - ); - } - - return Promise.all(promises); -}); diff --git a/src/processor/http/process-inbox.ts b/src/processor/http/process-inbox.ts deleted file mode 100644 index f102f8d6b4..0000000000 --- a/src/processor/http/process-inbox.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { verifySignature } from 'http-signature'; -import parseAcct from '../../acct/parse'; -import User, { IRemoteUser } from '../../models/user'; -import act from '../../remote/activitypub/act'; -import resolvePerson from '../../remote/activitypub/resolve-person'; -import Resolver from '../../remote/activitypub/resolver'; - -export default async ({ data }): Promise => { - const keyIdLower = data.signature.keyId.toLowerCase(); - let user; - - if (keyIdLower.startsWith('acct:')) { - const { username, host } = parseAcct(keyIdLower.slice('acct:'.length)); - if (host === null) { - throw 'request was made by local user'; - } - - user = await User.findOne({ usernameLower: username, hostLower: host }) as IRemoteUser; - } else { - user = await User.findOne({ - host: { $ne: null }, - 'account.publicKey.id': data.signature.keyId - }) as IRemoteUser; - - if (user === null) { - user = await resolvePerson(data.signature.keyId); - } - } - - if (user === null) { - throw 'failed to resolve user'; - } - - if (!verifySignature(data.signature, user.account.publicKey.publicKeyPem)) { - throw 'signature verification failed'; - } - - await Promise.all(await act(new Resolver(), user, data.inbox, true)); -}; diff --git a/src/queue.ts b/src/queue.ts deleted file mode 100644 index 08ea13c2a3..0000000000 --- a/src/queue.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createQueue } from 'kue'; -import config from './config'; - -export default createQueue({ - redis: { - port: config.redis.port, - host: config.redis.host, - auth: config.redis.pass - } -}); diff --git a/src/queue/index.ts b/src/queue/index.ts new file mode 100644 index 0000000000..c8c436b18c --- /dev/null +++ b/src/queue/index.ts @@ -0,0 +1,37 @@ +import { createQueue } from 'kue'; +import config from '../config'; +import db from './processors/db'; +import http from './processors/http'; + +const queue = createQueue({ + redis: { + port: config.redis.port, + host: config.redis.host, + auth: config.redis.pass + } +}); + +export function createHttp(data) { + return queue + .create('http', data) + .attempts(16) + .backoff({ delay: 16384, type: 'exponential' }); +} + +export function createDb(data) { + return queue.create('db', data); +} + +export function process() { + queue.process('db', db); + + /* + 256 is the default concurrency limit of Mozilla Firefox and Google + Chromium. + a8af215e691f3a2205a3758d2d96e9d328e100ff - chromium/src.git - Git at Google + https://chromium.googlesource.com/chromium/src.git/+/a8af215e691f3a2205a3758d2d96e9d328e100ff + Network.http.max-connections - MozillaZine Knowledge Base + http://kb.mozillazine.org/Network.http.max-connections + */ + queue.process('http', 256, http); +} diff --git a/src/processor/db/delete-post-dependents.ts b/src/queue/processors/db/delete-post-dependents.ts similarity index 100% rename from src/processor/db/delete-post-dependents.ts rename to src/queue/processors/db/delete-post-dependents.ts diff --git a/src/processor/db/index.ts b/src/queue/processors/db/index.ts similarity index 100% rename from src/processor/db/index.ts rename to src/queue/processors/db/index.ts diff --git a/src/queue/processors/http/deliver.ts b/src/queue/processors/http/deliver.ts new file mode 100644 index 0000000000..8cd9eb624e --- /dev/null +++ b/src/queue/processors/http/deliver.ts @@ -0,0 +1,17 @@ +import * as kue from 'kue'; + +import Channel from '../../models/channel'; +import Following from '../../models/following'; +import ChannelWatching from '../../models/channel-watching'; +import Post, { pack } from '../../models/post'; +import User, { isLocalUser } from '../../models/user'; +import stream, { publishChannelStream } from '../../publishers/stream'; +import context from '../../remote/activitypub/renderer/context'; +import renderCreate from '../../remote/activitypub/renderer/create'; +import renderNote from '../../remote/activitypub/renderer/note'; +import request from '../../remote/request'; + +export default async (job: kue.Job, done): Promise => { + + request(user, following.follower[0].account.inbox, create); +} diff --git a/src/processor/http/follow.ts b/src/queue/processors/http/follow.ts similarity index 100% rename from src/processor/http/follow.ts rename to src/queue/processors/http/follow.ts diff --git a/src/processor/http/index.ts b/src/queue/processors/http/index.ts similarity index 100% rename from src/processor/http/index.ts rename to src/queue/processors/http/index.ts diff --git a/src/processor/http/perform-activitypub.ts b/src/queue/processors/http/perform-activitypub.ts similarity index 100% rename from src/processor/http/perform-activitypub.ts rename to src/queue/processors/http/perform-activitypub.ts diff --git a/src/queue/processors/http/process-inbox.ts b/src/queue/processors/http/process-inbox.ts new file mode 100644 index 0000000000..fff1fbf663 --- /dev/null +++ b/src/queue/processors/http/process-inbox.ts @@ -0,0 +1,55 @@ +import * as kue from 'kue'; + +import { verifySignature } from 'http-signature'; +import parseAcct from '../../acct/parse'; +import User, { IRemoteUser } from '../../models/user'; +import act from '../../remote/activitypub/act'; +import resolvePerson from '../../remote/activitypub/resolve-person'; +import Resolver from '../../remote/activitypub/resolver'; + +// ユーザーのinboxにアクティビティが届いた時の処理 +export default async (job: kue.Job, done): Promise => { + const signature = job.data.signature; + const activity = job.data.activity; + + const keyIdLower = signature.keyId.toLowerCase(); + let user; + + if (keyIdLower.startsWith('acct:')) { + const { username, host } = parseAcct(keyIdLower.slice('acct:'.length)); + if (host === null) { + console.warn(`request was made by local user: @${username}`); + done(); + } + + user = await User.findOne({ usernameLower: username, hostLower: host }) as IRemoteUser; + } else { + user = await User.findOne({ + host: { $ne: null }, + 'account.publicKey.id': signature.keyId + }) as IRemoteUser; + + // アクティビティを送信してきたユーザーがまだMisskeyサーバーに登録されていなかったら登録する + if (user === null) { + user = await resolvePerson(signature.keyId); + } + } + + if (user === null) { + done(new Error('failed to resolve user')); + return; + } + + if (!verifySignature(signature, user.account.publicKey.publicKeyPem)) { + done(new Error('signature verification failed')); + return; + } + + // アクティビティを処理 + try { + await act(new Resolver(), user, activity); + done(); + } catch (e) { + done(e); + } +}; diff --git a/src/processor/http/report-github-failure.ts b/src/queue/processors/http/report-github-failure.ts similarity index 100% rename from src/processor/http/report-github-failure.ts rename to src/queue/processors/http/report-github-failure.ts diff --git a/src/processor/http/unfollow.ts b/src/queue/processors/http/unfollow.ts similarity index 100% rename from src/processor/http/unfollow.ts rename to src/queue/processors/http/unfollow.ts diff --git a/src/processor/index.ts b/src/queue/processors/index.ts similarity index 100% rename from src/processor/index.ts rename to src/queue/processors/index.ts diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index fa681982cf..c1a30ce7d0 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -1,10 +1,92 @@ -import create from '../create'; -import Resolver from '../resolver'; +import { JSDOM } from 'jsdom'; +const createDOMPurify = require('dompurify'); -export default (resolver: Resolver, actor, activity, distribute) => { +import Resolver from '../resolver'; +import DriveFile from '../../../models/drive-file'; +import Post from '../../../models/post'; +import uploadFromUrl from '../../../drive/upload-from-url'; +import createPost from '../../../post/create'; + +export default async (resolver: Resolver, actor, activity): Promise => { if ('actor' in activity && actor.account.uri !== activity.actor) { - throw new Error(); + throw new Error('invalid actor'); } - return create(resolver, actor, activity.object, distribute); + const uri = activity.id || activity; + + try { + await Promise.all([ + DriveFile.findOne({ 'metadata.uri': uri }).then(file => { + if (file !== null) { + throw new Error(); + } + }, () => {}), + Post.findOne({ uri }).then(post => { + if (post !== null) { + throw new Error(); + } + }, () => {}) + ]); + } catch (object) { + throw new Error(`already registered: ${uri}`); + } + + const object = await resolver.resolve(activity); + + switch (object.type) { + case 'Image': + createImage(resolver, object); + break; + + case 'Note': + createNote(resolver, object); + break; + } + + /// + + async function createImage(resolver: Resolver, image) { + if ('attributedTo' in image && actor.account.uri !== image.attributedTo) { + throw new Error('invalid image'); + } + + return await uploadFromUrl(image.url, actor); + } + + async function createNote(resolver: Resolver, note) { + if ( + ('attributedTo' in note && actor.account.uri !== note.attributedTo) || + typeof note.id !== 'string' + ) { + throw new Error('invalid note'); + } + + const mediaIds = []; + + if ('attachment' in note) { + note.attachment.forEach(async media => { + const created = await createImage(resolver, media); + mediaIds.push(created._id); + }); + } + + const { window } = new JSDOM(note.content); + + await createPost(actor, { + channelId: undefined, + index: undefined, + createdAt: new Date(note.published), + mediaIds, + replyId: undefined, + repostId: undefined, + poll: undefined, + text: window.document.body.textContent, + textHtml: note.content && createDOMPurify(window).sanitize(note.content), + userId: actor._id, + appId: null, + viaMobile: false, + geo: undefined, + uri: note.id + }, null, null, []); + } }; diff --git a/src/remote/activitypub/act/index.ts b/src/remote/activitypub/act/index.ts index d282e12885..d78335f16e 100644 --- a/src/remote/activitypub/act/index.ts +++ b/src/remote/activitypub/act/index.ts @@ -2,35 +2,29 @@ import create from './create'; import performDeleteActivity from './delete'; import follow from './follow'; import undo from './undo'; -import createObject from '../create'; import Resolver from '../resolver'; +import { IObject } from '../type'; -export default async (parentResolver: Resolver, actor, value, distribute?: boolean) => { - const collection = await parentResolver.resolveCollection(value); +export default async (parentResolver: Resolver, actor, activity: IObject): Promise => { + switch (activity.type) { + case 'Create': + await create(parentResolver, actor, activity); + break; - return collection.object.map(async element => { - const { resolver, object } = await collection.resolver.resolveOne(element); - const created = await (await createObject(resolver, actor, [object], distribute))[0]; + case 'Delete': + await performDeleteActivity(parentResolver, actor, activity); + break; - if (created !== null) { - return created; - } + case 'Follow': + await follow(parentResolver, actor, activity); + break; - switch (object.type) { - case 'Create': - return create(resolver, actor, object, distribute); + case 'Undo': + await undo(parentResolver, actor, activity); + break; - case 'Delete': - return performDeleteActivity(resolver, actor, object); - - case 'Follow': - return follow(resolver, actor, object, distribute); - - case 'Undo': - return undo(resolver, actor, object); - - default: - return null; - } - }); + default: + console.warn(`unknown activity type: ${activity.type}`); + return null; + } }; diff --git a/src/remote/activitypub/create.ts b/src/remote/activitypub/create.ts deleted file mode 100644 index 97c72860fd..0000000000 --- a/src/remote/activitypub/create.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { JSDOM } from 'jsdom'; -import { ObjectID } from 'mongodb'; -import config from '../../config'; -import DriveFile from '../../models/drive-file'; -import Post from '../../models/post'; -import { IRemoteUser } from '../../models/user'; -import uploadFromUrl from '../../drive/upload-from-url'; -import createPost from '../../post/create'; -import distributePost from '../../post/distribute'; -import Resolver from './resolver'; -const createDOMPurify = require('dompurify'); - -type IResult = { - resolver: Resolver; - object: { - $ref: string; - $id: ObjectID; - }; -}; - -class Creator { - private actor: IRemoteUser; - private distribute: boolean; - - constructor(actor, distribute) { - this.actor = actor; - this.distribute = distribute; - } - - private async createImage(resolver: Resolver, image) { - if ('attributedTo' in image && this.actor.account.uri !== image.attributedTo) { - throw new Error(); - } - - const { _id } = await uploadFromUrl(image.url, this.actor, image.id || null); - return { - resolver, - object: { $ref: 'driveFiles.files', $id: _id } - }; - } - - private async createNote(resolver: Resolver, note) { - if ( - ('attributedTo' in note && this.actor.account.uri !== note.attributedTo) || - typeof note.id !== 'string' - ) { - throw new Error(); - } - - const mediaIds = 'attachment' in note && - (await Promise.all(await this.create(resolver, note.attachment))) - .filter(media => media !== null && media.object.$ref === 'driveFiles.files') - .map(({ object }) => object.$id); - - const { window } = new JSDOM(note.content); - - const inserted = await createPost({ - channelId: undefined, - index: undefined, - createdAt: new Date(note.published), - mediaIds, - replyId: undefined, - repostId: undefined, - poll: undefined, - text: window.document.body.textContent, - textHtml: note.content && createDOMPurify(window).sanitize(note.content), - userId: this.actor._id, - appId: null, - viaMobile: false, - geo: undefined, - uri: note.id - }, null, null, []); - - const promises = []; - - if (this.distribute) { - promises.push(distributePost(this.actor, inserted.mentions, inserted)); - } - - // Register to search database - if (note.content && config.elasticsearch.enable) { - const es = require('../../db/elasticsearch'); - - promises.push(new Promise((resolve, reject) => { - es.index({ - index: 'misskey', - type: 'post', - id: inserted._id.toString(), - body: { - text: window.document.body.textContent - } - }, resolve); - })); - } - - await Promise.all(promises); - - return { - resolver, - object: { $ref: 'posts', id: inserted._id } - }; - } - - public async create(parentResolver: Resolver, value): Promise>> { - const collection = await parentResolver.resolveCollection(value); - - return collection.object.map(async element => { - const uri = element.id || element; - - try { - await Promise.all([ - DriveFile.findOne({ 'metadata.uri': uri }).then(file => { - if (file === null) { - return; - } - - throw { - $ref: 'driveFile.files', - $id: file._id - }; - }, () => {}), - Post.findOne({ uri }).then(post => { - if (post === null) { - return; - } - - throw { - $ref: 'posts', - $id: post._id - }; - }, () => {}) - ]); - } catch (object) { - return { - resolver: collection.resolver, - object - }; - } - - const { resolver, object } = await collection.resolver.resolveOne(element); - - switch (object.type) { - case 'Image': - return this.createImage(resolver, object); - - case 'Note': - return this.createNote(resolver, object); - } - - return null; - }); - } -} - -export default (resolver: Resolver, actor, value, distribute?: boolean) => { - const creator = new Creator(actor, distribute); - return creator.create(resolver, value); -}; diff --git a/src/remote/activitypub/resolver.ts b/src/remote/activitypub/resolver.ts index 371ccdcc30..de0bba2687 100644 --- a/src/remote/activitypub/resolver.ts +++ b/src/remote/activitypub/resolver.ts @@ -1,20 +1,45 @@ +import { IObject } from "./type"; + const request = require('request-promise-native'); export default class Resolver { - private requesting: Set; + private history: Set; - constructor(iterable?: Iterable) { - this.requesting = new Set(iterable); + constructor() { + this.history = new Set(); } - private async resolveUnrequestedOne(value) { - if (typeof value !== 'string') { - return { resolver: this, object: value }; + public async resolveCollection(value) { + const collection = typeof value === 'string' + ? await this.resolve(value) + : value; + + switch (collection.type) { + case 'Collection': + collection.objects = collection.object.items; + break; + + case 'OrderedCollection': + collection.objects = collection.object.orderedItems; + break; + + default: + throw new Error(`unknown collection type: ${collection.type}`); } - const resolver = new Resolver(this.requesting); + return collection; + } - resolver.requesting.add(value); + public async resolve(value): Promise { + if (typeof value !== 'string') { + return value; + } + + if (this.history.has(value)) { + throw new Error('cannot resolve already resolved one'); + } + + this.history.add(value); const object = await request({ url: value, @@ -29,41 +54,9 @@ export default class Resolver { !object['@context'].includes('https://www.w3.org/ns/activitystreams') : object['@context'] !== 'https://www.w3.org/ns/activitystreams' )) { - throw new Error(); + throw new Error('invalid response'); } - return { resolver, object }; - } - - public async resolveCollection(value) { - const resolved = typeof value === 'string' ? - await this.resolveUnrequestedOne(value) : - { resolver: this, object: value }; - - switch (resolved.object.type) { - case 'Collection': - resolved.object = resolved.object.items; - break; - - case 'OrderedCollection': - resolved.object = resolved.object.orderedItems; - break; - - default: - if (!Array.isArray(value)) { - resolved.object = [resolved.object]; - } - break; - } - - return resolved; - } - - public resolveOne(value) { - if (this.requesting.has(value)) { - throw new Error(); - } - - return this.resolveUnrequestedOne(value); + return object; } } diff --git a/src/server/activitypub/inbox.ts b/src/server/activitypub/inbox.ts index 5de8433850..847dc19af6 100644 --- a/src/server/activitypub/inbox.ts +++ b/src/server/activitypub/inbox.ts @@ -24,7 +24,7 @@ app.post('/@:user/inbox', bodyParser.json({ queue.create('http', { type: 'processInbox', - inbox: req.body, + activity: req.body, signature, }).save(); From 5bd1451b610c134c056991e05327990180cbb8d5 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 4 Apr 2018 23:22:48 +0900 Subject: [PATCH 02/68] wip --- src/queue/processors/http/deliver.ts | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/src/queue/processors/http/deliver.ts b/src/queue/processors/http/deliver.ts index 8cd9eb624e..1700063a5d 100644 --- a/src/queue/processors/http/deliver.ts +++ b/src/queue/processors/http/deliver.ts @@ -1,17 +1,7 @@ import * as kue from 'kue'; -import Channel from '../../models/channel'; -import Following from '../../models/following'; -import ChannelWatching from '../../models/channel-watching'; -import Post, { pack } from '../../models/post'; -import User, { isLocalUser } from '../../models/user'; -import stream, { publishChannelStream } from '../../publishers/stream'; -import context from '../../remote/activitypub/renderer/context'; -import renderCreate from '../../remote/activitypub/renderer/create'; -import renderNote from '../../remote/activitypub/renderer/note'; -import request from '../../remote/request'; +import request from '../../../remote/request'; export default async (job: kue.Job, done): Promise => { - - request(user, following.follower[0].account.inbox, create); -} + await request(job.data.user, job.data.to, job.data.content); +}; From 77f056b4fcdf74da8b6a8cc4a923eb8789d6f5ae Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 4 Apr 2018 23:59:38 +0900 Subject: [PATCH 03/68] wip --- src/{ => api}/drive/add-file.ts | 0 src/{ => api}/drive/upload-from-url.ts | 0 src/api/following/create.ts | 82 ++++++++++++++++++++++ src/{ => api}/post/create.ts | 0 src/{ => api}/post/distribute.ts | 0 src/{ => api}/post/watch.ts | 0 src/queue/processors/http/unfollow.ts | 97 ++++++++++++++------------ src/remote/activitypub/act/create.ts | 8 ++- src/remote/activitypub/act/follow.ts | 59 +--------------- 9 files changed, 142 insertions(+), 104 deletions(-) rename src/{ => api}/drive/add-file.ts (100%) rename src/{ => api}/drive/upload-from-url.ts (100%) create mode 100644 src/api/following/create.ts rename src/{ => api}/post/create.ts (100%) rename src/{ => api}/post/distribute.ts (100%) rename src/{ => api}/post/watch.ts (100%) diff --git a/src/drive/add-file.ts b/src/api/drive/add-file.ts similarity index 100% rename from src/drive/add-file.ts rename to src/api/drive/add-file.ts diff --git a/src/drive/upload-from-url.ts b/src/api/drive/upload-from-url.ts similarity index 100% rename from src/drive/upload-from-url.ts rename to src/api/drive/upload-from-url.ts diff --git a/src/api/following/create.ts b/src/api/following/create.ts new file mode 100644 index 0000000000..353a6c8920 --- /dev/null +++ b/src/api/following/create.ts @@ -0,0 +1,82 @@ +import User, { isLocalUser, isRemoteUser, pack as packUser, IUser } from '../../models/user'; +import Following from '../../models/following'; +import FollowingLog from '../../models/following-log'; +import FollowedLog from '../../models/followed-log'; +import event from '../../publishers/stream'; +import notify from '../../publishers/notify'; +import context from '../../remote/activitypub/renderer/context'; +import renderFollow from '../../remote/activitypub/renderer/follow'; +import renderAccept from '../../remote/activitypub/renderer/accept'; +import { createHttp } from '../../queue'; + +export default async function(follower: IUser, followee: IUser, activity?) { + const following = await Following.insert({ + createdAt: new Date(), + followerId: follower._id, + followeeId: followee._id + }); + + //#region Increment following count + User.update({ _id: follower._id }, { + $inc: { + followingCount: 1 + } + }); + + FollowingLog.insert({ + createdAt: following.createdAt, + userId: follower._id, + count: follower.followingCount + 1 + }); + //#endregion + + //#region Increment followers count + User.update({ _id: followee._id }, { + $inc: { + followersCount: 1 + } + }); + FollowedLog.insert({ + createdAt: following.createdAt, + userId: followee._id, + count: followee.followersCount + 1 + }); + //#endregion + + // Publish follow event + if (isLocalUser(follower)) { + packUser(followee, follower).then(packed => event(follower._id, 'follow', packed)); + } + + // Publish followed event + if (isLocalUser(followee)) { + packUser(follower, followee).then(packed => event(followee._id, 'followed', packed)), + + // 通知を作成 + notify(followee._id, follower._id, 'follow'); + } + + if (isLocalUser(follower) && isRemoteUser(followee)) { + const content = renderFollow(follower, followee); + content['@context'] = context; + + createHttp({ + type: 'deliver', + user: follower, + content, + to: followee.account.inbox + }).save(); + } + + if (isRemoteUser(follower) && isLocalUser(followee)) { + const content = renderAccept(activity); + content['@context'] = context; + + createHttp({ + type: 'deliver', + user: followee, + content, + to: follower.account.inbox + }).save(); + } +} diff --git a/src/post/create.ts b/src/api/post/create.ts similarity index 100% rename from src/post/create.ts rename to src/api/post/create.ts diff --git a/src/post/distribute.ts b/src/api/post/distribute.ts similarity index 100% rename from src/post/distribute.ts rename to src/api/post/distribute.ts diff --git a/src/post/watch.ts b/src/api/post/watch.ts similarity index 100% rename from src/post/watch.ts rename to src/api/post/watch.ts diff --git a/src/queue/processors/http/unfollow.ts b/src/queue/processors/http/unfollow.ts index d3d5f2246f..801a3612a7 100644 --- a/src/queue/processors/http/unfollow.ts +++ b/src/queue/processors/http/unfollow.ts @@ -1,56 +1,63 @@ -import FollowedLog from '../../models/followed-log'; -import Following from '../../models/following'; -import FollowingLog from '../../models/following-log'; -import User, { isRemoteUser, pack as packUser } from '../../models/user'; -import stream from '../../publishers/stream'; -import renderFollow from '../../remote/activitypub/renderer/follow'; -import renderUndo from '../../remote/activitypub/renderer/undo'; -import context from '../../remote/activitypub/renderer/context'; -import request from '../../remote/request'; +import FollowedLog from '../../../models/followed-log'; +import Following from '../../../models/following'; +import FollowingLog from '../../../models/following-log'; +import User, { isLocalUser, isRemoteUser, pack as packUser } from '../../../models/user'; +import stream from '../../../publishers/stream'; +import renderFollow from '../../../remote/activitypub/renderer/follow'; +import renderUndo from '../../../remote/activitypub/renderer/undo'; +import context from '../../../remote/activitypub/renderer/context'; +import request from '../../../remote/request'; +import Logger from '../../../utils/logger'; export default async ({ data }) => { - // Delete following - const following = await Following.findOneAndDelete({ _id: data.id }); + const following = await Following.findOne({ _id: data.id }); if (following === null) { return; } - const promisedFollower = User.findOne({ _id: following.followerId }); - const promisedFollowee = User.findOne({ _id: following.followeeId }); + const [follower, followee] = await Promise.all([ + User.findOne({ _id: following.followerId }), + User.findOne({ _id: following.followeeId }) + ]); - await Promise.all([ - // Decrement following count - User.update({ _id: following.followerId }, { $inc: { followingCount: -1 } }), - promisedFollower.then(({ followingCount }) => FollowingLog.insert({ - createdAt: new Date(), - userId: following.followerId, - count: followingCount - 1 - })), + if (isLocalUser(follower) && isRemoteUser(followee)) { + const undo = renderUndo(renderFollow(follower, followee)); + undo['@context'] = context; - // Decrement followers count - User.update({ _id: following.followeeId }, { $inc: { followersCount: -1 } }), - promisedFollowee.then(({ followersCount }) => FollowedLog.insert({ - createdAt: new Date(), - userId: following.followeeId, - count: followersCount - 1 - })), + await request(follower, followee.account.inbox, undo); + } + + try { + await Promise.all([ + // Delete following + Following.findOneAndDelete({ _id: data.id }), + + // Decrement following count + User.update({ _id: follower._id }, { $inc: { followingCount: -1 } }), + FollowingLog.insert({ + createdAt: new Date(), + userId: follower._id, + count: follower.followingCount - 1 + }), + + // Decrement followers count + User.update({ _id: followee._id }, { $inc: { followersCount: -1 } }), + FollowedLog.insert({ + createdAt: new Date(), + userId: followee._id, + count: followee.followersCount - 1 + }) + ]); + + if (isLocalUser(follower)) { + return; + } + + const promisedPackedUser = packUser(followee, follower); // Publish follow event - Promise.all([promisedFollower, promisedFollowee]).then(async ([follower, followee]) => { - if (isRemoteUser(follower)) { - return; - } - - const promisedPackedUser = packUser(followee, follower); - - if (isRemoteUser(followee)) { - const undo = renderUndo(renderFollow(follower, followee)); - undo['@context'] = context; - - await request(follower, followee.account.inbox, undo); - } - - stream(follower._id, 'unfollow', promisedPackedUser); - }) - ]); + stream(follower._id, 'unfollow', promisedPackedUser); + } catch (error) { + Logger.error(error.toString()); + } }; diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index c1a30ce7d0..7ee9f8dfb7 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -4,10 +4,10 @@ const createDOMPurify = require('dompurify'); import Resolver from '../resolver'; import DriveFile from '../../../models/drive-file'; import Post from '../../../models/post'; -import uploadFromUrl from '../../../drive/upload-from-url'; -import createPost from '../../../post/create'; +import uploadFromUrl from '../../../api/drive/upload-from-url'; +import createPost from '../../../api/post/create'; -export default async (resolver: Resolver, actor, activity): Promise => { +export default async (actor, activity): Promise => { if ('actor' in activity && actor.account.uri !== activity.actor) { throw new Error('invalid actor'); } @@ -31,6 +31,8 @@ export default async (resolver: Resolver, actor, activity): Promise => { throw new Error(`already registered: ${uri}`); } + const resolver = new Resolver(); + const object = await resolver.resolve(activity); switch (object.type) { diff --git a/src/remote/activitypub/act/follow.ts b/src/remote/activitypub/act/follow.ts index 23fa41df8e..dc173a0acb 100644 --- a/src/remote/activitypub/act/follow.ts +++ b/src/remote/activitypub/act/follow.ts @@ -1,15 +1,9 @@ -import { MongoError } from 'mongodb'; import parseAcct from '../../../acct/parse'; -import Following, { IFollowing } from '../../../models/following'; import User from '../../../models/user'; import config from '../../../config'; -import queue from '../../../queue'; -import context from '../renderer/context'; -import renderAccept from '../renderer/accept'; -import request from '../../request'; -import Resolver from '../resolver'; +import follow from '../../../api/following/create'; -export default async (resolver: Resolver, actor, activity, distribute) => { +export default async (actor, activity): Promise => { const prefix = config.url + '/@'; const id = activity.object.id || activity.object; @@ -27,52 +21,5 @@ export default async (resolver: Resolver, actor, activity, distribute) => { throw new Error(); } - if (!distribute) { - const { _id } = await Following.findOne({ - followerId: actor._id, - followeeId: followee._id - }); - - return { - resolver, - object: { $ref: 'following', $id: _id } - }; - } - - const promisedFollowing = Following.insert({ - createdAt: new Date(), - followerId: actor._id, - followeeId: followee._id - }).then(following => new Promise((resolve, reject) => { - queue.create('http', { - type: 'follow', - following: following._id - }).save(error => { - if (error) { - reject(error); - } else { - resolve(following); - } - }); - }) as Promise, async error => { - // duplicate key error - if (error instanceof MongoError && error.code === 11000) { - return Following.findOne({ - followerId: actor._id, - followeeId: followee._id - }); - } - - throw error; - }); - - const accept = renderAccept(activity); - accept['@context'] = context; - - await request(followee, actor.account.inbox, accept); - - return promisedFollowing.then(({ _id }) => ({ - resolver, - object: { $ref: 'following', $id: _id } - })); + await follow(actor, followee, activity); }; From 0ac695edbda10231ee70f0a0debedb4c8f708954 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 00:01:01 +0900 Subject: [PATCH 04/68] wip --- src/queue/processors/http/follow.ts | 69 ----------------------------- 1 file changed, 69 deletions(-) delete mode 100644 src/queue/processors/http/follow.ts diff --git a/src/queue/processors/http/follow.ts b/src/queue/processors/http/follow.ts deleted file mode 100644 index 8bf890efbc..0000000000 --- a/src/queue/processors/http/follow.ts +++ /dev/null @@ -1,69 +0,0 @@ -import User, { isLocalUser, pack as packUser } from '../../models/user'; -import Following from '../../models/following'; -import FollowingLog from '../../models/following-log'; -import FollowedLog from '../../models/followed-log'; -import event from '../../publishers/stream'; -import notify from '../../publishers/notify'; -import context from '../../remote/activitypub/renderer/context'; -import render from '../../remote/activitypub/renderer/follow'; -import request from '../../remote/request'; - -export default ({ data }) => Following.findOne({ _id: data.following }).then(({ followerId, followeeId }) => { - const promisedFollower = User.findOne({ _id: followerId }); - const promisedFollowee = User.findOne({ _id: followeeId }); - - return Promise.all([ - // Increment following count - User.update(followerId, { - $inc: { - followingCount: 1 - } - }), - - promisedFollower.then(({ followingCount }) => FollowingLog.insert({ - createdAt: data.following.createdAt, - userId: followerId, - count: followingCount + 1 - })), - - // Increment followers count - User.update({ _id: followeeId }, { - $inc: { - followersCount: 1 - } - }), - - promisedFollowee.then(({ followersCount }) => FollowedLog.insert({ - createdAt: data.following.createdAt, - userId: followerId, - count: followersCount + 1 - })), - - // Notify - promisedFollowee.then(followee => followee.host === null ? - notify(followeeId, followerId, 'follow') : null), - - // Publish follow event - Promise.all([promisedFollower, promisedFollowee]).then(([follower, followee]) => { - let followerEvent; - let followeeEvent; - - if (isLocalUser(follower)) { - followerEvent = packUser(followee, follower) - .then(packed => event(follower._id, 'follow', packed)); - } - - if (isLocalUser(followee)) { - followeeEvent = packUser(follower, followee) - .then(packed => event(followee._id, 'followed', packed)); - } else if (isLocalUser(follower)) { - const rendered = render(follower, followee); - rendered['@context'] = context; - - followeeEvent = request(follower, followee.account.inbox, rendered); - } - - return Promise.all([followerEvent, followeeEvent]); - }) - ]); -}); From 0009a371c86097fd1be117c1eb7e9fa2fcce7400 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 00:40:34 +0900 Subject: [PATCH 05/68] wip --- src/api/post/create.ts | 290 ++++++++++++++++++++++++++++++------- src/api/post/distribute.ts | 190 ------------------------ 2 files changed, 235 insertions(+), 245 deletions(-) delete mode 100644 src/api/post/distribute.ts diff --git a/src/api/post/create.ts b/src/api/post/create.ts index f78bbe7521..af94c6d811 100644 --- a/src/api/post/create.ts +++ b/src/api/post/create.ts @@ -1,76 +1,90 @@ -import parseAcct from '../acct/parse'; -import Post, { pack } from '../models/post'; -import User, { isLocalUser, isRemoteUser, IUser } from '../models/user'; -import stream from '../publishers/stream'; -import Following from '../models/following'; -import { createHttp } from '../queue'; -import renderNote from '../remote/activitypub/renderer/note'; -import renderCreate from '../remote/activitypub/renderer/create'; -import context from '../remote/activitypub/renderer/context'; +import parseAcct from '../../acct/parse'; +import Post, { pack, IPost } from '../../models/post'; +import User, { isLocalUser, isRemoteUser, IUser } from '../../models/user'; +import stream from '../../publishers/stream'; +import Following from '../../models/following'; +import { createHttp } from '../../queue'; +import renderNote from '../../remote/activitypub/renderer/note'; +import renderCreate from '../../remote/activitypub/renderer/create'; +import context from '../../remote/activitypub/renderer/context'; +import { IDriveFile } from '../../models/drive-file'; +import notify from '../../publishers/notify'; +import PostWatching from '../../models/post-watching'; +import watch from './watch'; +import Mute from '../../models/mute'; +import pushSw from '../../publishers/push-sw'; +import event from '../../publishers/stream'; +import parse from '../../text/parse'; -export default async (user: IUser, post, reply, repost, atMentions) => { - post.mentions = []; +export default async (user: IUser, content: { + createdAt: Date; + text: string; + reply: IPost; + repost: IPost; + media: IDriveFile[]; + geo: any; + viaMobile: boolean; + tags: string[]; +}) => new Promise(async (res, rej) => { + const tags = content.tags || []; - function addMention(mentionee) { - // Reject if already added - if (post.mentions.some(x => x.equals(mentionee))) return; + let tokens = null; - // Add mention - post.mentions.push(mentionee); + if (content.text) { + // Analyze + tokens = parse(content.text); + + // Extract hashtags + const hashtags = tokens + .filter(t => t.type == 'hashtag') + .map(t => t.hashtag); + + hashtags.forEach(tag => { + if (tags.indexOf(tag) == -1) { + tags.push(tag); + } + }); } - if (reply) { - // Add mention - addMention(reply.userId); - post.replyId = reply._id; - post._reply = { userId: reply.userId }; - } else { - post.replyId = null; - post._reply = null; - } + // 投稿を作成 + const post = await Post.insert({ + createdAt: content.createdAt, + mediaIds: content.media ? content.media.map(file => file._id) : [], + replyId: content.reply ? content.reply._id : null, + repostId: content.repost ? content.repost._id : null, + text: content.text, + tags, + userId: user._id, + viaMobile: content.viaMobile, + geo: content.geo || null, - if (repost) { - if (post.text) { - // Add mention - addMention(repost.userId); - } + // 以下非正規化データ + _reply: content.reply ? { userId: content.reply.userId } : null, + _repost: content.repost ? { userId: content.repost.userId } : null, + }); - post.repostId = repost._id; - post._repost = { userId: repost.userId }; - } else { - post.repostId = null; - post._repost = null; - } - - await Promise.all(atMentions.map(async mention => { - // Fetch mentioned user - // SELECT _id - const { _id } = await User - .findOne(parseAcct(mention), { _id: true }); - - // Add mention - addMention(_id); - })); - - const inserted = await Post.insert(post); + res(post); User.update({ _id: user._id }, { - // Increment my posts count + // Increment posts count $inc: { postsCount: 1 }, - + // Update latest post $set: { - latestPost: post._id + latestPost: post } }); - const postObj = await pack(inserted); + // Serialize + const postObj = await pack(post); // タイムラインへの投稿 if (!post.channelId) { // Publish event to myself's stream - stream(post.userId, 'post', postObj); + if (isLocalUser(user)) { + stream(post.userId, 'post', postObj); + } // Fetch all followers const followers = await Following.aggregate([{ @@ -144,6 +158,172 @@ export default async (user: IUser, post, reply, repost, atMentions) => { ); }*/ - return Promise.all(promises); + const mentions = []; -}; + async function addMention(mentionee, reason) { + // Reject if already added + if (mentions.some(x => x.equals(mentionee))) return; + + // Add mention + mentions.push(mentionee); + + // Publish event + if (!user._id.equals(mentionee)) { + const mentioneeMutes = await Mute.find({ + muter_id: mentionee, + deleted_at: { $exists: false } + }); + const mentioneesMutedUserIds = mentioneeMutes.map(m => m.muteeId.toString()); + if (mentioneesMutedUserIds.indexOf(user._id.toString()) == -1) { + event(mentionee, reason, postObj); + pushSw(mentionee, reason, postObj); + } + } + } + + // If has in reply to post + if (content.reply) { + // Increment replies count + Post.update({ _id: content.reply._id }, { + $inc: { + repliesCount: 1 + } + }); + + // (自分自身へのリプライでない限りは)通知を作成 + notify(content.reply.userId, user._id, 'reply', { + postId: post._id + }); + + // Fetch watchers + PostWatching.find({ + postId: content.reply._id, + userId: { $ne: user._id }, + // 削除されたドキュメントは除く + deletedAt: { $exists: false } + }, { + fields: { + userId: true + } + }).then(watchers => { + watchers.forEach(watcher => { + notify(watcher.userId, user._id, 'reply', { + postId: post._id + }); + }); + }); + + // この投稿をWatchする + if (isLocalUser(user) && user.account.settings.autoWatch !== false) { + watch(user._id, content.reply); + } + + // Add mention + addMention(content.reply.userId, 'reply'); + } + + // If it is repost + if (content.repost) { + // Notify + const type = content.text ? 'quote' : 'repost'; + notify(content.repost.userId, user._id, type, { + post_id: post._id + }); + + // Fetch watchers + PostWatching.find({ + postId: content.repost._id, + userId: { $ne: user._id }, + // 削除されたドキュメントは除く + deletedAt: { $exists: false } + }, { + fields: { + userId: true + } + }).then(watchers => { + watchers.forEach(watcher => { + notify(watcher.userId, user._id, type, { + postId: post._id + }); + }); + }); + + // この投稿をWatchする + if (isLocalUser(user) && user.account.settings.autoWatch !== false) { + watch(user._id, content.repost); + } + + // If it is quote repost + if (content.text) { + // Add mention + addMention(content.repost.userId, 'quote'); + } else { + // Publish event + if (!user._id.equals(content.repost.userId)) { + event(content.repost.userId, 'repost', postObj); + } + } + + // 今までで同じ投稿をRepostしているか + const existRepost = await Post.findOne({ + userId: user._id, + repostId: content.repost._id, + _id: { + $ne: post._id + } + }); + + if (!existRepost) { + // Update repostee status + Post.update({ _id: content.repost._id }, { + $inc: { + repostCount: 1 + } + }); + } + } + + // If has text content + if (content.text) { + // Extract an '@' mentions + const atMentions = tokens + .filter(t => t.type == 'mention') + .map(m => m.username) + // Drop dupulicates + .filter((v, i, s) => s.indexOf(v) == i); + + // Resolve all mentions + await Promise.all(atMentions.map(async mention => { + // Fetch mentioned user + // SELECT _id + const mentionee = await User + .findOne({ + usernameLower: mention.toLowerCase() + }, { _id: true }); + + // When mentioned user not found + if (mentionee == null) return; + + // 既に言及されたユーザーに対する返信や引用repostの場合も無視 + if (content.reply && content.reply.userId.equals(mentionee._id)) return; + if (content.repost && content.repost.userId.equals(mentionee._id)) return; + + // Add mention + addMention(mentionee._id, 'mention'); + + // Create notification + notify(mentionee._id, user._id, 'mention', { + post_id: post._id + }); + })); + } + + // Append mentions data + if (mentions.length > 0) { + Post.update({ _id: post._id }, { + $set: { + mentions + } + }); + } +}); diff --git a/src/api/post/distribute.ts b/src/api/post/distribute.ts deleted file mode 100644 index 49c6eb22df..0000000000 --- a/src/api/post/distribute.ts +++ /dev/null @@ -1,190 +0,0 @@ -import Mute from '../models/mute'; -import Post, { pack } from '../models/post'; -import Watching from '../models/post-watching'; -import User from '../models/user'; -import stream from '../publishers/stream'; -import notify from '../publishers/notify'; -import pushSw from '../publishers/push-sw'; -import queue from '../queue'; -import watch from './watch'; - -export default async (user, mentions, post) => { - const promisedPostObj = pack(post); - const promises = [ - User.update({ _id: user._id }, { - // Increment my posts count - $inc: { - postsCount: 1 - }, - - $set: { - latestPost: post._id - } - }), - new Promise((resolve, reject) => queue.create('http', { - type: 'deliverPost', - id: post._id, - }).save(error => error ? reject(error) : resolve())), - ] as Array>; - - function addMention(promisedMentionee, reason) { - // Publish event - promises.push(promisedMentionee.then(mentionee => { - if (user._id.equals(mentionee)) { - return Promise.resolve(); - } - - return Promise.all([ - promisedPostObj, - Mute.find({ - muterId: mentionee, - deletedAt: { $exists: false } - }) - ]).then(([postObj, mentioneeMutes]) => { - const mentioneesMutedUserIds = mentioneeMutes.map(m => m.muteeId.toString()); - if (mentioneesMutedUserIds.indexOf(user._id.toString()) == -1) { - stream(mentionee, reason, postObj); - pushSw(mentionee, reason, postObj); - } - }); - })); - } - - // If has in reply to post - if (post.replyId) { - promises.push( - // Increment replies count - Post.update({ _id: post.replyId }, { - $inc: { - repliesCount: 1 - } - }), - - // 自分自身へのリプライでない限りは通知を作成 - promisedPostObj.then(({ reply }) => { - return notify(reply.userId, user._id, 'reply', { - postId: post._id - }); - }), - - // Fetch watchers - Watching - .find({ - postId: post.replyId, - userId: { $ne: user._id }, - // 削除されたドキュメントは除く - deletedAt: { $exists: false } - }, { - fields: { - userId: true - } - }) - .then(watchers => { - watchers.forEach(watcher => { - notify(watcher.userId, user._id, 'reply', { - postId: post._id - }); - }); - }) - ); - - // Add mention - addMention(promisedPostObj.then(({ reply }) => reply.userId), 'reply'); - - // この投稿をWatchする - if (user.account.settings.autoWatch !== false) { - promises.push(promisedPostObj.then(({ reply }) => { - return watch(user._id, reply); - })); - } - } - - // If it is repost - if (post.repostId) { - const type = post.text ? 'quote' : 'repost'; - - promises.push( - promisedPostObj.then(({ repost }) => Promise.all([ - // Notify - notify(repost.userId, user._id, type, { - postId: post._id - }), - - // この投稿をWatchする - // TODO: ユーザーが「Repostしたときに自動でWatchする」設定を - // オフにしていた場合はしない - watch(user._id, repost) - ])), - - // Fetch watchers - Watching - .find({ - postId: post.repostId, - userId: { $ne: user._id }, - // 削除されたドキュメントは除く - deletedAt: { $exists: false } - }, { - fields: { - userId: true - } - }) - .then(watchers => { - watchers.forEach(watcher => { - notify(watcher.userId, user._id, type, { - postId: post._id - }); - }); - }) - ); - - // If it is quote repost - if (post.text) { - // Add mention - addMention(promisedPostObj.then(({ repost }) => repost.userId), 'quote'); - } else { - promises.push(promisedPostObj.then(postObj => { - // Publish event - if (!user._id.equals(postObj.repost.userId)) { - stream(postObj.repost.userId, 'repost', postObj); - } - })); - } - - // 今までで同じ投稿をRepostしているか - const existRepost = await Post.findOne({ - userId: user._id, - repostId: post.repostId, - _id: { - $ne: post._id - } - }); - - if (!existRepost) { - // Update repostee status - promises.push(Post.update({ _id: post.repostId }, { - $inc: { - repostCount: 1 - } - })); - } - } - - // Resolve all mentions - await promisedPostObj.then(({ reply, repost }) => Promise.all(mentions.map(async mention => { - // 既に言及されたユーザーに対する返信や引用repostの場合も無視 - if (reply && reply.userId.equals(mention)) return; - if (repost && repost.userId.equals(mention)) return; - - // Add mention - addMention(mention, 'mention'); - - // Create notification - await notify(mention, user._id, 'mention', { - postId: post._id - }); - }))); - - await Promise.all(promises); - - return promisedPostObj; -}; From fd73fad148a500bd95a575fe6e4b73a25882fb89 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 00:50:57 +0900 Subject: [PATCH 06/68] wip --- src/api/post/create.ts | 15 ++++- src/remote/activitypub/act/create.ts | 18 ++---- src/server/api/endpoints/posts/create.ts | 82 ++++-------------------- 3 files changed, 31 insertions(+), 84 deletions(-) diff --git a/src/api/post/create.ts b/src/api/post/create.ts index af94c6d811..8256cbc355 100644 --- a/src/api/post/create.ts +++ b/src/api/post/create.ts @@ -15,6 +15,8 @@ import Mute from '../../models/mute'; import pushSw from '../../publishers/push-sw'; import event from '../../publishers/stream'; import parse from '../../text/parse'; +import html from '../../text/html'; +import { IApp } from '../../models/app'; export default async (user: IUser, content: { createdAt: Date; @@ -23,9 +25,14 @@ export default async (user: IUser, content: { repost: IPost; media: IDriveFile[]; geo: any; + poll: any; viaMobile: boolean; tags: string[]; -}) => new Promise(async (res, rej) => { + cw: string; + visibility: string; + uri?: string; + app?: IApp; +}) => new Promise(async (res, rej) => { const tags = content.tags || []; let tokens = null; @@ -53,10 +60,16 @@ export default async (user: IUser, content: { replyId: content.reply ? content.reply._id : null, repostId: content.repost ? content.repost._id : null, text: content.text, + textHtml: tokens === null ? null : html(tokens), + poll: content.poll, + cw: content.cw, tags, userId: user._id, viaMobile: content.viaMobile, geo: content.geo || null, + uri: content.uri, + appId: content.app ? content.app._id : null, + visibility: content.visibility, // 以下非正規化データ _reply: content.reply ? { userId: content.reply.userId } : null, diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index 7ee9f8dfb7..957900900f 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -63,32 +63,26 @@ export default async (actor, activity): Promise => { throw new Error('invalid note'); } - const mediaIds = []; + const media = []; if ('attachment' in note) { note.attachment.forEach(async media => { const created = await createImage(resolver, media); - mediaIds.push(created._id); + media.push(created); }); } const { window } = new JSDOM(note.content); await createPost(actor, { - channelId: undefined, - index: undefined, createdAt: new Date(note.published), - mediaIds, - replyId: undefined, - repostId: undefined, - poll: undefined, + media, + reply: undefined, + repost: undefined, text: window.document.body.textContent, - textHtml: note.content && createDOMPurify(window).sanitize(note.content), - userId: actor._id, - appId: null, viaMobile: false, geo: undefined, uri: note.id - }, null, null, []); + }); } }; diff --git a/src/server/api/endpoints/posts/create.ts b/src/server/api/endpoints/posts/create.ts index 03af7ee763..d241c8c387 100644 --- a/src/server/api/endpoints/posts/create.ts +++ b/src/server/api/endpoints/posts/create.ts @@ -3,16 +3,12 @@ */ import $ from 'cafy'; import deepEqual = require('deep-equal'); -import renderAcct from '../../../../acct/render'; -import config from '../../../../config'; -import html from '../../../../text/html'; -import parse from '../../../../text/parse'; -import Post, { IPost, isValidText, isValidCw } from '../../../../models/post'; +import Post, { IPost, isValidText, isValidCw, pack } from '../../../../models/post'; import { ILocalUser } from '../../../../models/user'; import Channel, { IChannel } from '../../../../models/channel'; import DriveFile from '../../../../models/drive-file'; -import create from '../../../../post/create'; -import distribute from '../../../../post/distribute'; +import create from '../../../../api/post/create'; +import { IApp } from '../../../../models/app'; /** * Create a post @@ -22,7 +18,7 @@ import distribute from '../../../../post/distribute'; * @param {any} app * @return {Promise} */ -module.exports = (params, user: ILocalUser, app) => new Promise(async (res, rej) => { +module.exports = (params, user: ILocalUser, app: IApp) => new Promise(async (res, rej) => { // Get 'visibility' parameter const [visibility = 'public', visibilityErr] = $(params.visibility).optional.string().or(['public', 'unlisted', 'private', 'direct']).$; if (visibilityErr) return rej('invalid visibility'); @@ -230,82 +226,26 @@ module.exports = (params, user: ILocalUser, app) => new Promise(async (res, rej) } } - let tokens = null; - if (text) { - // Analyze - tokens = parse(text); - - // Extract hashtags - const hashtags = tokens - .filter(t => t.type == 'hashtag') - .map(t => t.hashtag); - - hashtags.forEach(tag => { - if (tags.indexOf(tag) == -1) { - tags.push(tag); - } - }); - } - - let atMentions = []; - - // If has text content - if (text) { - /* - // Extract a hashtags - const hashtags = tokens - .filter(t => t.type == 'hashtag') - .map(t => t.hashtag) - // Drop dupulicates - .filter((v, i, s) => s.indexOf(v) == i); - - // ハッシュタグをデータベースに登録 - registerHashtags(user, hashtags); - */ - // Extract an '@' mentions - atMentions = tokens - .filter(t => t.type == 'mention') - .map(renderAcct) - // Drop dupulicates - .filter((v, i, s) => s.indexOf(v) == i); - } - // 投稿を作成 - const post = await create({ + const post = await create(user, { createdAt: new Date(), - channelId: channel ? channel._id : undefined, - index: channel ? channel.index + 1 : undefined, - mediaIds: files ? files.map(file => file._id) : [], + media: files, poll: poll, text: text, - textHtml: tokens === null ? null : html(tokens), + reply, + repost, cw: cw, tags: tags, - userId: user._id, - appId: app ? app._id : null, + app: app, viaMobile: viaMobile, visibility, geo - }, reply, repost, atMentions); + }); - const postObj = await distribute(user, post.mentions, post); + const postObj = await pack(post, user); // Reponse res({ createdPost: postObj }); - - // Register to search database - if (post.text && config.elasticsearch.enable) { - const es = require('../../../db/elasticsearch'); - - es.index({ - index: 'misskey', - type: 'post', - id: post._id.toString(), - body: { - text: post.text - } - }); - } }); From fba46b4c7f5751cd31463e922edb19f5652ca408 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 01:07:07 +0900 Subject: [PATCH 07/68] wip --- src/queue/processors/http/index.ts | 10 +--- .../processors/http/perform-activitypub.ts | 7 --- src/remote/activitypub/resolve-person.ts | 58 +++++-------------- 3 files changed, 15 insertions(+), 60 deletions(-) delete mode 100644 src/queue/processors/http/perform-activitypub.ts diff --git a/src/queue/processors/http/index.ts b/src/queue/processors/http/index.ts index 8f9aa717c3..06c6b1d1aa 100644 --- a/src/queue/processors/http/index.ts +++ b/src/queue/processors/http/index.ts @@ -1,17 +1,11 @@ -import deliverPost from './deliver-post'; -import follow from './follow'; -import performActivityPub from './perform-activitypub'; +import deliver from './deliver'; import processInbox from './process-inbox'; import reportGitHubFailure from './report-github-failure'; -import unfollow from './unfollow'; const handlers = { - deliverPost, - follow, - performActivityPub, + deliver, processInbox, reportGitHubFailure, - unfollow }; export default (job, done) => handlers[job.data.type](job).then(() => done(), done); diff --git a/src/queue/processors/http/perform-activitypub.ts b/src/queue/processors/http/perform-activitypub.ts deleted file mode 100644 index 963e532fe5..0000000000 --- a/src/queue/processors/http/perform-activitypub.ts +++ /dev/null @@ -1,7 +0,0 @@ -import User from '../../models/user'; -import act from '../../remote/activitypub/act'; -import Resolver from '../../remote/activitypub/resolver'; - -export default ({ data }) => User.findOne({ _id: data.actor }) - .then(actor => act(new Resolver(), actor, data.outbox)) - .then(Promise.all); diff --git a/src/remote/activitypub/resolve-person.ts b/src/remote/activitypub/resolve-person.ts index 59be65908e..77d08398be 100644 --- a/src/remote/activitypub/resolve-person.ts +++ b/src/remote/activitypub/resolve-person.ts @@ -1,17 +1,15 @@ import { JSDOM } from 'jsdom'; import { toUnicode } from 'punycode'; import User, { validateUsername, isValidName, isValidDescription } from '../../models/user'; -import queue from '../../queue'; import webFinger from '../webfinger'; import create from './create'; import Resolver from './resolver'; - -async function isCollection(collection) { - return ['Collection', 'OrderedCollection'].includes(collection.type); -} +import uploadFromUrl from '../../api/drive/upload-from-url'; export default async (value, verifier?: string) => { - const { resolver, object } = await new Resolver().resolveOne(value); + const resolver = new Resolver(); + + const object = await resolver.resolve(value) as any; if ( object === null || @@ -21,24 +19,10 @@ export default async (value, verifier?: string) => { !isValidName(object.name) || !isValidDescription(object.summary) ) { - throw new Error(); + throw new Error('invalid person'); } - const [followers, following, outbox, finger] = await Promise.all([ - resolver.resolveOne(object.followers).then( - resolved => isCollection(resolved.object) ? resolved.object : null, - () => null - ), - resolver.resolveOne(object.following).then( - resolved => isCollection(resolved.object) ? resolved.object : null, - () => null - ), - resolver.resolveOne(object.outbox).then( - resolved => isCollection(resolved.object) ? resolved.object : null, - () => null - ), - webFinger(object.id, verifier), - ]); + const finger = await webFinger(object.id, verifier); const host = toUnicode(finger.subject.replace(/^.*?@/, '')); const hostLower = host.replace(/[A-Z]+/, matched => matched.toLowerCase()); @@ -50,10 +34,10 @@ export default async (value, verifier?: string) => { bannerId: null, createdAt: Date.parse(object.published), description: summaryDOM.textContent, - followersCount: followers ? followers.totalItem || 0 : 0, - followingCount: following ? following.totalItem || 0 : 0, + followersCount: 0, + followingCount: 0, name: object.name, - postsCount: outbox ? outbox.totalItem || 0 : 0, + postsCount: 0, driveCapacity: 1024 * 1024 * 8, // 8MiB username: object.preferredUsername, usernameLower: object.preferredUsername.toLowerCase(), @@ -69,33 +53,17 @@ export default async (value, verifier?: string) => { }, }); - queue.create('http', { - type: 'performActivityPub', - actor: user._id, - outbox - }).save(); - const [avatarId, bannerId] = await Promise.all([ object.icon, object.image - ].map(async value => { - if (value === undefined) { + ].map(async url => { + if (url === undefined) { return null; } - try { - const created = await create(resolver, user, value); + const img = await uploadFromUrl(url, user); - await Promise.all(created.map(asyncCreated => asyncCreated.then(created => { - if (created !== null && created.object.$ref === 'driveFiles.files') { - throw created.object.$id; - } - }, () => {}))); - - return null; - } catch (id) { - return id; - } + return img._id; })); User.update({ _id: user._id }, { $set: { avatarId, bannerId } }); From eb304cb5fb588a3da8742f234cdf05ce6deeaa59 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 01:22:41 +0900 Subject: [PATCH 08/68] wip --- src/api/following/delete.ts | 69 +++++++++++++++++++++ src/queue/processors/http/unfollow.ts | 63 ------------------- src/remote/activitypub/act/create.ts | 1 - src/remote/activitypub/act/index.ts | 11 ++-- src/remote/activitypub/act/undo.ts | 15 +++++ src/remote/activitypub/act/undo/index.ts | 27 -------- src/remote/activitypub/act/undo/unfollow.ts | 11 ---- src/remote/activitypub/act/unfollow.ts | 25 ++++++++ 8 files changed, 114 insertions(+), 108 deletions(-) create mode 100644 src/api/following/delete.ts delete mode 100644 src/queue/processors/http/unfollow.ts create mode 100644 src/remote/activitypub/act/undo.ts delete mode 100644 src/remote/activitypub/act/undo/index.ts delete mode 100644 src/remote/activitypub/act/undo/unfollow.ts create mode 100644 src/remote/activitypub/act/unfollow.ts diff --git a/src/api/following/delete.ts b/src/api/following/delete.ts new file mode 100644 index 0000000000..4cdff7ce1b --- /dev/null +++ b/src/api/following/delete.ts @@ -0,0 +1,69 @@ +import User, { isLocalUser, isRemoteUser, pack as packUser, IUser } from '../../models/user'; +import Following from '../../models/following'; +import FollowingLog from '../../models/following-log'; +import FollowedLog from '../../models/followed-log'; +import event from '../../publishers/stream'; +import context from '../../remote/activitypub/renderer/context'; +import renderFollow from '../../remote/activitypub/renderer/follow'; +import renderUndo from '../../remote/activitypub/renderer/undo'; +import { createHttp } from '../../queue'; + +export default async function(follower: IUser, followee: IUser, activity?) { + const following = await Following.findOne({ + followerId: follower._id, + followeeId: followee._id + }); + + if (following == null) { + console.warn('フォロー解除がリクエストされましたがフォローしていませんでした'); + return; + } + + Following.remove({ + _id: following._id + }); + + //#region Decrement following count + User.update({ _id: follower._id }, { + $inc: { + followingCount: -1 + } + }); + + FollowingLog.insert({ + createdAt: following.createdAt, + userId: follower._id, + count: follower.followingCount - 1 + }); + //#endregion + + //#region Decrement followers count + User.update({ _id: followee._id }, { + $inc: { + followersCount: -1 + } + }); + FollowedLog.insert({ + createdAt: following.createdAt, + userId: followee._id, + count: followee.followersCount - 1 + }); + //#endregion + + // Publish unfollow event + if (isLocalUser(follower)) { + packUser(followee, follower).then(packed => event(follower._id, 'unfollow', packed)); + } + + if (isLocalUser(follower) && isRemoteUser(followee)) { + const content = renderUndo(renderFollow(follower, followee)); + content['@context'] = context; + + createHttp({ + type: 'deliver', + user: follower, + content, + to: followee.account.inbox + }).save(); + } +} diff --git a/src/queue/processors/http/unfollow.ts b/src/queue/processors/http/unfollow.ts deleted file mode 100644 index 801a3612a7..0000000000 --- a/src/queue/processors/http/unfollow.ts +++ /dev/null @@ -1,63 +0,0 @@ -import FollowedLog from '../../../models/followed-log'; -import Following from '../../../models/following'; -import FollowingLog from '../../../models/following-log'; -import User, { isLocalUser, isRemoteUser, pack as packUser } from '../../../models/user'; -import stream from '../../../publishers/stream'; -import renderFollow from '../../../remote/activitypub/renderer/follow'; -import renderUndo from '../../../remote/activitypub/renderer/undo'; -import context from '../../../remote/activitypub/renderer/context'; -import request from '../../../remote/request'; -import Logger from '../../../utils/logger'; - -export default async ({ data }) => { - const following = await Following.findOne({ _id: data.id }); - if (following === null) { - return; - } - - const [follower, followee] = await Promise.all([ - User.findOne({ _id: following.followerId }), - User.findOne({ _id: following.followeeId }) - ]); - - if (isLocalUser(follower) && isRemoteUser(followee)) { - const undo = renderUndo(renderFollow(follower, followee)); - undo['@context'] = context; - - await request(follower, followee.account.inbox, undo); - } - - try { - await Promise.all([ - // Delete following - Following.findOneAndDelete({ _id: data.id }), - - // Decrement following count - User.update({ _id: follower._id }, { $inc: { followingCount: -1 } }), - FollowingLog.insert({ - createdAt: new Date(), - userId: follower._id, - count: follower.followingCount - 1 - }), - - // Decrement followers count - User.update({ _id: followee._id }, { $inc: { followersCount: -1 } }), - FollowedLog.insert({ - createdAt: new Date(), - userId: followee._id, - count: followee.followersCount - 1 - }) - ]); - - if (isLocalUser(follower)) { - return; - } - - const promisedPackedUser = packUser(followee, follower); - - // Publish follow event - stream(follower._id, 'unfollow', promisedPackedUser); - } catch (error) { - Logger.error(error.toString()); - } -}; diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index 957900900f..c486571fc1 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -1,5 +1,4 @@ import { JSDOM } from 'jsdom'; -const createDOMPurify = require('dompurify'); import Resolver from '../resolver'; import DriveFile from '../../../models/drive-file'; diff --git a/src/remote/activitypub/act/index.ts b/src/remote/activitypub/act/index.ts index d78335f16e..f22500acef 100644 --- a/src/remote/activitypub/act/index.ts +++ b/src/remote/activitypub/act/index.ts @@ -2,25 +2,24 @@ import create from './create'; import performDeleteActivity from './delete'; import follow from './follow'; import undo from './undo'; -import Resolver from '../resolver'; import { IObject } from '../type'; -export default async (parentResolver: Resolver, actor, activity: IObject): Promise => { +export default async (actor, activity: IObject): Promise => { switch (activity.type) { case 'Create': - await create(parentResolver, actor, activity); + await create(actor, activity); break; case 'Delete': - await performDeleteActivity(parentResolver, actor, activity); + await performDeleteActivity(actor, activity); break; case 'Follow': - await follow(parentResolver, actor, activity); + await follow(actor, activity); break; case 'Undo': - await undo(parentResolver, actor, activity); + await undo(actor, activity); break; default: diff --git a/src/remote/activitypub/act/undo.ts b/src/remote/activitypub/act/undo.ts new file mode 100644 index 0000000000..b3b83777d1 --- /dev/null +++ b/src/remote/activitypub/act/undo.ts @@ -0,0 +1,15 @@ +import unfollow from './unfollow'; + +export default async (actor, activity): Promise => { + if ('actor' in activity && actor.account.uri !== activity.actor) { + throw new Error('invalid actor'); + } + + switch (activity.object.type) { + case 'Follow': + unfollow(activity.object); + break; + } + + return null; +}; diff --git a/src/remote/activitypub/act/undo/index.ts b/src/remote/activitypub/act/undo/index.ts deleted file mode 100644 index aa60d3a4fa..0000000000 --- a/src/remote/activitypub/act/undo/index.ts +++ /dev/null @@ -1,27 +0,0 @@ -import act from '../../act'; -import deleteObject from '../../delete'; -import unfollow from './unfollow'; -import Resolver from '../../resolver'; - -export default async (resolver: Resolver, actor, activity): Promise => { - if ('actor' in activity && actor.account.uri !== activity.actor) { - throw new Error(); - } - - const results = await act(resolver, actor, activity.object); - - await Promise.all(results.map(async promisedResult => { - const result = await promisedResult; - - if (result === null || await deleteObject(result) !== null) { - return; - } - - switch (result.object.$ref) { - case 'following': - await unfollow(result.object); - } - })); - - return null; -}; diff --git a/src/remote/activitypub/act/undo/unfollow.ts b/src/remote/activitypub/act/undo/unfollow.ts deleted file mode 100644 index c17e06e8a9..0000000000 --- a/src/remote/activitypub/act/undo/unfollow.ts +++ /dev/null @@ -1,11 +0,0 @@ -import queue from '../../../../queue'; - -export default ({ $id }) => new Promise((resolve, reject) => { - queue.create('http', { type: 'unfollow', id: $id }).save(error => { - if (error) { - reject(error); - } else { - resolve(); - } - }); -}); diff --git a/src/remote/activitypub/act/unfollow.ts b/src/remote/activitypub/act/unfollow.ts new file mode 100644 index 0000000000..e3c9e1c1c8 --- /dev/null +++ b/src/remote/activitypub/act/unfollow.ts @@ -0,0 +1,25 @@ +import parseAcct from '../../../acct/parse'; +import User from '../../../models/user'; +import config from '../../../config'; +import unfollow from '../../../api/following/delete'; + +export default async (actor, activity): Promise => { + const prefix = config.url + '/@'; + const id = activity.object.id || activity.object; + + if (!id.startsWith(prefix)) { + return null; + } + + const { username, host } = parseAcct(id.slice(prefix.length)); + if (host !== null) { + throw new Error(); + } + + const followee = await User.findOne({ username, host }); + if (followee === null) { + throw new Error(); + } + + await unfollow(actor, followee, activity); +}; From b6b98752053042b3b37d5b94bc823635edc2061f Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 01:24:01 +0900 Subject: [PATCH 09/68] wip --- src/queue/processors/http/process-inbox.ts | 12 ++++++------ src/queue/processors/index.ts | 18 ------------------ 2 files changed, 6 insertions(+), 24 deletions(-) delete mode 100644 src/queue/processors/index.ts diff --git a/src/queue/processors/http/process-inbox.ts b/src/queue/processors/http/process-inbox.ts index fff1fbf663..82585d3a6b 100644 --- a/src/queue/processors/http/process-inbox.ts +++ b/src/queue/processors/http/process-inbox.ts @@ -1,11 +1,11 @@ import * as kue from 'kue'; import { verifySignature } from 'http-signature'; -import parseAcct from '../../acct/parse'; -import User, { IRemoteUser } from '../../models/user'; -import act from '../../remote/activitypub/act'; -import resolvePerson from '../../remote/activitypub/resolve-person'; -import Resolver from '../../remote/activitypub/resolver'; +import parseAcct from '../../../acct/parse'; +import User, { IRemoteUser } from '../../../models/user'; +import act from '../../../remote/activitypub/act'; +import resolvePerson from '../../../remote/activitypub/resolve-person'; +import Resolver from '../../../remote/activitypub/resolver'; // ユーザーのinboxにアクティビティが届いた時の処理 export default async (job: kue.Job, done): Promise => { @@ -47,7 +47,7 @@ export default async (job: kue.Job, done): Promise => { // アクティビティを処理 try { - await act(new Resolver(), user, activity); + await act(user, activity); done(); } catch (e) { done(e); diff --git a/src/queue/processors/index.ts b/src/queue/processors/index.ts deleted file mode 100644 index 172048ddae..0000000000 --- a/src/queue/processors/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -import queue from '../queue'; -import db from './db'; -import http from './http'; - -export default () => { - queue.process('db', db); - - /* - 256 is the default concurrency limit of Mozilla Firefox and Google - Chromium. - - a8af215e691f3a2205a3758d2d96e9d328e100ff - chromium/src.git - Git at Google - https://chromium.googlesource.com/chromium/src.git/+/a8af215e691f3a2205a3758d2d96e9d328e100ff - Network.http.max-connections - MozillaZine Knowledge Base - http://kb.mozillazine.org/Network.http.max-connections - */ - queue.process('http', 256, http); -}; From c2c03a1c650c0395fc4d77334ec86d00b1bb24c2 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 03:21:11 +0900 Subject: [PATCH 10/68] wip --- src/api/drive/add-file.ts | 12 +++---- src/api/drive/upload-from-url.ts | 2 +- src/api/post/create.ts | 13 ++++---- src/api/post/watch.ts | 2 +- .../processors/db/delete-post-dependents.ts | 12 +++---- src/queue/processors/http/process-inbox.ts | 1 - src/remote/activitypub/act/create.ts | 25 ++++++++++----- src/remote/activitypub/act/delete.ts | 31 ++++++++++++------- src/remote/activitypub/act/undo.ts | 2 +- src/remote/activitypub/delete/index.ts | 10 ------ src/remote/activitypub/delete/post.ts | 13 -------- src/remote/activitypub/resolve-person.ts | 1 - src/server/activitypub/inbox.ts | 4 +-- 13 files changed, 60 insertions(+), 68 deletions(-) delete mode 100644 src/remote/activitypub/delete/index.ts delete mode 100644 src/remote/activitypub/delete/post.ts diff --git a/src/api/drive/add-file.ts b/src/api/drive/add-file.ts index 24eb5208d5..64a2f18340 100644 --- a/src/api/drive/add-file.ts +++ b/src/api/drive/add-file.ts @@ -10,12 +10,12 @@ import * as debug from 'debug'; import fileType = require('file-type'); import prominence = require('prominence'); -import DriveFile, { IMetadata, getGridFSBucket } from '../models/drive-file'; -import DriveFolder from '../models/drive-folder'; -import { pack } from '../models/drive-file'; -import event, { publishDriveStream } from '../publishers/stream'; -import getAcct from '../acct/render'; -import config from '../config'; +import DriveFile, { IMetadata, getGridFSBucket } from '../../models/drive-file'; +import DriveFolder from '../../models/drive-folder'; +import { pack } from '../../models/drive-file'; +import event, { publishDriveStream } from '../../publishers/stream'; +import getAcct from '../../acct/render'; +import config from '../../config'; const gm = _gm.subClass({ imageMagick: true diff --git a/src/api/drive/upload-from-url.ts b/src/api/drive/upload-from-url.ts index f96af0f266..26c890d157 100644 --- a/src/api/drive/upload-from-url.ts +++ b/src/api/drive/upload-from-url.ts @@ -1,5 +1,5 @@ import * as URL from 'url'; -import { IDriveFile, validateFileName } from '../models/drive-file'; +import { IDriveFile, validateFileName } from '../../models/drive-file'; import create from './add-file'; import * as debug from 'debug'; import * as tmp from 'tmp'; diff --git a/src/api/post/create.ts b/src/api/post/create.ts index 8256cbc355..36819ec2b8 100644 --- a/src/api/post/create.ts +++ b/src/api/post/create.ts @@ -1,6 +1,5 @@ -import parseAcct from '../../acct/parse'; import Post, { pack, IPost } from '../../models/post'; -import User, { isLocalUser, isRemoteUser, IUser } from '../../models/user'; +import User, { isLocalUser, IUser } from '../../models/user'; import stream from '../../publishers/stream'; import Following from '../../models/following'; import { createHttp } from '../../queue'; @@ -25,14 +24,16 @@ export default async (user: IUser, content: { repost: IPost; media: IDriveFile[]; geo: any; - poll: any; + poll?: any; viaMobile: boolean; - tags: string[]; - cw: string; - visibility: string; + tags?: string[]; + cw?: string; + visibility?: string; uri?: string; app?: IApp; }) => new Promise(async (res, rej) => { + if (content.visibility == null) content.visibility = 'public'; + const tags = content.tags || []; let tokens = null; diff --git a/src/api/post/watch.ts b/src/api/post/watch.ts index 61ea444430..bbd9976f40 100644 --- a/src/api/post/watch.ts +++ b/src/api/post/watch.ts @@ -1,5 +1,5 @@ import * as mongodb from 'mongodb'; -import Watching from '../models/post-watching'; +import Watching from '../../models/post-watching'; export default async (me: mongodb.ObjectID, post: object) => { // 自分の投稿はwatchできない diff --git a/src/queue/processors/db/delete-post-dependents.ts b/src/queue/processors/db/delete-post-dependents.ts index 879c41ec9c..6de21eb053 100644 --- a/src/queue/processors/db/delete-post-dependents.ts +++ b/src/queue/processors/db/delete-post-dependents.ts @@ -1,9 +1,9 @@ -import Favorite from '../../models/favorite'; -import Notification from '../../models/notification'; -import PollVote from '../../models/poll-vote'; -import PostReaction from '../../models/post-reaction'; -import PostWatching from '../../models/post-watching'; -import Post from '../../models/post'; +import Favorite from '../../../models/favorite'; +import Notification from '../../../models/notification'; +import PollVote from '../../../models/poll-vote'; +import PostReaction from '../../../models/post-reaction'; +import PostWatching from '../../../models/post-watching'; +import Post from '../../../models/post'; export default async ({ data }) => Promise.all([ Favorite.remove({ postId: data._id }), diff --git a/src/queue/processors/http/process-inbox.ts b/src/queue/processors/http/process-inbox.ts index 82585d3a6b..c3074429f8 100644 --- a/src/queue/processors/http/process-inbox.ts +++ b/src/queue/processors/http/process-inbox.ts @@ -5,7 +5,6 @@ import parseAcct from '../../../acct/parse'; import User, { IRemoteUser } from '../../../models/user'; import act from '../../../remote/activitypub/act'; import resolvePerson from '../../../remote/activitypub/resolve-person'; -import Resolver from '../../../remote/activitypub/resolver'; // ユーザーのinboxにアクティビティが届いた時の処理 export default async (job: kue.Job, done): Promise => { diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index c486571fc1..f97832a989 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -36,17 +36,17 @@ export default async (actor, activity): Promise => { switch (object.type) { case 'Image': - createImage(resolver, object); + createImage(object); break; case 'Note': - createNote(resolver, object); + createNote(object); break; } /// - async function createImage(resolver: Resolver, image) { + async function createImage(image) { if ('attributedTo' in image && actor.account.uri !== image.attributedTo) { throw new Error('invalid image'); } @@ -54,7 +54,7 @@ export default async (actor, activity): Promise => { return await uploadFromUrl(image.url, actor); } - async function createNote(resolver: Resolver, note) { + async function createNote(note) { if ( ('attributedTo' in note && actor.account.uri !== note.attributedTo) || typeof note.id !== 'string' @@ -63,20 +63,29 @@ export default async (actor, activity): Promise => { } const media = []; - if ('attachment' in note) { note.attachment.forEach(async media => { - const created = await createImage(resolver, media); + const created = await createImage(media); media.push(created); }); } + let reply = null; + if ('inReplyTo' in note) { + const inReplyToPost = await Post.findOne({ uri: note.id || note }); + if (inReplyToPost) { + reply = inReplyToPost; + } else { + reply = await createNote(await resolver.resolve(note)); + } + } + const { window } = new JSDOM(note.content); - await createPost(actor, { + return await createPost(actor, { createdAt: new Date(note.published), media, - reply: undefined, + reply, repost: undefined, text: window.document.body.textContent, viaMobile: false, diff --git a/src/remote/activitypub/act/delete.ts b/src/remote/activitypub/act/delete.ts index f9eb4dd08d..334ca47edf 100644 --- a/src/remote/activitypub/act/delete.ts +++ b/src/remote/activitypub/act/delete.ts @@ -1,21 +1,28 @@ -import create from '../create'; -import deleteObject from '../delete'; +import Resolver from '../resolver'; +import Post from '../../../models/post'; +import { createDb } from '../../../queue'; -export default async (resolver, actor, activity) => { +export default async (actor, activity): Promise => { if ('actor' in activity && actor.account.uri !== activity.actor) { throw new Error(); } - const results = await create(resolver, actor, activity.object); + const resolver = new Resolver(); - await Promise.all(results.map(async promisedResult => { - const result = await promisedResult; - if (result === null) { - return; - } + const object = await resolver.resolve(activity); - await deleteObject(result); - })); + switch (object.type) { + case 'Note': + deleteNote(object); + break; + } - return null; + async function deleteNote(note) { + const post = await Post.findOneAndDelete({ uri: note.id }); + + createDb({ + type: 'deletePostDependents', + id: post._id + }).delay(65536).save(); + } }; diff --git a/src/remote/activitypub/act/undo.ts b/src/remote/activitypub/act/undo.ts index b3b83777d1..9d9f6b0359 100644 --- a/src/remote/activitypub/act/undo.ts +++ b/src/remote/activitypub/act/undo.ts @@ -7,7 +7,7 @@ export default async (actor, activity): Promise => { switch (activity.object.type) { case 'Follow': - unfollow(activity.object); + unfollow(actor, activity.object); break; } diff --git a/src/remote/activitypub/delete/index.ts b/src/remote/activitypub/delete/index.ts deleted file mode 100644 index bc9104284b..0000000000 --- a/src/remote/activitypub/delete/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -import deletePost from './post'; - -export default async ({ object }) => { - switch (object.$ref) { - case 'posts': - return deletePost(object); - } - - return null; -}; diff --git a/src/remote/activitypub/delete/post.ts b/src/remote/activitypub/delete/post.ts deleted file mode 100644 index f6c816647d..0000000000 --- a/src/remote/activitypub/delete/post.ts +++ /dev/null @@ -1,13 +0,0 @@ -import Post from '../../../models/post'; -import queue from '../../../queue'; - -export default async ({ $id }) => { - const promisedDeletion = Post.findOneAndDelete({ _id: $id }); - - await new Promise((resolve, reject) => queue.create('db', { - type: 'deletePostDependents', - id: $id - }).delay(65536).save(error => error ? reject(error) : resolve())); - - return promisedDeletion; -}; diff --git a/src/remote/activitypub/resolve-person.ts b/src/remote/activitypub/resolve-person.ts index 77d08398be..28162497f3 100644 --- a/src/remote/activitypub/resolve-person.ts +++ b/src/remote/activitypub/resolve-person.ts @@ -2,7 +2,6 @@ import { JSDOM } from 'jsdom'; import { toUnicode } from 'punycode'; import User, { validateUsername, isValidName, isValidDescription } from '../../models/user'; import webFinger from '../webfinger'; -import create from './create'; import Resolver from './resolver'; import uploadFromUrl from '../../api/drive/upload-from-url'; diff --git a/src/server/activitypub/inbox.ts b/src/server/activitypub/inbox.ts index 847dc19af6..b0015409a9 100644 --- a/src/server/activitypub/inbox.ts +++ b/src/server/activitypub/inbox.ts @@ -1,7 +1,7 @@ import * as bodyParser from 'body-parser'; import * as express from 'express'; import { parseRequest } from 'http-signature'; -import queue from '../../queue'; +import { createHttp } from '../../queue'; const app = express(); @@ -22,7 +22,7 @@ app.post('/@:user/inbox', bodyParser.json({ return res.sendStatus(401); } - queue.create('http', { + createHttp({ type: 'processInbox', activity: req.body, signature, From fc15249aa43471e73eb9dda46e1807084f4d2cd3 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 15:50:52 +0900 Subject: [PATCH 11/68] wip --- src/api/post/create.ts | 11 +++++++---- src/client/app/init.ts | 6 +----- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/api/post/create.ts b/src/api/post/create.ts index 36819ec2b8..5495117538 100644 --- a/src/api/post/create.ts +++ b/src/api/post/create.ts @@ -54,8 +54,7 @@ export default async (user: IUser, content: { }); } - // 投稿を作成 - const post = await Post.insert({ + const data: any = { createdAt: content.createdAt, mediaIds: content.media ? content.media.map(file => file._id) : [], replyId: content.reply ? content.reply._id : null, @@ -68,14 +67,18 @@ export default async (user: IUser, content: { userId: user._id, viaMobile: content.viaMobile, geo: content.geo || null, - uri: content.uri, appId: content.app ? content.app._id : null, visibility: content.visibility, // 以下非正規化データ _reply: content.reply ? { userId: content.reply.userId } : null, _repost: content.repost ? { userId: content.repost.userId } : null, - }); + }; + + if (content.uri != null) data.uri = content.uri; + + // 投稿を作成 + const post = await Post.insert(data); res(post); diff --git a/src/client/app/init.ts b/src/client/app/init.ts index 3e5c38961f..2fb8f15cf3 100644 --- a/src/client/app/init.ts +++ b/src/client/app/init.ts @@ -14,7 +14,7 @@ import ElementLocaleJa from 'element-ui/lib/locale/lang/ja'; import App from './app.vue'; import checkForUpdate from './common/scripts/check-for-update'; import MiOS, { API } from './common/mios'; -import { version, codename, hostname, lang } from './config'; +import { version, codename, lang } from './config'; let elementLocale; switch (lang) { @@ -60,10 +60,6 @@ console.info( window.clearTimeout((window as any).mkBootTimer); delete (window as any).mkBootTimer; -if (hostname != 'localhost') { - document.domain = hostname; -} - //#region Set lang attr const html = document.documentElement; html.setAttribute('lang', lang); From d3ed2761b9f007fae6977fdbf136619bce498c98 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 15:54:12 +0900 Subject: [PATCH 12/68] wip --- src/server/webfinger.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/server/webfinger.ts b/src/server/webfinger.ts index 20057da31f..fd7ebc3fb5 100644 --- a/src/server/webfinger.ts +++ b/src/server/webfinger.ts @@ -1,11 +1,12 @@ +import * as express from 'express'; + import config from '../config'; import parseAcct from '../acct/parse'; import User from '../models/user'; -const express = require('express'); const app = express(); -app.get('/.well-known/webfinger', async (req, res) => { +app.get('/.well-known/webfinger', async (req: express.Request, res: express.Response) => { if (typeof req.query.resource !== 'string') { return res.sendStatus(400); } @@ -34,13 +35,15 @@ app.get('/.well-known/webfinger', async (req, res) => { return res.json({ subject: `acct:${user.username}@${config.host}`, - links: [ - { - rel: 'self', - type: 'application/activity+json', - href: `${config.url}/@${user.username}` - } - ] + links: [{ + rel: 'self', + type: 'application/activity+json', + href: `${config.url}/@${user.username}` + }, { + rel: 'http://webfinger.net/rel/profile-page', + type: 'text/html', + href: `${config.url}/@${user.username}` + }] }); }); From f5c55d46b71af6d3f346192a014212c747d1321c Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 17:52:46 +0900 Subject: [PATCH 13/68] wip --- src/server/activitypub/inbox.ts | 4 +--- src/server/activitypub/outbox.ts | 3 +-- src/server/activitypub/post.ts | 3 +-- src/server/activitypub/publickey.ts | 3 +-- src/server/activitypub/user.ts | 3 +-- 5 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/server/activitypub/inbox.ts b/src/server/activitypub/inbox.ts index b0015409a9..1b6cc0c00a 100644 --- a/src/server/activitypub/inbox.ts +++ b/src/server/activitypub/inbox.ts @@ -3,9 +3,7 @@ import * as express from 'express'; import { parseRequest } from 'http-signature'; import { createHttp } from '../../queue'; -const app = express(); - -app.disable('x-powered-by'); +const app = express.Router(); app.post('/@:user/inbox', bodyParser.json({ type() { diff --git a/src/server/activitypub/outbox.ts b/src/server/activitypub/outbox.ts index 9ecb0c0711..976908d1f3 100644 --- a/src/server/activitypub/outbox.ts +++ b/src/server/activitypub/outbox.ts @@ -6,8 +6,7 @@ import config from '../../config'; import Post from '../../models/post'; import withUser from './with-user'; -const app = express(); -app.disable('x-powered-by'); +const app = express.Router(); app.get('/@:user/outbox', withUser(username => { return `${config.url}/@${username}/inbox`; diff --git a/src/server/activitypub/post.ts b/src/server/activitypub/post.ts index 91d91aeb95..355c603563 100644 --- a/src/server/activitypub/post.ts +++ b/src/server/activitypub/post.ts @@ -5,8 +5,7 @@ import parseAcct from '../../acct/parse'; import Post from '../../models/post'; import User from '../../models/user'; -const app = express(); -app.disable('x-powered-by'); +const app = express.Router(); app.get('/@:user/:post', async (req, res, next) => { const accepted = req.accepts(['html', 'application/activity+json', 'application/ld+json']); diff --git a/src/server/activitypub/publickey.ts b/src/server/activitypub/publickey.ts index c564c437e6..b48504927a 100644 --- a/src/server/activitypub/publickey.ts +++ b/src/server/activitypub/publickey.ts @@ -4,8 +4,7 @@ import render from '../../remote/activitypub/renderer/key'; import config from '../../config'; import withUser from './with-user'; -const app = express(); -app.disable('x-powered-by'); +const app = express.Router(); app.get('/@:user/publickey', withUser(username => { return `${config.url}/@${username}/publickey`; diff --git a/src/server/activitypub/user.ts b/src/server/activitypub/user.ts index baf2dc9a05..f054974510 100644 --- a/src/server/activitypub/user.ts +++ b/src/server/activitypub/user.ts @@ -11,8 +11,7 @@ const respond = withUser(username => `${config.url}/@${username}`, (user, req, r res.json(rendered); }); -const app = express(); -app.disable('x-powered-by'); +const app = express.Router(); app.get('/@:user', (req, res, next) => { const accepted = req.accepts(['html', 'application/activity+json', 'application/ld+json']); From 06347cd71e46ce2b991bc8b872cd0725c8862954 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 18:08:51 +0900 Subject: [PATCH 14/68] wip --- src/api/drive/upload-from-url.ts | 8 +++++++- src/index.ts | 4 ++++ src/remote/activitypub/resolve-person.ts | 10 +++++----- src/remote/activitypub/resolver.ts | 8 ++++++-- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/api/drive/upload-from-url.ts b/src/api/drive/upload-from-url.ts index 26c890d157..676586cd15 100644 --- a/src/api/drive/upload-from-url.ts +++ b/src/api/drive/upload-from-url.ts @@ -6,14 +6,18 @@ import * as tmp from 'tmp'; import * as fs from 'fs'; import * as request from 'request'; -const log = debug('misskey:common:drive:upload_from_url'); +const log = debug('misskey:drive:upload-from-url'); export default async (url, user, folderId = null, uri = null): Promise => { + log(`REQUESTED: ${url}`); + let name = URL.parse(url).pathname.split('/').pop(); if (!validateFileName(name)) { name = null; } + log(`name: ${name}`); + // Create temp file const path = await new Promise((res: (string) => void, rej) => { tmp.file((e, path) => { @@ -37,6 +41,8 @@ export default async (url, user, folderId = null, uri = null): Promise { if (e) log(e.stack); diff --git a/src/index.ts b/src/index.ts index 29c4f3431a..e35c917a44 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,6 +30,10 @@ const ev = new Xev(); process.title = 'Misskey'; +if (process.env.NODE_ENV != 'production') { + process.env.DEBUG = 'misskey:*'; +} + // https://github.com/Automattic/kue/issues/822 require('events').EventEmitter.prototype._maxListeners = 256; diff --git a/src/remote/activitypub/resolve-person.ts b/src/remote/activitypub/resolve-person.ts index 28162497f3..c288a2f009 100644 --- a/src/remote/activitypub/resolve-person.ts +++ b/src/remote/activitypub/resolve-person.ts @@ -31,7 +31,7 @@ export default async (value, verifier?: string) => { const user = await User.insert({ avatarId: null, bannerId: null, - createdAt: Date.parse(object.published), + createdAt: Date.parse(object.published) || null, description: summaryDOM.textContent, followersCount: 0, followingCount: 0, @@ -55,14 +55,14 @@ export default async (value, verifier?: string) => { const [avatarId, bannerId] = await Promise.all([ object.icon, object.image - ].map(async url => { - if (url === undefined) { + ].map(async img => { + if (img === undefined) { return null; } - const img = await uploadFromUrl(url, user); + const file = await uploadFromUrl(img.url, user); - return img._id; + return file._id; })); User.update({ _id: user._id }, { $set: { avatarId, bannerId } }); diff --git a/src/remote/activitypub/resolver.ts b/src/remote/activitypub/resolver.ts index de0bba2687..09a6e70056 100644 --- a/src/remote/activitypub/resolver.ts +++ b/src/remote/activitypub/resolver.ts @@ -1,6 +1,8 @@ -import { IObject } from "./type"; +import * as request from 'request-promise-native'; +import * as debug from 'debug'; +import { IObject } from './type'; -const request = require('request-promise-native'); +const log = debug('misskey:activitypub:resolver'); export default class Resolver { private history: Set; @@ -57,6 +59,8 @@ export default class Resolver { throw new Error('invalid response'); } + log(`resolved: ${JSON.stringify(object)}`); + return object; } } From 7403f38fb43b0ad747236061a591cbf94e198ba6 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 18:43:06 +0900 Subject: [PATCH 15/68] wip --- src/api/post/create.ts | 15 ++++++++------- src/index.ts | 2 +- src/queue/index.ts | 8 +++++++- src/queue/processors/http/deliver.ts | 9 ++++++++- src/queue/processors/http/index.ts | 16 ++++++++++++---- .../processors/http/report-github-failure.ts | 6 +++--- src/remote/activitypub/resolver.ts | 2 +- src/remote/request.ts | 8 ++++++++ src/server/api/endpoints/following/create.ts | 11 ++--------- 9 files changed, 50 insertions(+), 27 deletions(-) diff --git a/src/api/post/create.ts b/src/api/post/create.ts index 5495117538..dbeb87ae86 100644 --- a/src/api/post/create.ts +++ b/src/api/post/create.ts @@ -18,20 +18,21 @@ import html from '../../text/html'; import { IApp } from '../../models/app'; export default async (user: IUser, content: { - createdAt: Date; - text: string; - reply: IPost; - repost: IPost; - media: IDriveFile[]; - geo: any; + createdAt?: Date; + text?: string; + reply?: IPost; + repost?: IPost; + media?: IDriveFile[]; + geo?: any; poll?: any; - viaMobile: boolean; + viaMobile?: boolean; tags?: string[]; cw?: string; visibility?: string; uri?: string; app?: IApp; }) => new Promise(async (res, rej) => { + if (content.createdAt == null) content.createdAt = new Date(); if (content.visibility == null) content.visibility = 'public'; const tags = content.tags || []; diff --git a/src/index.ts b/src/index.ts index e35c917a44..f45bcaa6ad 100644 --- a/src/index.ts +++ b/src/index.ts @@ -103,7 +103,7 @@ async function workerMain(opt) { if (!opt['only-server']) { // start processor - require('./processor').default(); + require('./queue').default(); } // Send a 'ready' message to parent process diff --git a/src/queue/index.ts b/src/queue/index.ts index c8c436b18c..86600dc265 100644 --- a/src/queue/index.ts +++ b/src/queue/index.ts @@ -1,8 +1,12 @@ import { createQueue } from 'kue'; +import * as debug from 'debug'; + import config from '../config'; import db from './processors/db'; import http from './processors/http'; +const log = debug('misskey:queue'); + const queue = createQueue({ redis: { port: config.redis.port, @@ -12,6 +16,8 @@ const queue = createQueue({ }); export function createHttp(data) { + log(`HTTP job created: ${JSON.stringify(data)}`); + return queue .create('http', data) .attempts(16) @@ -22,7 +28,7 @@ export function createDb(data) { return queue.create('db', data); } -export function process() { +export default function() { queue.process('db', db); /* diff --git a/src/queue/processors/http/deliver.ts b/src/queue/processors/http/deliver.ts index 1700063a5d..da7e8bc368 100644 --- a/src/queue/processors/http/deliver.ts +++ b/src/queue/processors/http/deliver.ts @@ -3,5 +3,12 @@ import * as kue from 'kue'; import request from '../../../remote/request'; export default async (job: kue.Job, done): Promise => { - await request(job.data.user, job.data.to, job.data.content); + try { + await request(job.data.user, job.data.to, job.data.content); + done(); + } catch (e) { + console.warn(`deliver failed: ${e}`); + + done(e); + } }; diff --git a/src/queue/processors/http/index.ts b/src/queue/processors/http/index.ts index 06c6b1d1aa..3d7d941b1a 100644 --- a/src/queue/processors/http/index.ts +++ b/src/queue/processors/http/index.ts @@ -3,9 +3,17 @@ import processInbox from './process-inbox'; import reportGitHubFailure from './report-github-failure'; const handlers = { - deliver, - processInbox, - reportGitHubFailure, + deliver, + processInbox, + reportGitHubFailure }; -export default (job, done) => handlers[job.data.type](job).then(() => done(), done); +export default (job, done) => { + const handler = handlers[job.data.type]; + + if (handler) { + handler(job).then(() => done(), done); + } else { + console.warn(`Unknown job: ${job.data.type}`); + } +}; diff --git a/src/queue/processors/http/report-github-failure.ts b/src/queue/processors/http/report-github-failure.ts index 4f6f5ccee5..e747d062d3 100644 --- a/src/queue/processors/http/report-github-failure.ts +++ b/src/queue/processors/http/report-github-failure.ts @@ -1,6 +1,6 @@ import * as request from 'request-promise-native'; -import User from '../../models/user'; -const createPost = require('../../server/api/endpoints/posts/create'); +import User from '../../../models/user'; +import createPost from '../../../api/post/create'; export default async ({ data }) => { const asyncBot = User.findOne({ _id: data.userId }); @@ -20,5 +20,5 @@ export default async ({ data }) => { `**⚠️BUILD STILL FAILED⚠️**: ?[${data.message}](${data.htmlUrl})` : `**🚨BUILD FAILED🚨**: →→→?[${data.message}](${data.htmlUrl})←←←`; - createPost({ text }, await asyncBot); + createPost(await asyncBot, { text }); }; diff --git a/src/remote/activitypub/resolver.ts b/src/remote/activitypub/resolver.ts index 09a6e70056..38639c6813 100644 --- a/src/remote/activitypub/resolver.ts +++ b/src/remote/activitypub/resolver.ts @@ -59,7 +59,7 @@ export default class Resolver { throw new Error('invalid response'); } - log(`resolved: ${JSON.stringify(object)}`); + log(`resolved: ${JSON.stringify(object, null, 2)}`); return object; } diff --git a/src/remote/request.ts b/src/remote/request.ts index 72262cbf61..a375aebfbb 100644 --- a/src/remote/request.ts +++ b/src/remote/request.ts @@ -1,9 +1,15 @@ import { request } from 'https'; import { sign } from 'http-signature'; import { URL } from 'url'; +import * as debug from 'debug'; + import config from '../config'; +const log = debug('misskey:activitypub:deliver'); + export default ({ account, username }, url, object) => new Promise((resolve, reject) => { + log(`--> ${url}`); + const { protocol, hostname, port, pathname, search } = new URL(url); const req = request({ @@ -14,6 +20,8 @@ export default ({ account, username }, url, object) => new Promise((resolve, rej path: pathname + search, }, res => { res.on('end', () => { + log(`${url} --> ${res.statusCode}`); + if (res.statusCode >= 200 && res.statusCode < 300) { resolve(); } else { diff --git a/src/server/api/endpoints/following/create.ts b/src/server/api/endpoints/following/create.ts index e568595215..fae686ce54 100644 --- a/src/server/api/endpoints/following/create.ts +++ b/src/server/api/endpoints/following/create.ts @@ -4,7 +4,7 @@ import $ from 'cafy'; import User from '../../../../models/user'; import Following from '../../../../models/following'; -import queue from '../../../../queue'; +import create from '../../../../api/following/create'; /** * Follow a user @@ -50,15 +50,8 @@ module.exports = (params, user) => new Promise(async (res, rej) => { } // Create following - const { _id } = await Following.insert({ - createdAt: new Date(), - followerId: follower._id, - followeeId: followee._id - }); - - queue.create('http', { type: 'follow', following: _id }).save(); + create(follower, followee); // Send response res(); - }); From fd87a63e573581544a169143fad4ef2180be22bd Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 18:50:52 +0900 Subject: [PATCH 16/68] wip --- src/remote/activitypub/resolve-person.ts | 2 +- src/remote/resolve-user.ts | 2 +- src/server/api/endpoints/users/show.ts | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/remote/activitypub/resolve-person.ts b/src/remote/activitypub/resolve-person.ts index c288a2f009..b979bb1cd2 100644 --- a/src/remote/activitypub/resolve-person.ts +++ b/src/remote/activitypub/resolve-person.ts @@ -15,7 +15,7 @@ export default async (value, verifier?: string) => { object.type !== 'Person' || typeof object.preferredUsername !== 'string' || !validateUsername(object.preferredUsername) || - !isValidName(object.name) || + (object.name != '' && !isValidName(object.name)) || !isValidDescription(object.summary) ) { throw new Error('invalid person'); diff --git a/src/remote/resolve-user.ts b/src/remote/resolve-user.ts index 48219e8cb3..9e1ae51952 100644 --- a/src/remote/resolve-user.ts +++ b/src/remote/resolve-user.ts @@ -16,7 +16,7 @@ export default async (username, host, option) => { const finger = await webFinger(acctLower, acctLower); const self = finger.links.find(link => link.rel && link.rel.toLowerCase() === 'self'); if (!self) { - throw new Error(); + throw new Error('self link not found'); } user = await resolvePerson(self.href, acctLower); diff --git a/src/server/api/endpoints/users/show.ts b/src/server/api/endpoints/users/show.ts index 2b02799378..d272ce4639 100644 --- a/src/server/api/endpoints/users/show.ts +++ b/src/server/api/endpoints/users/show.ts @@ -37,7 +37,8 @@ module.exports = (params, me) => new Promise(async (res, rej) => { if (typeof host === 'string') { try { user = await resolveRemoteUser(username, host, cursorOption); - } catch (exception) { + } catch (e) { + console.warn(`failed to resolve remote user: ${e}`); return rej('failed to resolve remote user'); } } else { From 2a80fdeafe295896b99a499b499873d7d8b55a3d Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 19:19:00 +0900 Subject: [PATCH 17/68] wip --- src/remote/activitypub/act/create.ts | 46 ++++++++++++++----------- src/remote/activitypub/act/index.ts | 4 +++ src/remote/activitypub/renderer/note.ts | 13 ++++--- 3 files changed, 38 insertions(+), 25 deletions(-) diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index f97832a989..80afb61bd7 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -1,11 +1,13 @@ import { JSDOM } from 'jsdom'; +import * as debug from 'debug'; import Resolver from '../resolver'; -import DriveFile from '../../../models/drive-file'; import Post from '../../../models/post'; import uploadFromUrl from '../../../api/drive/upload-from-url'; import createPost from '../../../api/post/create'; +const log = debug('misskey:activitypub'); + export default async (actor, activity): Promise => { if ('actor' in activity && actor.account.uri !== activity.actor) { throw new Error('invalid actor'); @@ -13,26 +15,20 @@ export default async (actor, activity): Promise => { const uri = activity.id || activity; - try { - await Promise.all([ - DriveFile.findOne({ 'metadata.uri': uri }).then(file => { - if (file !== null) { - throw new Error(); - } - }, () => {}), - Post.findOne({ uri }).then(post => { - if (post !== null) { - throw new Error(); - } - }, () => {}) - ]); - } catch (object) { - throw new Error(`already registered: ${uri}`); - } + log(`Create: ${uri}`); + + // TODO: 同じURIをもつものが既に登録されていないかチェック const resolver = new Resolver(); - const object = await resolver.resolve(activity); + let object; + + try { + object = await resolver.resolve(activity.object); + } catch (e) { + log(`Resolve failed: ${e}`); + throw e; + } switch (object.type) { case 'Image': @@ -42,15 +38,22 @@ export default async (actor, activity): Promise => { case 'Note': createNote(object); break; + + default: + console.warn(`Unknown type: ${object.type}`); + break; } /// async function createImage(image) { if ('attributedTo' in image && actor.account.uri !== image.attributedTo) { + log(`invalid image: ${JSON.stringify(image, null, 2)}`); throw new Error('invalid image'); } + log(`Creating the Image: ${uri}`); + return await uploadFromUrl(image.url, actor); } @@ -59,11 +62,14 @@ export default async (actor, activity): Promise => { ('attributedTo' in note && actor.account.uri !== note.attributedTo) || typeof note.id !== 'string' ) { + log(`invalid note: ${JSON.stringify(note, null, 2)}`); throw new Error('invalid note'); } + log(`Creating the Note: ${uri}`); + const media = []; - if ('attachment' in note) { + if ('attachment' in note && note.attachment != null) { note.attachment.forEach(async media => { const created = await createImage(media); media.push(created); @@ -71,7 +77,7 @@ export default async (actor, activity): Promise => { } let reply = null; - if ('inReplyTo' in note) { + if ('inReplyTo' in note && note.inReplyTo != null) { const inReplyToPost = await Post.findOne({ uri: note.id || note }); if (inReplyToPost) { reply = inReplyToPost; diff --git a/src/remote/activitypub/act/index.ts b/src/remote/activitypub/act/index.ts index f22500acef..5840227098 100644 --- a/src/remote/activitypub/act/index.ts +++ b/src/remote/activitypub/act/index.ts @@ -18,6 +18,10 @@ export default async (actor, activity: IObject): Promise => { await follow(actor, activity); break; + case 'Accept': + // noop + break; + case 'Undo': await undo(actor, activity); break; diff --git a/src/remote/activitypub/renderer/note.ts b/src/remote/activitypub/renderer/note.ts index 43531b121a..e45b10215a 100644 --- a/src/remote/activitypub/renderer/note.ts +++ b/src/remote/activitypub/renderer/note.ts @@ -2,11 +2,14 @@ import renderDocument from './document'; import renderHashtag from './hashtag'; import config from '../../../config'; import DriveFile from '../../../models/drive-file'; -import Post from '../../../models/post'; -import User from '../../../models/user'; +import Post, { IPost } from '../../../models/post'; +import User, { IUser } from '../../../models/user'; + +export default async (user: IUser, post: IPost) => { + const promisedFiles = post.mediaIds + ? DriveFile.find({ _id: { $in: post.mediaIds } }) + : Promise.resolve([]); -export default async (user, post) => { - const promisedFiles = DriveFile.find({ _id: { $in: post.mediaIds } }); let inReplyTo; if (post.replyId) { @@ -39,6 +42,6 @@ export default async (user, post) => { cc: `${attributedTo}/followers`, inReplyTo, attachment: (await promisedFiles).map(renderDocument), - tag: post.tags.map(renderHashtag) + tag: (post.tags || []).map(renderHashtag) }; }; From a6abcd1aa5edca98d8cc2b974cc63b06b3dd75bf Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 19:23:42 +0900 Subject: [PATCH 18/68] wip --- src/remote/activitypub/act/create.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index 80afb61bd7..7d5a9d427a 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -78,7 +78,7 @@ export default async (actor, activity): Promise => { let reply = null; if ('inReplyTo' in note && note.inReplyTo != null) { - const inReplyToPost = await Post.findOne({ uri: note.id || note }); + const inReplyToPost = await Post.findOne({ uri: note.inReplyTo.id || note.inReplyTo }); if (inReplyToPost) { reply = inReplyToPost; } else { From 7c86d096ac6593c38496d84453490a422651dd25 Mon Sep 17 00:00:00 2001 From: "greenkeeper[bot]" Date: Thu, 5 Apr 2018 11:24:06 +0000 Subject: [PATCH 19/68] fix(package): update webpack to version 4.5.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 38d96117ce..45ceaaf887 100644 --- a/package.json +++ b/package.json @@ -209,7 +209,7 @@ "vuedraggable": "2.16.0", "web-push": "3.3.0", "webfinger.js": "2.6.6", - "webpack": "4.4.1", + "webpack": "4.5.0", "webpack-cli": "2.0.13", "webpack-replace-loader": "1.3.0", "websocket": "1.0.25", From 5f8ab584464386b67bff6f9b7f60525e3e50cecc Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 22:49:41 +0900 Subject: [PATCH 20/68] wip --- src/remote/activitypub/act/create.ts | 106 ++++++++++++----------- src/remote/activitypub/act/index.ts | 3 +- src/remote/activitypub/resolve-person.ts | 2 +- src/remote/activitypub/resolver.ts | 4 + 4 files changed, 62 insertions(+), 53 deletions(-) diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index 7d5a9d427a..9669348d58 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -5,10 +5,12 @@ import Resolver from '../resolver'; import Post from '../../../models/post'; import uploadFromUrl from '../../../api/drive/upload-from-url'; import createPost from '../../../api/post/create'; +import { IRemoteUser, isRemoteUser } from '../../../models/user'; +import resolvePerson from '../resolve-person'; const log = debug('misskey:activitypub'); -export default async (actor, activity): Promise => { +export default async (actor: IRemoteUser, activity): Promise => { if ('actor' in activity && actor.account.uri !== activity.actor) { throw new Error('invalid actor'); } @@ -32,71 +34,73 @@ export default async (actor, activity): Promise => { switch (object.type) { case 'Image': - createImage(object); + createImage(resolver, actor, object); break; case 'Note': - createNote(object); + createNote(resolver, actor, object); break; default: console.warn(`Unknown type: ${object.type}`); break; } +}; - /// - - async function createImage(image) { - if ('attributedTo' in image && actor.account.uri !== image.attributedTo) { - log(`invalid image: ${JSON.stringify(image, null, 2)}`); - throw new Error('invalid image'); - } - - log(`Creating the Image: ${uri}`); - - return await uploadFromUrl(image.url, actor); +async function createImage(resolver: Resolver, actor: IRemoteUser, image) { + if ('attributedTo' in image && actor.account.uri !== image.attributedTo) { + log(`invalid image: ${JSON.stringify(image, null, 2)}`); + throw new Error('invalid image'); } - async function createNote(note) { - if ( - ('attributedTo' in note && actor.account.uri !== note.attributedTo) || - typeof note.id !== 'string' - ) { - log(`invalid note: ${JSON.stringify(note, null, 2)}`); - throw new Error('invalid note'); - } + log(`Creating the Image: ${image.id}`); - log(`Creating the Note: ${uri}`); + return await uploadFromUrl(image.url, actor); +} - const media = []; - if ('attachment' in note && note.attachment != null) { - note.attachment.forEach(async media => { - const created = await createImage(media); - media.push(created); - }); - } +async function createNote(resolver: Resolver, actor: IRemoteUser, note) { + if ( + ('attributedTo' in note && actor.account.uri !== note.attributedTo) || + typeof note.id !== 'string' + ) { + log(`invalid note: ${JSON.stringify(note, null, 2)}`); + throw new Error('invalid note'); + } - let reply = null; - if ('inReplyTo' in note && note.inReplyTo != null) { - const inReplyToPost = await Post.findOne({ uri: note.inReplyTo.id || note.inReplyTo }); - if (inReplyToPost) { - reply = inReplyToPost; - } else { - reply = await createNote(await resolver.resolve(note)); - } - } + log(`Creating the Note: ${note.id}`); - const { window } = new JSDOM(note.content); - - return await createPost(actor, { - createdAt: new Date(note.published), - media, - reply, - repost: undefined, - text: window.document.body.textContent, - viaMobile: false, - geo: undefined, - uri: note.id + const media = []; + if ('attachment' in note && note.attachment != null) { + note.attachment.forEach(async media => { + const created = await createImage(resolver, note.actor, media); + media.push(created); }); } -}; + + let reply = null; + if ('inReplyTo' in note && note.inReplyTo != null) { + const inReplyToPost = await Post.findOne({ uri: note.inReplyTo.id || note.inReplyTo }); + if (inReplyToPost) { + reply = inReplyToPost; + } else { + const inReplyTo = await resolver.resolve(note.inReplyTo) as any; + const actor = await resolvePerson(inReplyTo.attributedTo); + if (isRemoteUser(actor)) { + reply = await createNote(resolver, actor, inReplyTo); + } + } + } + + const { window } = new JSDOM(note.content); + + return await createPost(actor, { + createdAt: new Date(note.published), + media, + reply, + repost: undefined, + text: window.document.body.textContent, + viaMobile: false, + geo: undefined, + uri: note.id + }); +} diff --git a/src/remote/activitypub/act/index.ts b/src/remote/activitypub/act/index.ts index 5840227098..f58505b0ad 100644 --- a/src/remote/activitypub/act/index.ts +++ b/src/remote/activitypub/act/index.ts @@ -3,8 +3,9 @@ import performDeleteActivity from './delete'; import follow from './follow'; import undo from './undo'; import { IObject } from '../type'; +import { IUser } from '../../../models/user'; -export default async (actor, activity: IObject): Promise => { +export default async (actor: IUser, activity: IObject): Promise => { switch (activity.type) { case 'Create': await create(actor, activity); diff --git a/src/remote/activitypub/resolve-person.ts b/src/remote/activitypub/resolve-person.ts index b979bb1cd2..2bf7a13540 100644 --- a/src/remote/activitypub/resolve-person.ts +++ b/src/remote/activitypub/resolve-person.ts @@ -11,7 +11,7 @@ export default async (value, verifier?: string) => { const object = await resolver.resolve(value) as any; if ( - object === null || + object == null || object.type !== 'Person' || typeof object.preferredUsername !== 'string' || !validateUsername(object.preferredUsername) || diff --git a/src/remote/activitypub/resolver.ts b/src/remote/activitypub/resolver.ts index 38639c6813..4a97e2ef66 100644 --- a/src/remote/activitypub/resolver.ts +++ b/src/remote/activitypub/resolver.ts @@ -33,6 +33,10 @@ export default class Resolver { } public async resolve(value): Promise { + if (value == null) { + throw new Error('resolvee is null (or undefined)'); + } + if (typeof value !== 'string') { return value; } From 30bd467b7143502b5aacc86de7e724ac4aa9c6c3 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 23:19:47 +0900 Subject: [PATCH 21/68] wip --- src/api/post/create.ts | 40 +++++++++++++++------------- src/remote/activitypub/act/create.ts | 6 ++--- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/src/api/post/create.ts b/src/api/post/create.ts index dbeb87ae86..7b7fceda2a 100644 --- a/src/api/post/create.ts +++ b/src/api/post/create.ts @@ -31,7 +31,7 @@ export default async (user: IUser, content: { visibility?: string; uri?: string; app?: IApp; -}) => new Promise(async (res, rej) => { +}, silent = false) => new Promise(async (res, rej) => { if (content.createdAt == null) content.createdAt = new Date(); if (content.visibility == null) content.visibility = 'public'; @@ -120,26 +120,28 @@ export default async (user: IUser, content: { _id: false }); - const note = await renderNote(user, post); - const content = renderCreate(note); - content['@context'] = context; + if (!silent) { + const note = await renderNote(user, post); + const content = renderCreate(note); + content['@context'] = context; - Promise.all(followers.map(({ follower }) => { - if (isLocalUser(follower)) { - // Publish event to followers stream - stream(follower._id, 'post', postObj); - } else { - // フォロワーがリモートユーザーかつ投稿者がローカルユーザーなら投稿を配信 - if (isLocalUser(user)) { - createHttp({ - type: 'deliver', - user, - content, - to: follower.account.inbox - }).save(); + Promise.all(followers.map(({ follower }) => { + if (isLocalUser(follower)) { + // Publish event to followers stream + stream(follower._id, 'post', postObj); + } else { + // フォロワーがリモートユーザーかつ投稿者がローカルユーザーなら投稿を配信 + if (isLocalUser(user)) { + createHttp({ + type: 'deliver', + user, + content, + to: follower.account.inbox + }).save(); + } } - } - })); + })); + } } // チャンネルへの投稿 diff --git a/src/remote/activitypub/act/create.ts b/src/remote/activitypub/act/create.ts index 9669348d58..fe58f58f87 100644 --- a/src/remote/activitypub/act/create.ts +++ b/src/remote/activitypub/act/create.ts @@ -58,7 +58,7 @@ async function createImage(resolver: Resolver, actor: IRemoteUser, image) { return await uploadFromUrl(image.url, actor); } -async function createNote(resolver: Resolver, actor: IRemoteUser, note) { +async function createNote(resolver: Resolver, actor: IRemoteUser, note, silent = false) { if ( ('attributedTo' in note && actor.account.uri !== note.attributedTo) || typeof note.id !== 'string' @@ -86,7 +86,7 @@ async function createNote(resolver: Resolver, actor: IRemoteUser, note) { const inReplyTo = await resolver.resolve(note.inReplyTo) as any; const actor = await resolvePerson(inReplyTo.attributedTo); if (isRemoteUser(actor)) { - reply = await createNote(resolver, actor, inReplyTo); + reply = await createNote(resolver, actor, inReplyTo, true); } } } @@ -102,5 +102,5 @@ async function createNote(resolver: Resolver, actor: IRemoteUser, note) { viaMobile: false, geo: undefined, uri: note.id - }); + }, silent); } From 0de40f3a76ef159b099a90b65ded3073dbbd2b78 Mon Sep 17 00:00:00 2001 From: syuilo Date: Thu, 5 Apr 2018 23:24:51 +0900 Subject: [PATCH 22/68] wip --- src/api/following/create.ts | 16 +++------------- src/api/following/delete.ts | 9 ++------- src/api/post/create.ts | 9 ++------- src/queue/index.ts | 9 +++++++++ 4 files changed, 16 insertions(+), 27 deletions(-) diff --git a/src/api/following/create.ts b/src/api/following/create.ts index 353a6c8920..d919f4487f 100644 --- a/src/api/following/create.ts +++ b/src/api/following/create.ts @@ -7,7 +7,7 @@ import notify from '../../publishers/notify'; import context from '../../remote/activitypub/renderer/context'; import renderFollow from '../../remote/activitypub/renderer/follow'; import renderAccept from '../../remote/activitypub/renderer/accept'; -import { createHttp } from '../../queue'; +import { deliver } from '../../queue'; export default async function(follower: IUser, followee: IUser, activity?) { const following = await Following.insert({ @@ -60,23 +60,13 @@ export default async function(follower: IUser, followee: IUser, activity?) { const content = renderFollow(follower, followee); content['@context'] = context; - createHttp({ - type: 'deliver', - user: follower, - content, - to: followee.account.inbox - }).save(); + deliver(follower, content, followee.account.inbox).save(); } if (isRemoteUser(follower) && isLocalUser(followee)) { const content = renderAccept(activity); content['@context'] = context; - createHttp({ - type: 'deliver', - user: followee, - content, - to: follower.account.inbox - }).save(); + deliver(followee, content, follower.account.inbox).save(); } } diff --git a/src/api/following/delete.ts b/src/api/following/delete.ts index 4cdff7ce1b..364a4803b9 100644 --- a/src/api/following/delete.ts +++ b/src/api/following/delete.ts @@ -6,7 +6,7 @@ import event from '../../publishers/stream'; import context from '../../remote/activitypub/renderer/context'; import renderFollow from '../../remote/activitypub/renderer/follow'; import renderUndo from '../../remote/activitypub/renderer/undo'; -import { createHttp } from '../../queue'; +import { deliver } from '../../queue'; export default async function(follower: IUser, followee: IUser, activity?) { const following = await Following.findOne({ @@ -59,11 +59,6 @@ export default async function(follower: IUser, followee: IUser, activity?) { const content = renderUndo(renderFollow(follower, followee)); content['@context'] = context; - createHttp({ - type: 'deliver', - user: follower, - content, - to: followee.account.inbox - }).save(); + deliver(follower, content, followee.account.inbox).save(); } } diff --git a/src/api/post/create.ts b/src/api/post/create.ts index 7b7fceda2a..9723dbe452 100644 --- a/src/api/post/create.ts +++ b/src/api/post/create.ts @@ -2,7 +2,7 @@ import Post, { pack, IPost } from '../../models/post'; import User, { isLocalUser, IUser } from '../../models/user'; import stream from '../../publishers/stream'; import Following from '../../models/following'; -import { createHttp } from '../../queue'; +import { deliver } from '../../queue'; import renderNote from '../../remote/activitypub/renderer/note'; import renderCreate from '../../remote/activitypub/renderer/create'; import context from '../../remote/activitypub/renderer/context'; @@ -132,12 +132,7 @@ export default async (user: IUser, content: { } else { // フォロワーがリモートユーザーかつ投稿者がローカルユーザーなら投稿を配信 if (isLocalUser(user)) { - createHttp({ - type: 'deliver', - user, - content, - to: follower.account.inbox - }).save(); + deliver(user, content, follower.account.inbox).save(); } } })); diff --git a/src/queue/index.ts b/src/queue/index.ts index 86600dc265..689985e0ed 100644 --- a/src/queue/index.ts +++ b/src/queue/index.ts @@ -28,6 +28,15 @@ export function createDb(data) { return queue.create('db', data); } +export function deliver(user, content, to) { + return createHttp({ + type: 'deliver', + user, + content, + to + }); +} + export default function() { queue.process('db', db); From f0e8e6392b5ef99488ea0bbecbf9029e30ef0cfa Mon Sep 17 00:00:00 2001 From: Akihiko Odaki Date: Fri, 6 Apr 2018 01:36:34 +0900 Subject: [PATCH 23/68] Allow name property of user to be null --- src/client/app/ch/tags/channel.tag | 10 ++++++-- .../common/scripts/compose-notification.ts | 13 ++++++----- .../common/views/components/autocomplete.vue | 4 +++- .../app/common/views/components/messaging.vue | 6 +++-- .../views/components/welcome-timeline.vue | 4 +++- .../views/components/followers-window.vue | 11 +++++++-- .../views/components/following-window.vue | 11 +++++++-- .../views/components/friends-maker.vue | 4 +++- .../components/messaging-room-window.vue | 6 ++++- .../views/components/notifications.vue | 16 +++++++------ .../views/components/post-detail.sub.vue | 6 ++++- .../desktop/views/components/post-detail.vue | 11 +++++++-- .../desktop/views/components/post-preview.vue | 6 ++++- .../views/components/posts.post.sub.vue | 6 ++++- .../desktop/views/components/posts.post.vue | 6 ++++- .../views/components/settings.mute.vue | 6 +++-- .../views/components/settings.profile.vue | 4 ++-- .../desktop/views/components/ui.header.vue | 9 +++++++- .../views/components/users-list.item.vue | 6 ++++- .../desktop/views/pages/messaging-room.vue | 3 ++- .../pages/user/user.followers-you-know.vue | 6 +++-- .../desktop/views/pages/user/user.header.vue | 6 ++++- .../app/desktop/views/pages/user/user.vue | 3 ++- .../views/widgets/channel.channel.post.vue | 6 ++++- .../app/desktop/views/widgets/profile.vue | 9 +++++++- .../app/desktop/views/widgets/users.vue | 4 +++- .../views/components/notification-preview.vue | 23 +++++++++++++------ .../mobile/views/components/notification.vue | 15 ++++++++---- .../app/mobile/views/components/post-card.vue | 6 ++++- .../views/components/post-detail.sub.vue | 6 ++++- .../mobile/views/components/post-detail.vue | 11 +++++++-- .../mobile/views/components/post-preview.vue | 6 ++++- .../app/mobile/views/components/post.sub.vue | 6 ++++- .../app/mobile/views/components/post.vue | 11 +++++++-- .../app/mobile/views/components/ui.header.vue | 8 ++++++- .../app/mobile/views/components/ui.nav.vue | 8 ++++++- .../app/mobile/views/components/user-card.vue | 6 ++++- .../mobile/views/components/user-preview.vue | 6 ++++- .../app/mobile/views/pages/followers.vue | 10 ++++++-- .../app/mobile/views/pages/following.vue | 10 ++++++-- .../app/mobile/views/pages/messaging-room.vue | 10 ++++++-- .../mobile/views/pages/profile-setting.vue | 4 ++-- .../app/mobile/views/pages/settings.vue | 8 ++++++- src/client/app/mobile/views/pages/user.vue | 11 +++++---- .../pages/user/home.followers-you-know.vue | 8 ++++++- .../app/mobile/views/widgets/profile.vue | 10 +++++++- src/models/user.ts | 6 ++--- src/othello/ai/back.ts | 17 +++++++------- src/renderers/get-notification-summary.ts | 15 ++++++------ src/renderers/get-user-summary.ts | 3 ++- src/server/api/bot/core.ts | 7 +++--- src/server/api/bot/interfaces/line.ts | 5 ++-- 52 files changed, 311 insertions(+), 107 deletions(-) diff --git a/src/client/app/ch/tags/channel.tag b/src/client/app/ch/tags/channel.tag index 1ebc3ccebc..4856728dec 100644 --- a/src/client/app/ch/tags/channel.tag +++ b/src/client/app/ch/tags/channel.tag @@ -165,7 +165,7 @@
{ post.index }: - { post.user.name } + { getUserName(post.user) } ID:{ acct } @@ -230,10 +230,12 @@ diff --git a/src/client/app/common/scripts/compose-notification.ts b/src/client/app/common/scripts/compose-notification.ts index ebc15952f6..e99d502960 100644 --- a/src/client/app/common/scripts/compose-notification.ts +++ b/src/client/app/common/scripts/compose-notification.ts @@ -1,5 +1,6 @@ import getPostSummary from '../../../../renderers/get-post-summary'; import getReactionEmoji from '../../../../renderers/get-reaction-emoji'; +import getUserName from '../../../../renderers/get-user-name'; type Notification = { title: string; @@ -21,35 +22,35 @@ export default function(type, data): Notification { case 'mention': return { - title: `${data.user.name}さんから:`, + title: `${getUserName(data.user)}さんから:`, body: getPostSummary(data), icon: data.user.avatarUrl + '?thumbnail&size=64' }; case 'reply': return { - title: `${data.user.name}さんから返信:`, + title: `${getUserName(data.user)}さんから返信:`, body: getPostSummary(data), icon: data.user.avatarUrl + '?thumbnail&size=64' }; case 'quote': return { - title: `${data.user.name}さんが引用:`, + title: `${getUserName(data.user)}さんが引用:`, body: getPostSummary(data), icon: data.user.avatarUrl + '?thumbnail&size=64' }; case 'reaction': return { - title: `${data.user.name}: ${getReactionEmoji(data.reaction)}:`, + title: `${getUserName(data.user)}: ${getReactionEmoji(data.reaction)}:`, body: getPostSummary(data.post), icon: data.user.avatarUrl + '?thumbnail&size=64' }; case 'unread_messaging_message': return { - title: `${data.user.name}さんからメッセージ:`, + title: `${getUserName(data.user)}さんからメッセージ:`, body: data.text, // TODO: getMessagingMessageSummary(data), icon: data.user.avatarUrl + '?thumbnail&size=64' }; @@ -57,7 +58,7 @@ export default function(type, data): Notification { case 'othello_invited': return { title: '対局への招待があります', - body: `${data.parent.name}さんから`, + body: `${getUserName(data.parent)}さんから`, icon: data.parent.avatarUrl + '?thumbnail&size=64' }; diff --git a/src/client/app/common/views/components/autocomplete.vue b/src/client/app/common/views/components/autocomplete.vue index 38eaf86508..8837fde6be 100644 --- a/src/client/app/common/views/components/autocomplete.vue +++ b/src/client/app/common/views/components/autocomplete.vue @@ -3,7 +3,7 @@
  1. - {{ user.name }} + {{ getUserName(user) }} @{{ getAcct(user) }}
@@ -22,6 +22,7 @@ import Vue from 'vue'; import * as emojilib from 'emojilib'; import contains from '../../../common/scripts/contains'; import getAcct from '../../../../../acct/render'; +import getUserName from '../../../../../renderers/get-user-name'; const lib = Object.entries(emojilib.lib).filter((x: any) => { return x[1].category != 'flags'; @@ -107,6 +108,7 @@ export default Vue.extend({ }, methods: { getAcct, + getUserName, exec() { this.select = -1; if (this.$refs.suggests) { diff --git a/src/client/app/common/views/components/messaging.vue b/src/client/app/common/views/components/messaging.vue index 4ab3e46e89..9b1449daa5 100644 --- a/src/client/app/common/views/components/messaging.vue +++ b/src/client/app/common/views/components/messaging.vue @@ -14,7 +14,7 @@ tabindex="-1" > - {{ user.name }} + {{ getUserName(user) }} @{{ getAcct(user) }} @@ -33,7 +33,7 @@
- {{ isMe(message) ? message.recipient.name : message.user.name }} + {{ getUserName(isMe(message) ? message.recipient : message.user) }} @{{ getAcct(isMe(message) ? message.recipient : message.user) }}
@@ -52,6 +52,7 @@ diff --git a/src/client/app/desktop/views/components/following-window.vue b/src/client/app/desktop/views/components/following-window.vue index 612847b386..cbd8ec5f94 100644 --- a/src/client/app/desktop/views/components/following-window.vue +++ b/src/client/app/desktop/views/components/following-window.vue @@ -1,7 +1,7 @@