-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathcategorize.js
More file actions
executable file
·86 lines (73 loc) · 2.55 KB
/
categorize.js
File metadata and controls
executable file
·86 lines (73 loc) · 2.55 KB
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
"use strict";
const config = require('./config/database');
const Promise = require("bluebird");
const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect(config.db.uri);
const path = require('path');
const Torrent = require('./models/Torrent.js');
const bunyan = require("bunyan");
const logger = bunyan.createLogger({name: "categorize"});
const CronJob = require("cron").CronJob;
const filter = { 'category' : /Unknown/ };
const dynamicToIgnore = () => {
const pad = (n, width, z) => {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
const result = [];
// need to refactor this shit
for(var i=2; i<100; i++) {
result.push('.s'+pad(i,2));
result.push('.r'+pad(i,2));
result.push('.z'+pad(i,2));
result.push('.'+pad(i,2));
}
for(var i=2; i<1000; i++) {
result.push('.s'+pad(i,3));
result.push('.r'+pad(i,3));
result.push('.z'+pad(i,3));
result.push('.'+pad(i,3));
}
return result;
}
function findCategoryBasedOnExtensions(exts) {
return Object.keys(config.extToCateg)
.map(categ => { // browse category extensions
if ( config.extToCateg[categ].some(c => exts.includes(c)) )
return categ;
})
.find((c) => c !== undefined); // find the first category
}
const job = new CronJob("30 * * * * *", function() { // run each 30 seconds
const cursor = Torrent.find(filter).sort({'imported': -1}).limit(100).cursor();
cursor.eachAsync(torrent => {
logger.info(`Treating ${torrent._id} categorization`);
if(!torrent.files) {
logger.info(`Torrent ${torrent._id} has no files!`);
return Promise.resolve(torrent);
}
const exts = torrent.files
.map(file => path.extname(file).toLowerCase())
.filter(ext => ext.length > 0) // no empty
.filter(ext => !config.extToIgnore.includes(ext)) // no ignored
.filter(ext => !dynamicToIgnore().includes(ext)) // no special ignored
.filter(ext => ext.length < config.limitExt) // with min length
.slice() // shallow copy
.sort() // sort
.reduce((p, c) => {
if(p[0] !== c) return p.concat(c);
return p;
}, []) // deduplicate
if(exts.length > 5) {
return Promise.resolve(`Torrent ${torrent._id} has no too many extensions!`);
}
const category = findCategoryBasedOnExtensions(exts);
torrent.category = category || "Unknown";
return torrent.save();
})
.then(() => Promise.resolve(logger.info(`All torrents treated`)))
.catch(err => Promise.reject(logger.error(err)))
});
job.start();