Sharkey/src/queue/processors/db/import-following.ts

71 lines
1.9 KiB
TypeScript
Raw Normal View History

2019-03-11 17:34:19 +02:00
import * as Bull from 'bull';
import * as mongo from 'mongodb';
import { queueLogger } from '../../logger';
import User from '../../../models/user';
import follow from '../../../services/following/create';
import DriveFile from '../../../models/drive-file';
import { getOriginalUrl } from '../../../misc/get-drive-file-url';
import parseAcct from '../../../misc/acct/parse';
import resolveUser from '../../../remote/resolve-user';
import { downloadTextFile } from '../../../misc/download-text-file';
import { isSelfHost, toDbHost } from '../../../misc/convert-host';
2019-03-11 17:34:19 +02:00
const logger = queueLogger.createSubLogger('import-following');
export async function importFollowing(job: Bull.Job, done: any): Promise<void> {
logger.info(`Importing following of ${job.data.user._id} ...`);
const user = await User.findOne({
_id: new mongo.ObjectID(job.data.user._id.toString())
});
const file = await DriveFile.findOne({
_id: new mongo.ObjectID(job.data.fileId.toString())
});
const url = getOriginalUrl(file);
const csv = await downloadTextFile(url);
2019-04-05 18:41:08 +03:00
let linenum = 0;
2019-03-11 17:34:19 +02:00
for (const line of csv.trim().split('\n')) {
2019-04-05 18:41:08 +03:00
linenum++;
2019-03-11 17:34:19 +02:00
2019-04-05 18:41:08 +03:00
try {
const { username, host } = parseAcct(line.trim());
2019-03-11 17:34:19 +02:00
2019-04-05 18:41:08 +03:00
let target = isSelfHost(host) ? await User.findOne({
host: null,
usernameLower: username.toLowerCase()
}) : await User.findOne({
host: toDbHost(host),
usernameLower: username.toLowerCase()
});
2019-03-11 17:34:19 +02:00
2019-04-05 18:41:08 +03:00
if (host == null && target == null) continue;
if (target == null) {
target = await resolveUser(username, host);
}
2019-03-11 17:34:19 +02:00
2019-04-05 18:41:08 +03:00
if (target == null) {
throw `cannot resolve user: @${username}@${host}`;
}
2019-04-05 18:41:08 +03:00
// skip myself
if (target._id.equals(job.data.user._id)) continue;
2019-03-12 06:12:49 +02:00
2019-04-05 18:41:08 +03:00
logger.info(`Follow[${linenum}] ${target._id} ...`);
follow(user, target);
} catch (e) {
logger.warn(`Error in line:${linenum} ${e}`);
}
2019-03-11 17:34:19 +02:00
}
logger.succ('Imported');
done();
}