forked from pymedusa/medusa.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.js
244 lines (210 loc) · 6.16 KB
/
validate.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
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
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const winston = require('winston');
const { Validator } = require('jsonschema');
const dupKeyValidator = require('json-dup-key-validator');
const moment = require('moment-timezone');
const isEqual = require('lodash/isEqual');
const log = winston.createLogger({
transports: [new winston.transports.Console()],
format: winston.format.combine(
winston.format.timestamp({ format: 'HH:mm:ss' }),
winston.format.colorize({ error: true, warning: true }),
winston.format.printf(info => `[${info.timestamp}] ${info.level}: ${info.message}`)
)
});
/**
* Validate a JSON file.
* @param {string} filePath Absolute path to the file
* @param {jsonschema.Validator} validator Validator object
* @returns {(string|null)} Error if failed, null if passed
*/
const validateJSON = (filePath, validator) => {
const data = fs.readFileSync(filePath, 'utf-8');
const isInvalid = dupKeyValidator.validate(data, false);
if (isInvalid !== undefined) {
return isInvalid.replace(/\n/g, '\\n');
}
const obj = JSON.parse(data);
const results = validator.validate(obj, '/');
if (results.errors.length > 0) {
const messageList = results.errors.map(result => String(result));
return messageList.join('\n');
}
return null;
};
/**
* Validate the scene exceptions JSON files.
* @returns {boolean} Validation result.
*/
const validateSceneExceptions = () => {
const validator = new Validator();
validator.addSchema({
'id': '/indexerSchema',
'type': 'object',
'additionalProperties': false,
'patternProperties': {
'^([1-9]\\d+)$': {
'type': 'object',
'additionalProperties': false,
'patternProperties': {
'^(-1|\\d+)$': {
'type': 'array',
'minItems': 1,
'uniqueItems': true,
'items': {
'type': 'string'
}
}
}
}
}
});
return glob
.sync('scene_exceptions/scene_exceptions_*.json', {
cwd: __dirname,
absolute: true
}).map(filePath => {
const fileName = path.basename(filePath);
log.info(`Validating: scene_exceptions/${fileName}`);
// Example: scene_exceptions_tvdb.json
const indexer = fileName.split('.')[0].split('_').pop();
validator.addSchema({
'id': '/',
'type': 'object',
'additionalProperties': false,
'properties': {
[indexer]: {
'$ref': '/indexerSchema'
}
}
});
const result = validateJSON(filePath, validator);
if (result !== null) {
log.error(`${result}\n`);
return false;
}
console.log();
return true;
}).every(Boolean);
};
/**
* Validate the scene exceptions JSON files.
* @returns {boolean} Validation result.
*/
const validateBrokenProviders = () => {
const relFile = 'providers/broken_providers.json';
const filePath = path.resolve(__dirname, relFile);
log.info(`Validating: ${relFile}`);
const validator = new Validator();
validator.addSchema({
'id': '/',
'type': 'array',
'minItems': 1,
'uniqueItems': true,
'items': {
'type': 'string'
}
});
const result = validateJSON(filePath, validator);
if (result !== null) {
log.error(`${result}\n`);
return false;
}
console.log();
return true;
};
/**
* Validate the network timezones list.
* @returns {boolean} Validation result.
*/
const validateNetworkTimezones = () => {
const relFile = 'sb_network_timezones/network_timezones.txt';
const filePath = path.resolve(__dirname, relFile);
log.info(`Validating: ${relFile}`);
let errors = 0;
const data = fs.readFileSync(filePath, 'utf-8');
const linePattern = /^.+:[\w/]+$/;
// https://stackoverflow.com/a/5202185/7597273
const rsplit = (str, sep, maxsplit) => {
const split = str.split(sep);
return maxsplit ?
[split.slice(0, -maxsplit).join(sep)].concat(split.slice(-maxsplit)) :
split;
};
const logError = (message, index, line) => {
if (line) {
log.error(`Line #${index}: ${message}\n\t\`${line}\``);
} else {
log.error(`Line #${index}: ${message}`);
}
errors++;
};
const timezones = moment.tz.names();
const lines = data.split('\n');
if (!data.trim() || lines.length === 0) {
log.warn('File is empty.');
return true;
}
const networkNames = {};
lines.forEach((line, index) => {
const lineIndex = index + 1;
const trimmedLine = line.trim();
if (lineIndex === lines.length) {
if (trimmedLine) {
logError('Please leave one empty line at the end of the file.', lineIndex);
} else {
// Last line should not be processed.
return;
}
}
if (!trimmedLine) {
logError('Please remove empty lines.', lineIndex);
return;
}
if (line.includes('\r')) {
logError('`\\r` found - please only use Linux EOL (`\\n`).', lineIndex);
}
if (!linePattern.test(line)) {
logError('Line format invalid, please use: `Network Name:Timezone`', lineIndex, line);
}
const [network, timezone] = rsplit(line, ':', 1);
if (!timezones.includes(timezone)) {
logError(`Timezone \`${timezone}\` is invalid.`, lineIndex, line);
}
if (networkNames[network] === undefined) {
networkNames[network] = lineIndex;
} else {
logError(`Duplicate entry found.`, lineIndex, line);
logError(`First entry.`, networkNames[network], lines[networkNames[network] - 1]);
}
});
const sortedLines = lines.slice().filter(Boolean);
sortedLines.sort();
sortedLines.push('');
let sorted = isEqual(lines, sortedLines);
if (!sorted) {
if (process.argv.includes('--fix')) {
log.info(`Writing sorted lines to ${relFile}.`);
fs.writeFileSync(filePath, sortedLines.join('\n'));
sorted = true;
} else {
log.error('Lines are unsorted. Run `yarn validate --fix` to fix.');
}
}
console.log();
return errors === 0 && sorted;
};
const results = [
validateSceneExceptions(),
validateBrokenProviders(),
validateNetworkTimezones()
];
process.exit(
Number(
!results.every(Boolean)
)
);