-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcleanup.mjs
332 lines (294 loc) · 8.78 KB
/
cleanup.mjs
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import dotenv from 'dotenv'
import fs from 'fs'
import Mongo from 'mongodb'
import Redis from 'ioredis'
import { iso6393 } from 'iso-639-3'
console.log('\nStarting cleanup process\n')
const { MongoClient, ObjectId } = Mongo
// load .env if exists
if (fs.existsSync('./.env')) {
dotenv.config()
}
const errorEnv = (env) => {
console.error("Missing required ENV '" + env + "'. Make sure you add it!!!")
process.exit(1)
}
const warnEnv = (env, defaultValue) => {
console.error(
"ENV '" + env + "' is not provided, using default:",
defaultValue
)
process.exit(1)
}
if (!('NEXT_PUBLIC_SITE_NAME' in process.env)) {
warnEnv('NEXT_PUBLIC_SITE_NAME', 'The Anime Index')
}
if (!('NEXT_PUBLIC_DOMAIN' in process.env)) {
warnEnv('NEXT_PUBLIC_DOMAIN', 'https://theindex.moe')
}
if (!('DATABASE_URL' in process.env)) {
warnEnv('DATABASE_URL', 'mongodb://mongo:27017/index')
}
let dbClient, db
try {
dbClient = new MongoClient(
'DATABASE_URL' in process.env
? process.env.DATABASE_URL
: 'mongodb://mongo:27017/index',
{ maxPoolSize: 5 }
)
await dbClient.connect()
db = dbClient.db('index')
console.log('Connection to mongo db server could be established')
} catch (e) {
console.error('Failed to connect to mongo db server:', e)
process.exit(1)
}
if (!('CACHE_URL' in process.env)) {
warnEnv('CACHE_URL', 'redis://redis:6379')
}
let cacheClient
try {
cacheClient = new Redis(
'CACHE_URL' in process.env ? process.env.CACHE_URL : 'redis://localhost'
)
cacheClient.flushall().catch((e) => console.error('Failed to flush cache', e))
console.log('Connection to redis cache server could be established')
} catch (e) {
console.error('Failed to connect to redis cache server:', e)
process.exit(1)
}
if (!('CHROME_URL' in process.env)) {
warnEnv('CHROME_URL', 'ws://chrome:3300')
}
if (!('DISCORD_CLIENT_ID' in process.env)) {
errorEnv('DISCORD_CLIENT_ID')
}
if (!('DISCORD_CLIENT_SECRET' in process.env)) {
errorEnv('DISCORD_CLIENT_SECRET')
}
// not used atm
if (!('DISCORD_BOT_TOKEN' in process.env)) {
// errorEnv('DISCORD_BOT_TOKEN')
}
if ('SETUP_WHITELIST_DISCORD_ID' in process.env) {
console.log(
"ENV 'SETUP_WHITELIST_DISCORD_ID' provided, on login of",
process.env.SETUP_WHITELIST_DISCORD_ID,
'the person will be elevated to admin rights if not already admin'
)
} else {
console.warn(
"ENV 'SETUP_WHITELIST_DISCORD_ID' is not provided, no admin account will be created on any login"
)
}
if ('AUDIT_WEBHOOK' in process.env) {
console.log(
"ENV 'AUDIT_WEBHOOK' provided, on item edits, a post will be send to webhook:",
process.env.AUDIT_WEBHOOK
)
} else {
console.warn(
"ENV 'AUDIT_WEBHOOK' is not provided, no webhook posts will be made"
)
}
const polluteId = (query) => {
if (typeof query !== 'undefined') {
if (query.hasOwnProperty('_id') && typeof query._id === 'string') {
query._id = new ObjectId(query._id)
}
if (
query.hasOwnProperty('lastModified') &&
typeof query.lastModified === 'string'
) {
query.lastModified = new Date(query.lastModified)
}
}
return query
}
const update = async (collection, query, data) => {
await db.collection(collection).updateOne(polluteId(query), {
$set: data,
$currentDate: { lastModified: true },
})
}
const remove = async (collection, query) => {
await db.collection(collection).deleteOne(polluteId(query))
}
let dbCollections = await db.listCollections({}, { nameOnly: true }).toArray()
dbCollections = dbCollections.map((c) => c.name)
if (!dbCollections.includes('libraries')) {
console.error('Database seems empty, skipping libraries...')
} else {
const libraries = await db.collection('libraries').find().toArray()
await Promise.all(
libraries.map(async (library) => {
let foundInvalidCollection = false
const collections = library.collections.map((collection) => {
if (typeof collection === 'string') {
return collection
}
console.warn(
'Library',
library.name,
'has invalid collection id',
collection
)
if ('_id' in collection) {
foundInvalidCollection = true
return collection._id
}
console.error(
'Library',
library.name,
'could not extract invalid collection id from',
collection
)
return collection
})
if (foundInvalidCollection) {
await update(
'libraries',
{ _id: library._id },
{
collections: collections,
}
)
}
})
)
}
if (!dbCollections.includes('columns') || !dbCollections.includes('items')) {
console.error('Database seems empty, skipping columns...')
} else {
const columns = await db.collection('columns').find().toArray()
await Promise.all(
columns.map(async (column) => {
if (column.type === 'bool' || column.type === 'boolean') {
console.log('column', column._id.toString())
await update('columns', { _id: column._id }, { type: 'feature' })
}
})
)
console.log('Cleaned up columns\n')
let items = await db.collection('items').find().toArray()
const livingLang = iso6393.filter((lang) => lang.type === 'living')
await Promise.all(
items.map(async (item) => {
const columnKeys = Object.keys(item.data)
let updateData = false
for (const columnId of columnKeys) {
const column = columns.find(
(column) => column._id.toString() === columnId
)
if (!column) {
delete item.data[columnId]
updateData = true
} else if (column.type === 'language') {
item.data[column._id.toString()] = item.data[
column._id.toString()
].map((l) => {
if (l !== l.toLowerCase()) {
l = l.toLowerCase()
updateData = true
}
if (l.length === 2) {
const newL = livingLang.find((lang) => lang.iso6391 === l)
if (newL) {
l = newL.iso6393
updateData = true
}
}
return l
})
}
}
if (updateData) {
await update('items', { _id: item._id }, { data: item.data })
console.log('Deleted data of non existing column from item', item._id)
}
})
)
console.log('Cleaned up items\n')
}
if (!dbCollections.includes('users')) {
console.error('Database seems empty, skipping users...')
} else {
let users = await db.collection('users').find().toArray()
for (let i = 0; i < users.length; i++) {
const user = users[i]
const userData = await db.collection('nextauth_users').findOne({
_id: new ObjectId(user.uid),
})
if (!userData) {
console.warn('User', user.uid, "is not registered in next-auth's user db")
}
let multipleUsers = users.filter((u) => u.uid === user.uid)
if (multipleUsers.length > 1) {
console.warn(
multipleUsers.length,
'user account entries found for the same user',
user.uid,
userData.name
)
let data = {
accountType: 'user',
description: '',
favs: [],
lists: [],
followLists: [],
createdAt: new Date(),
}
for (const user of multipleUsers) {
if (user.accountType === 'admin') {
data.accountType = 'admin'
} else if (
user.accountType === 'editor' &&
data.accountType !== 'admin'
) {
data.accountType = 'editor'
}
if (
user.description !== '' &&
user.description.length > data.description.length
) {
data.description = user.description
}
for (const fav of user.favs) {
if (!data.favs.includes(fav)) {
data.favs.push(fav)
}
}
for (const list of user.lists) {
if (!data.lists.includes(list)) {
data.lists.push(list)
}
}
for (const list of user.followLists) {
if (!data.followLists.includes(list)) {
data.followLists.push(list)
}
}
if (user.createdAt.getTime() < data.createdAt.getTime()) {
data.createdAt = user.createdAt
}
}
for (let i = 1; i < multipleUsers.length; i++) {
await remove('users', { _id: multipleUsers[i]._id })
users = users.filter((u) => u._id !== multipleUsers[i]._id)
console.log(
'Removed duplicate user',
multipleUsers[i]._id,
'of duplicate user entry of uid',
user.uid
)
}
await update('users', { _id: multipleUsers[0]._id }, { data })
}
}
console.log('Cleaned up users\n')
}
console.log('Cleanup finished\n')
await dbClient.close()
console.log('Mongo db connection closed\n')
process.exit(0)