2018-04-02 10:50:40 +00:00
|
|
|
import { MongoError } from 'mongodb';
|
|
|
|
import parseAcct from '../../../acct/parse';
|
2018-04-03 07:33:16 +00:00
|
|
|
import Following, { IFollowing } from '../../../models/following';
|
2018-04-02 10:50:40 +00:00
|
|
|
import User from '../../../models/user';
|
|
|
|
import config from '../../../config';
|
|
|
|
import queue from '../../../queue';
|
2018-04-03 03:07:29 +00:00
|
|
|
import context from '../renderer/context';
|
|
|
|
import renderAccept from '../renderer/accept';
|
|
|
|
import request from '../../request';
|
2018-04-02 10:50:40 +00:00
|
|
|
|
2018-04-03 07:33:16 +00:00
|
|
|
export default async (resolver, actor, activity, distribute) => {
|
2018-04-02 10:50:40 +00:00
|
|
|
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();
|
|
|
|
}
|
|
|
|
|
2018-04-03 07:33:16 +00:00
|
|
|
if (!distribute) {
|
|
|
|
const { _id } = await Following.findOne({
|
2018-04-02 10:50:40 +00:00
|
|
|
followerId: actor._id,
|
|
|
|
followeeId: followee._id
|
2018-04-03 07:33:16 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
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);
|
2018-04-02 10:50:40 +00:00
|
|
|
}
|
2018-04-03 07:33:16 +00:00
|
|
|
});
|
|
|
|
}) as Promise<IFollowing>, async error => {
|
|
|
|
// duplicate key error
|
|
|
|
if (error instanceof MongoError && error.code === 11000) {
|
|
|
|
return Following.findOne({
|
|
|
|
followerId: actor._id,
|
|
|
|
followeeId: followee._id
|
|
|
|
});
|
|
|
|
}
|
2018-04-03 03:07:29 +00:00
|
|
|
|
2018-04-03 07:33:16 +00:00
|
|
|
throw error;
|
|
|
|
});
|
|
|
|
|
|
|
|
const accept = renderAccept(activity);
|
|
|
|
accept['@context'] = context;
|
|
|
|
|
|
|
|
await request(followee, actor.account.inbox, accept);
|
2018-04-03 03:07:29 +00:00
|
|
|
|
2018-04-03 07:33:16 +00:00
|
|
|
return promisedFollowing.then(({ _id }) => ({
|
|
|
|
resolver,
|
|
|
|
object: { $ref: 'following', $id: _id }
|
|
|
|
}));
|
2018-04-02 10:50:40 +00:00
|
|
|
};
|