monkeeShark/src/queue/processors/http/unfollow.ts

64 lines
1.9 KiB
TypeScript
Raw Normal View History

2018-04-04 14:59:38 +00:00
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';
2018-04-03 08:18:06 +00:00
export default async ({ data }) => {
2018-04-04 14:59:38 +00:00
const following = await Following.findOne({ _id: data.id });
2018-04-03 08:18:06 +00:00
if (following === null) {
return;
}
2018-04-04 14:59:38 +00:00
const [follower, followee] = await Promise.all([
User.findOne({ _id: following.followerId }),
User.findOne({ _id: following.followeeId })
]);
2018-04-03 08:18:06 +00:00
2018-04-04 14:59:38 +00:00
if (isLocalUser(follower) && isRemoteUser(followee)) {
const undo = renderUndo(renderFollow(follower, followee));
undo['@context'] = context;
2018-04-03 08:18:06 +00:00
2018-04-04 14:59:38 +00:00
await request(follower, followee.account.inbox, undo);
}
2018-04-03 08:18:06 +00:00
2018-04-04 14:59:38 +00:00
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);
2018-04-03 08:18:06 +00:00
2018-04-04 14:59:38 +00:00
// Publish follow event
stream(follower._id, 'unfollow', promisedPackedUser);
} catch (error) {
Logger.error(error.toString());
}
2018-04-03 08:18:06 +00:00
};