-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathimporter.js
161 lines (137 loc) · 4.36 KB
/
importer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
const typeorm = require("typeorm");
const { MeiliSearch } = require('meilisearch')
const fs = require('fs');
const yaml = require('js-yaml');
const cliProgress = require('cli-progress');
const colors = require('ansi-colors');
const { program } = require('commander');
program
.name('node importer.js')
.description('A utility to import past posts from Misskey into Meilisearch')
.version('1.0.0')
.option('--config <file>', 'path of Misskey config file (.config/default.yml)')
.option('--id <aid>', 'starts processing from the specified "aid" sequence')
.option('--batch-size <size>', 'number of notes to import in one process', 1000)
.parse();
const options = program.opts();
const configFilename = options.config ?? '../misskey/.config/default.yml';
const config = (() => {
try {
return yaml.load(fs.readFileSync(configFilename, 'utf8'))
} catch(e) {
console.error('Misskey config file reading failed.');
process.exit(1);
}
})();
if (config.id != 'aid') {
console.error('Id format must be "aid".');
process.exit(1);
}
if (!config.meilisearch) {
console.error("Meilisearch settings are not enabled.");
process.exit(1);
}
const bar = new cliProgress.SingleBar({
format: 'Importing |' + colors.cyan('{bar}') + '| {percentage}% | {value}/{total} Chunks | {lastId} ',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});
const meilisearch = new MeiliSearch({
host: `${config.meilisearch.ssl ? 'https' : 'http' }://${config.meilisearch.host}:${config.meilisearch.port}`,
apiKey: config.meilisearch.apiKey,
});
const meilisearchNoteIndex = meilisearch.index(`${config.meilisearch.index}---notes`);
const meilisearchIndexScope = config.meilisearch?.scope ?? 'local';
const dataSource = new typeorm.DataSource({
type: "postgres",
host: config.db.host,
port: config.db.port,
username: config.db.user,
password: config.db.pass,
database: config.db.db,
synchronize: false,
});
dataSource
.initialize()
.then(async connection => {
addFunction_Base36Decode(connection);
importNotes(connection, options.id);
}).catch((e) => {
console.error("Error: ", e);
process.exit(1);
});
const importNotes = async (connection, id) => {
let lastId = id;
console.log('Preparing for import...');
const { total } = await connection.createQueryBuilder()
.from('note')
.where("(text IS NOT NULL OR cw IS NOT NULL) AND visibility IN ('home', 'public')")
.andWhere(() => {
switch (meilisearchIndexScope) {
case 'global': return 'true';
case 'local': return '"userHost" IS NULL';
default: return '"userHost" IN (:...hosts)';
}
})
.setParameter('hosts', meilisearchIndexScope)
.andWhere(lastId ? 'id < :id' : 'true')
.setParameter('id', lastId)
.select("count(*)", 'total')
.getRawOne();
bar.start(total, 0, { lastId: lastId ?? '(all)' });
while (true) {
notes = await connection.createQueryBuilder()
.from('note')
.where("(text IS NOT NULL OR cw IS NOT NULL) AND visibility IN ('home', 'public')")
.andWhere(() => {
switch (meilisearchIndexScope) {
case 'global': return 'true';
case 'local': return '"userHost" IS NULL';
default: return '"userHost" IN (:...hosts)';
}
})
.setParameter('hosts', meilisearchIndexScope)
.orderBy('id', 'DESC')
.andWhere(lastId ? 'id < :id' : 'true')
.setParameter('id', lastId)
.select(['id', 'base36_decode(substring(id, 1, 8))+946684800000 AS "createdAt"', '"userHost"', '"channelId"', 'cw', 'text', 'tags'])
.take(options.batchSize)
.getRawMany();
if (notes.length == 0) {
break;
}
await meilisearchNoteIndex.addDocuments(notes, { primaryKey: 'id' });
lastId = notes[notes.length - 1].id;
bar.increment(notes.length, { lastId });
}
bar.update(total, { lastId: '(done)'} );
bar.stop();
};
const addFunction_Base36Decode = (connection) => {
connection.query(`
CREATE OR REPLACE FUNCTION base36_decode(IN base36 varchar)
RETURNS bigint AS $$
DECLARE
a char[];
ret bigint;
i int;
val int;
chars varchar;
BEGIN
chars := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
FOR i IN REVERSE char_length(base36)..1 LOOP
a := a || substring(upper(base36) FROM i FOR 1)::char;
END LOOP;
i := 0;
ret := 0;
WHILE i < (array_length(a,1)) LOOP
val := position(a[i+1] IN chars)-1;
ret := ret + (val * (36 ^ i));
i := i + 1;
END LOOP;
RETURN ret;
END;
$$ LANGUAGE 'plpgsql' IMMUTABLE;
`);
};