Spaces:
Build error
Build error
File size: 20,661 Bytes
0bfe2e3 |
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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 |
import { Parser } from 'expr-eval';
import { ParsedStream, ParsedStreams, ParsedStreamSchema } from '../db';
import bytes from 'bytes';
export abstract class StreamExpressionEngine {
protected parser: Parser;
constructor() {
// only allow comparison and logical operators
this.parser = new Parser({
operators: {
comparison: true,
logical: true,
add: true,
concatenate: false,
conditional: true,
divide: false,
factorial: false,
multiply: false,
power: false,
remainder: false,
subtract: true,
sin: false,
cos: false,
tan: false,
asin: false,
acos: false,
atan: false,
sinh: false,
cosh: false,
tanh: false,
asinh: false,
acosh: false,
atanh: false,
sqrt: false,
log: false,
ln: false,
lg: false,
log10: false,
abs: false,
ceil: false,
floor: false,
round: false,
trunc: false,
exp: false,
length: false,
in: false,
random: false,
min: true,
max: true,
assignment: false,
fndef: false,
cbrt: false,
expm1: false,
log1p: false,
sign: false,
log2: false,
},
});
this.setupParserFunctions();
}
private setupParserFunctions() {
this.parser.functions.regexMatched = function (
streams: ParsedStream[],
...regexNames: string[]
) {
if (regexNames.length === 0) {
return streams.filter((stream) => stream.regexMatched);
}
return streams.filter((stream) =>
regexNames.some((regexName) => stream.regexMatched?.name === regexName)
);
};
// gets all streams that have a regex matched with an index in the range of min and max
this.parser.functions.regexMatchedInRange = function (
streams: ParsedStream[],
min: number,
max: number
) {
return streams.filter((stream) => {
if (!stream.regexMatched) {
return false;
} else if (
stream.regexMatched.index < min ||
stream.regexMatched.index > max
) {
return false;
}
return true;
});
};
this.parser.functions.indexer = function (
streams: ParsedStream[],
...indexers: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
indexers.length === 0 ||
indexers.some((i) => typeof i !== 'string')
) {
throw new Error('You must provide one or more indexer strings');
}
return streams.filter((stream) =>
indexers.includes(stream.indexer || 'Unknown')
);
};
this.parser.functions.resolution = function (
streams: ParsedStream[],
...resolutions: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
resolutions.length === 0 ||
resolutions.some((r) => typeof r !== 'string')
) {
throw new Error('You must provide one or more resolution strings');
}
return streams.filter((stream) =>
resolutions
.map((r) => r.toLowerCase())
.includes(stream.parsedFile?.resolution?.toLowerCase() || 'unknown')
);
};
this.parser.functions.quality = function (
streams: ParsedStream[],
...qualities: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
qualities.length === 0 ||
qualities.some((q) => typeof q !== 'string')
) {
throw new Error('You must provide one or more quality strings');
}
return streams.filter((stream) =>
qualities
.map((q) => q.toLowerCase())
.includes(stream.parsedFile?.quality?.toLowerCase() || 'unknown')
);
};
this.parser.functions.encode = function (
streams: ParsedStream[],
...encodes: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
encodes.length === 0 ||
encodes.some((e) => typeof e !== 'string')
) {
throw new Error('You must provide one or more encode strings');
}
return streams.filter((stream) =>
encodes
.map((encode) => encode.toLowerCase())
.includes(stream.parsedFile?.encode?.toLowerCase() || 'unknown')
);
};
this.parser.functions.type = function (
streams: ParsedStream[],
...types: string[]
) {
if (!Array.isArray(streams)) {
throw new Error('Your streams input must be an array of streams');
} else if (
types.length === 0 ||
types.some((t) => typeof t !== 'string')
) {
throw new Error('You must provide one or more type string parameters');
}
return streams.filter((stream) =>
types.map((t) => t.toLowerCase()).includes(stream.type.toLowerCase())
);
};
this.parser.functions.visualTag = function (
streams: ParsedStream[],
...visualTags: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
visualTags.length === 0 ||
visualTags.some((v) => typeof v !== 'string')
) {
throw new Error(
'You must provide one or more visual tag string parameters'
);
}
return streams.filter((stream) =>
stream.parsedFile?.visualTags.some((v) =>
visualTags.map((vt) => vt.toLowerCase()).includes(v.toLowerCase())
)
);
};
this.parser.functions.audioTag = function (
streams: ParsedStream[],
...audioTags: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
audioTags.length === 0 ||
audioTags.some((a) => typeof a !== 'string')
) {
throw new Error(
'You must provide one or more audio tag string parameters'
);
}
return streams.filter((stream) =>
audioTags
.map((a) => a.toLowerCase())
.some((a) =>
stream.parsedFile?.audioTags
.map((at) => at.toLowerCase())
.includes(a)
)
);
};
this.parser.functions.audioChannels = function (
streams: ParsedStream[],
...audioChannels: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
audioChannels.length === 0 ||
audioChannels.some((a) => typeof a !== 'string')
) {
throw new Error(
'You must provide one or more audio channel string parameters'
);
}
return streams.filter((stream) =>
audioChannels
.map((a) => a.toLowerCase())
.some((a) =>
stream.parsedFile?.audioChannels
?.map((ac) => ac.toLowerCase())
.includes(a)
)
);
};
this.parser.functions.language = function (
streams: ParsedStream[],
...languages: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
languages.length === 0 ||
languages.some((l) => typeof l !== 'string')
) {
throw new Error(
'You must provide one or more language string parameters'
);
}
return streams.filter((stream) =>
languages
.map((l) => l.toLowerCase())
.some((l) =>
stream.parsedFile?.languages
?.map((lang) => lang.toLowerCase())
.includes(l)
)
);
};
this.parser.functions.seeders = function (
streams: ParsedStream[],
minSeeders?: number,
maxSeeders?: number
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
typeof minSeeders !== 'number' &&
typeof maxSeeders !== 'number'
) {
throw new Error('Min and max seeders must be a number');
}
// select streams with seeders that lie within the range.
return streams.filter((stream) => {
if (minSeeders && (stream.torrent?.seeders ?? 0) < minSeeders) {
return false;
}
if (maxSeeders && (stream.torrent?.seeders ?? 0) > maxSeeders) {
return false;
}
return true;
});
};
this.parser.functions.size = function (
streams: ParsedStream[],
minSize?: string | number,
maxSize?: string | number
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
typeof minSize !== 'number' &&
typeof maxSize !== 'number' &&
typeof minSize !== 'string' &&
typeof maxSize !== 'string'
) {
throw new Error('Min and max size must be a number');
}
// use the bytes library to ensure we get a number
const minSizeInBytes =
typeof minSize === 'string' ? bytes.parse(minSize) : minSize;
const maxSizeInBytes =
typeof maxSize === 'string' ? bytes.parse(maxSize) : maxSize;
return streams.filter((stream) => {
if (
minSize &&
stream.size &&
minSizeInBytes &&
stream.size < minSizeInBytes
) {
return false;
}
if (
maxSize &&
stream.size &&
maxSizeInBytes &&
stream.size > maxSizeInBytes
) {
return false;
}
return true;
});
};
this.parser.functions.service = function (
streams: ParsedStream[],
...services: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
services.length === 0 ||
services.some((s) => typeof s !== 'string')
) {
throw new Error(
'You must provide one or more service string parameters'
);
} else if (
services.length === 0 ||
services.some((s) => typeof s !== 'string')
) {
throw new Error(
'You must provide one or more service string parameters'
);
} else if (
!services.every((s) =>
[
'realdebrid',
'debridlink',
'alldebrid',
'torbox',
'pikpak',
'seedr',
'offcloud',
'premiumize',
'easynews',
'easydebrid',
].includes(s)
)
) {
throw new Error(
'Service must be a string and one of: realdebrid, debridlink, alldebrid, torbox, pikpak, seedr, offcloud, premiumize, easynews, easydebrid'
);
}
return streams.filter((stream) =>
services.some((s) => stream.service?.id === s)
);
};
this.parser.functions.cached = function (streams: ParsedStream[]) {
if (!Array.isArray(streams)) {
throw new Error(
"Please use one of 'totalStreams' or 'previousStreams' as the first argument"
);
}
return streams.filter((stream) => stream.service?.cached === true);
};
this.parser.functions.uncached = function (streams: ParsedStream[]) {
if (!Array.isArray(streams)) {
throw new Error(
"Please use one of 'totalStreams' or 'previousStreams' as the first argument"
);
}
return streams.filter((stream) => stream.service?.cached === false);
};
this.parser.functions.releaseGroup = function (
streams: ParsedStream[],
...releaseGroups: string[]
) {
if (!Array.isArray(streams)) {
throw new Error(
"Please use one of 'totalStreams' or 'previousStreams' as the first argument"
);
} else if (
releaseGroups.length === 0 ||
releaseGroups.some((r) => typeof r !== 'string')
) {
throw new Error(
'You must provide one or more release group string parameters'
);
}
return streams.filter((stream) =>
releaseGroups.some((r) => stream.parsedFile?.releaseGroup === r)
);
};
this.parser.functions.addon = function (
streams: ParsedStream[],
...addons: string[]
) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
} else if (
addons.length === 0 ||
addons.some((a) => typeof a !== 'string')
) {
throw new Error('You must provide one or more addon string parameters');
}
return streams.filter((stream) => addons.includes(stream.addon.name));
};
this.parser.functions.library = function (streams: ParsedStream[]) {
if (!Array.isArray(streams) || streams.some((stream) => !stream.type)) {
throw new Error('Your streams input must be an array of streams');
}
return streams.filter((stream) => stream.library);
};
this.parser.functions.count = function (streams: ParsedStream[]) {
if (!Array.isArray(streams)) {
throw new Error(
"Please use one of 'totalStreams' or 'previousStreams' as the first argument"
);
}
return streams.length;
};
this.parser.functions.negate = function (
streams: ParsedStream[],
originalStreams: ParsedStream[]
) {
if (!Array.isArray(originalStreams) || !Array.isArray(streams)) {
throw new Error(
"Both arguments of the 'negate' function must be arrays of streams"
);
}
const streamIds = new Set(streams.map((stream) => stream.id));
return originalStreams.filter((stream) => !streamIds.has(stream.id));
};
this.parser.functions.merge = function (
...streamArrays: ParsedStream[][]
): ParsedStream[] {
const seen = new Set<string>();
const merged: ParsedStream[] = [];
for (const array of streamArrays) {
for (const stream of array) {
if (!seen.has(stream.id)) {
seen.add(stream.id);
merged.push(stream);
}
}
}
return merged;
};
this.parser.functions.slice = function (
streams: ParsedStream[],
start: number,
end: number
) {
if (!Array.isArray(streams)) {
throw new Error('Your streams input must be an array of streams');
}
return streams.slice(start, end);
};
}
protected async evaluateCondition(condition: string): Promise<any> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('Condition parsing timed out'));
}, 1);
try {
const result = this.parser.evaluate(condition);
clearTimeout(timeout);
resolve(result);
} catch (error) {
clearTimeout(timeout);
reject(error);
}
});
}
protected createTestStream(
overrides: Partial<ParsedStream> = {}
): ParsedStream {
const defaultStream: ParsedStream = {
id: '1',
type: 'http',
addon: {
instanceId: 'test-instance',
presetType: 'test-preset',
presetInstanceId: 'test-preset-instance',
manifestUrl: 'https://example.com/manifest.json',
enabled: true,
name: 'Test Addon',
timeout: 30000,
},
service: {
id: 'realdebrid',
cached: true,
},
indexer: 'Test Indexer',
parsedFile: {
title: 'Test Title',
year: '2024',
season: 1,
episode: 1,
seasons: [1],
resolution: '1080p',
quality: 'BluRay',
encode: 'x264',
releaseGroup: 'TEST',
seasonEpisode: ['S01', 'E01'],
visualTags: ['HDR'],
audioTags: ['AAC'],
audioChannels: ['2.0'],
languages: ['English'],
},
size: 1073741824, // 1GB in bytes
folderSize: 2147483648, // 2GB in bytes
library: false,
url: 'https://example.com/stream.mkv',
filename: 'test.mkv',
folderName: 'Test Folder',
duration: 7200, // 2 hours in seconds
age: '1 day',
message: 'Test message',
torrent: {
infoHash: 'test-hash',
fileIdx: 0,
seeders: 100,
sources: ['https://tracker.example.com'],
},
countryWhitelist: ['USA'],
notWebReady: false,
bingeGroup: 'test-group',
requestHeaders: { 'User-Agent': 'Test' },
responseHeaders: { 'Content-Type': 'video/mp4' },
videoHash: 'test-video-hash',
subtitles: [],
proxied: false,
regexMatched: {
name: 'test-regex',
pattern: 'test',
index: 0,
},
keywordMatched: false,
ytId: undefined,
externalUrl: undefined,
error: undefined,
originalName: 'Original Test Name',
originalDescription: 'Original Test Description',
};
return { ...defaultStream, ...overrides };
}
}
export class GroupConditionEvaluator extends StreamExpressionEngine {
private previousStreams: ParsedStream[];
private totalStreams: ParsedStream[];
private previousGroupTimeTaken: number;
private totalTimeTaken: number;
constructor(
previousStreams: ParsedStream[],
totalStreams: ParsedStream[],
previousGroupTimeTaken: number,
totalTimeTaken: number,
queryType: string
) {
super();
this.previousStreams = previousStreams;
this.totalStreams = totalStreams;
this.previousGroupTimeTaken = previousGroupTimeTaken;
this.totalTimeTaken = totalTimeTaken;
// Set up constants for this specific parser
this.parser.consts.previousStreams = this.previousStreams;
this.parser.consts.totalStreams = this.totalStreams;
this.parser.consts.queryType = queryType;
this.parser.consts.previousGroupTimeTaken = this.previousGroupTimeTaken;
this.parser.consts.totalTimeTaken = this.totalTimeTaken;
}
async evaluate(condition: string) {
return await this.evaluateCondition(condition);
}
static async testEvaluate(condition: string) {
const parser = new GroupConditionEvaluator([], [], 0, 0, 'movie');
return await parser.evaluate(condition);
}
}
export class StreamSelector extends StreamExpressionEngine {
constructor() {
super();
}
async select(
streams: ParsedStream[],
condition: string
): Promise<ParsedStream[]> {
// Set the streams constant for this filter operation
this.parser.consts.streams = streams;
let selectedStreams: ParsedStream[] = [];
selectedStreams = await this.evaluateCondition(condition);
// if the result is a boolean value, convert it to the appropriate type
// true = all streams, false = no streams
if (typeof selectedStreams === 'boolean') {
selectedStreams = selectedStreams ? streams : [];
}
// attempt to parse the result
try {
selectedStreams = ParsedStreams.parse(selectedStreams);
} catch (error) {
throw new Error(
`Filter condition failed: ${error instanceof Error ? error.message : String(error)}`
);
}
return selectedStreams;
}
static async testSelect(condition: string): Promise<ParsedStream[]> {
const parser = new StreamSelector();
const streams = [
parser.createTestStream({ type: 'debrid' }),
parser.createTestStream({ type: 'debrid' }),
parser.createTestStream({ type: 'debrid' }),
parser.createTestStream({ type: 'usenet' }),
parser.createTestStream({ type: 'p2p' }),
parser.createTestStream({ type: 'p2p' }),
];
return await parser.select(streams, condition);
}
}
|