2019-11-11 02:20:00 +00:00
|
|
|
'use strict';
|
|
|
|
|
2020-03-30 01:01:08 +00:00
|
|
|
const config = require('config');
|
2020-07-10 00:01:23 +00:00
|
|
|
const util = require('util');
|
2020-03-29 02:00:46 +00:00
|
|
|
const Promise = require('bluebird');
|
2020-04-26 01:51:59 +00:00
|
|
|
const fs = require('fs');
|
|
|
|
const fsPromises = require('fs').promises;
|
2020-03-30 01:01:08 +00:00
|
|
|
const path = require('path');
|
2020-07-10 00:01:23 +00:00
|
|
|
const stream = require('stream');
|
2021-11-20 23:31:09 +00:00
|
|
|
const { nanoid } = require('nanoid/non-secure');
|
2020-03-30 01:01:08 +00:00
|
|
|
const mime = require('mime');
|
2020-04-11 20:49:37 +00:00
|
|
|
// const fileType = require('file-type');
|
2020-07-17 01:39:13 +00:00
|
|
|
const ffmpeg = require('fluent-ffmpeg');
|
2020-03-30 01:01:08 +00:00
|
|
|
const sharp = require('sharp');
|
|
|
|
const blake2 = require('blake2');
|
2020-08-17 13:53:20 +00:00
|
|
|
const taskQueue = require('promise-task-queue');
|
2023-11-30 02:12:47 +00:00
|
|
|
|
|
|
|
const { Upload } = require('@aws-sdk/lib-storage');
|
|
|
|
const { S3Client } = require('@aws-sdk/client-s3');
|
2019-11-11 02:20:00 +00:00
|
|
|
|
2020-03-29 02:00:46 +00:00
|
|
|
const logger = require('./logger')(__filename);
|
|
|
|
const argv = require('./argv');
|
|
|
|
const knex = require('./knex');
|
2020-03-30 01:01:08 +00:00
|
|
|
const http = require('./utils/http');
|
2020-08-14 21:21:53 +00:00
|
|
|
const bulkInsert = require('./utils/bulk-insert');
|
2022-04-01 22:32:23 +00:00
|
|
|
const chunk = require('./utils/chunk');
|
2020-03-29 02:00:46 +00:00
|
|
|
const { get } = require('./utils/qu');
|
|
|
|
|
2023-06-10 23:17:37 +00:00
|
|
|
// const pipeline = util.promisify(stream.pipeline);
|
2020-08-17 13:53:20 +00:00
|
|
|
const streamQueue = taskQueue();
|
2020-07-10 00:01:23 +00:00
|
|
|
|
2023-11-30 02:12:47 +00:00
|
|
|
const s3 = new S3Client({
|
|
|
|
region: 'eu-central-1',
|
|
|
|
endpoint: 'https://s3.eu-central-1.wasabisys.com',
|
2021-02-22 01:33:39 +00:00
|
|
|
credentials: {
|
|
|
|
accessKeyId: config.s3.accessKey,
|
|
|
|
secretAccessKey: config.s3.secretKey,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2021-02-04 21:58:18 +00:00
|
|
|
function sampleMedias(medias, limit = argv.mediaLimit, preferLast = true) {
|
2020-05-14 02:26:05 +00:00
|
|
|
// limit media sets, use extras as fallbacks
|
|
|
|
if (medias.length <= limit) {
|
|
|
|
return medias;
|
|
|
|
}
|
|
|
|
|
|
|
|
const chunkSize = Math.floor(medias.length / limit);
|
|
|
|
const rest = medias.length - (limit * chunkSize);
|
|
|
|
|
|
|
|
const chunks = Array.from(
|
|
|
|
{ length: limit },
|
|
|
|
(value, index) => {
|
|
|
|
const start = (chunkSize * index) + Math.min(index, rest);
|
|
|
|
|
|
|
|
return medias.slice(
|
|
|
|
start,
|
|
|
|
start + chunkSize + (index < rest ? 1 : 0),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
// flip last chunk so the very last image (often the best cumshot) is tried first
|
|
|
|
const lastPreferredChunks = preferLast
|
|
|
|
? chunks.slice(0, -1).concat(chunks.slice(-1).reverse())
|
|
|
|
: chunks;
|
|
|
|
|
2022-04-01 22:32:23 +00:00
|
|
|
const groupedMedias = lastPreferredChunks.map((mediaChunk) => {
|
2020-05-14 02:26:05 +00:00
|
|
|
// merge chunked medias into single media with grouped fallback priorities,
|
|
|
|
// so the first sources of each media is preferred over all second sources, etc.
|
2022-04-01 22:32:23 +00:00
|
|
|
const sources = mediaChunk
|
2020-05-14 02:26:05 +00:00
|
|
|
.reduce((accSources, media) => {
|
|
|
|
media.sources.forEach((source, index) => {
|
|
|
|
if (!accSources[index]) {
|
|
|
|
accSources.push([source]);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
accSources[index].push(source);
|
|
|
|
});
|
|
|
|
|
|
|
|
return accSources;
|
|
|
|
}, [])
|
|
|
|
.flat();
|
|
|
|
|
|
|
|
return {
|
2022-04-01 22:32:23 +00:00
|
|
|
id: mediaChunk[0].id,
|
|
|
|
role: mediaChunk[0].role,
|
2020-05-14 02:26:05 +00:00
|
|
|
sources,
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
|
|
|
return groupedMedias;
|
2020-04-11 20:49:37 +00:00
|
|
|
}
|
|
|
|
|
2020-03-29 02:00:46 +00:00
|
|
|
function itemsByKey(items, key) {
|
2020-05-14 02:26:05 +00:00
|
|
|
return items.reduce((acc, item) => ({ ...acc, [item[key]]: item }), {});
|
2019-11-11 02:20:00 +00:00
|
|
|
}
|
|
|
|
|
2022-09-27 18:09:46 +00:00
|
|
|
function isValidUrl(url) {
|
|
|
|
try {
|
|
|
|
const urlObject = new URL(url);
|
|
|
|
|
|
|
|
return !!urlObject;
|
|
|
|
} catch (error) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-29 02:00:46 +00:00
|
|
|
function toBaseSource(rawSource) {
|
2020-07-10 00:01:23 +00:00
|
|
|
if (rawSource && (rawSource.src || (rawSource.extract && rawSource.url) || rawSource.stream)) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const baseSource = {};
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2022-09-27 18:09:46 +00:00
|
|
|
if (rawSource.src) {
|
|
|
|
if (!isValidUrl(rawSource.src)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
baseSource.src = rawSource.src;
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (rawSource.quality) baseSource.quality = rawSource.quality;
|
|
|
|
if (rawSource.type) baseSource.type = rawSource.type;
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2022-09-27 18:09:46 +00:00
|
|
|
if (rawSource.url) {
|
|
|
|
if (!isValidUrl(rawSource.url)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
baseSource.url = rawSource.url;
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (rawSource.extract) baseSource.extract = rawSource.extract;
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2021-08-09 08:31:12 +00:00
|
|
|
if (rawSource.expectType) baseSource.expectType = rawSource.expectType;
|
|
|
|
|
2020-07-10 00:01:23 +00:00
|
|
|
if (rawSource.stream) {
|
|
|
|
baseSource.src = rawSource.stream;
|
|
|
|
baseSource.stream = rawSource.stream;
|
|
|
|
}
|
|
|
|
|
2020-09-17 00:30:58 +00:00
|
|
|
// reject source if response mimetype does not match specified type
|
|
|
|
if (rawSource.verifyType) baseSource.verifyType = rawSource.verifyType;
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (rawSource.referer) baseSource.referer = rawSource.referer;
|
|
|
|
if (rawSource.host) baseSource.host = rawSource.host;
|
2020-07-01 02:47:05 +00:00
|
|
|
if (rawSource.attempts) baseSource.attempts = rawSource.attempts;
|
2020-11-22 23:38:22 +00:00
|
|
|
if (rawSource.interval) baseSource.interval = rawSource.interval;
|
|
|
|
if (rawSource.concurrency) baseSource.concurrency = rawSource.concurrency;
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2021-02-04 00:13:02 +00:00
|
|
|
if (rawSource.vr) baseSource.vr = rawSource.vr;
|
|
|
|
|
2020-07-15 01:24:47 +00:00
|
|
|
if (rawSource.credit !== undefined) baseSource.credit = rawSource.credit;
|
2020-05-14 02:26:05 +00:00
|
|
|
if (rawSource.comment) baseSource.comment = rawSource.comment;
|
|
|
|
if (rawSource.group) baseSource.group = rawSource.group;
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2020-07-10 01:42:08 +00:00
|
|
|
if (rawSource.process) baseSource.process = rawSource.process;
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return baseSource;
|
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (typeof rawSource === 'string') {
|
2022-09-27 18:09:46 +00:00
|
|
|
if (!isValidUrl(rawSource)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2023-08-11 01:56:08 +00:00
|
|
|
if (new URL(rawSource).pathname.match(/\.(m3u8)|(mpd)$/)) {
|
2023-06-05 02:49:44 +00:00
|
|
|
return {
|
|
|
|
src: rawSource,
|
|
|
|
stream: rawSource,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return {
|
|
|
|
src: rawSource,
|
|
|
|
};
|
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2023-07-01 19:46:44 +00:00
|
|
|
if (typeof rawSource === 'function') {
|
|
|
|
return {
|
|
|
|
defer: rawSource,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return null;
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2020-12-20 03:21:28 +00:00
|
|
|
function baseSourceToBaseMedia(baseSource, role, metadata) {
|
2020-05-14 02:26:05 +00:00
|
|
|
if (Array.isArray(baseSource)) {
|
|
|
|
if (baseSource.length > 0) {
|
|
|
|
return {
|
2020-05-16 02:36:45 +00:00
|
|
|
...metadata,
|
2020-05-14 02:26:05 +00:00
|
|
|
id: nanoid(),
|
|
|
|
role,
|
|
|
|
sources: baseSource,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (baseSource) {
|
|
|
|
return {
|
2020-05-16 02:36:45 +00:00
|
|
|
...metadata,
|
2020-05-14 02:26:05 +00:00
|
|
|
id: nanoid(),
|
|
|
|
role,
|
|
|
|
sources: [baseSource],
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2021-01-24 19:43:34 +00:00
|
|
|
function sortBaseTrailersByQuality(sources, role) {
|
|
|
|
if (role === 'trailers') {
|
|
|
|
const sortedSources = sources.sort((sourceA, sourceB) => {
|
2021-02-04 00:13:02 +00:00
|
|
|
if (config.media.trailerQuality.includes(sourceB.quality) && config.media.trailerQuality.indexOf(sourceA.quality) > config.media.trailerQuality.indexOf(sourceB.quality)) {
|
2021-01-24 19:43:34 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2021-02-04 00:13:02 +00:00
|
|
|
if (config.media.trailerQuality.includes(sourceA.quality) && config.media.trailerQuality.indexOf(sourceA.quality) < config.media.trailerQuality.indexOf(sourceB.quality)) {
|
2021-01-24 19:43:34 +00:00
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
});
|
|
|
|
|
|
|
|
return sortedSources;
|
|
|
|
}
|
|
|
|
|
|
|
|
return sources;
|
|
|
|
}
|
|
|
|
|
2020-05-16 02:36:45 +00:00
|
|
|
function fallbackMediaToBaseMedia(rawMedia, role, metadata) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const baseSources = rawMedia
|
2021-11-20 22:59:15 +00:00
|
|
|
.map((source) => toBaseSource(source))
|
2020-05-14 02:26:05 +00:00
|
|
|
.filter(Boolean);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2021-01-24 19:43:34 +00:00
|
|
|
const sortedBaseSources = sortBaseTrailersByQuality(baseSources, role);
|
|
|
|
|
|
|
|
return baseSourceToBaseMedia(sortedBaseSources, role, metadata);
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2020-05-16 02:36:45 +00:00
|
|
|
function toBaseMedias(rawMedias, role, metadata) {
|
2020-05-14 02:26:05 +00:00
|
|
|
if (!rawMedias || rawMedias.length === 0) {
|
|
|
|
return [];
|
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const baseMedias = rawMedias.map((rawMedia) => {
|
|
|
|
if (!rawMedia) {
|
|
|
|
return null;
|
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (Array.isArray(rawMedia)) {
|
|
|
|
// fallback sources provided
|
2020-05-16 02:36:45 +00:00
|
|
|
return fallbackMediaToBaseMedia(rawMedia, role, metadata);
|
2020-05-14 02:26:05 +00:00
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const baseSource = toBaseSource(rawMedia);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-16 02:36:45 +00:00
|
|
|
return baseSourceToBaseMedia(baseSource, role, metadata);
|
2020-05-14 02:26:05 +00:00
|
|
|
}).filter(Boolean);
|
2020-04-11 20:49:37 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const sampledBaseMedias = sampleMedias(baseMedias);
|
2020-04-11 20:49:37 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return sampledBaseMedias;
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function findSourceDuplicates(baseMedias) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const sourceUrls = baseMedias
|
2021-11-20 22:59:15 +00:00
|
|
|
.map((baseMedia) => baseMedia.sources.map((source) => source.src))
|
2020-05-14 02:26:05 +00:00
|
|
|
.flat()
|
|
|
|
.filter(Boolean);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const extractUrls = baseMedias
|
2023-07-01 19:46:44 +00:00
|
|
|
.map((baseMedia) => baseMedia.sources.map((source) => source.extract))
|
2020-05-14 02:26:05 +00:00
|
|
|
.flat()
|
|
|
|
.filter(Boolean);
|
2020-03-24 02:48:24 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const [existingSourceMedia, existingExtractMedia] = await Promise.all([
|
2023-07-01 19:46:44 +00:00
|
|
|
// may try to check thousands of URLs at once, don't pass all of them to a single query
|
2022-04-01 22:32:23 +00:00
|
|
|
chunk(sourceUrls).reduce(async (chain, sourceUrlsChunk) => {
|
|
|
|
const accUrls = await chain;
|
|
|
|
const existingUrls = await knex('media').whereIn('source', sourceUrlsChunk);
|
|
|
|
|
|
|
|
return [...accUrls, ...existingUrls];
|
|
|
|
}, []),
|
|
|
|
chunk(extractUrls).reduce(async (chain, extractUrlsChunk) => {
|
|
|
|
const accUrls = await chain;
|
|
|
|
const existingUrls = await knex('media').whereIn('source_page', extractUrlsChunk);
|
|
|
|
|
|
|
|
return [...accUrls, ...existingUrls];
|
|
|
|
}, []),
|
2020-05-14 02:26:05 +00:00
|
|
|
]);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const existingSourceMediaByUrl = itemsByKey(existingSourceMedia, 'source');
|
|
|
|
const existingExtractMediaByUrl = itemsByKey(existingExtractMedia, 'source_page');
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2022-04-01 22:32:23 +00:00
|
|
|
return {
|
|
|
|
existingSourceMediaByUrl,
|
|
|
|
existingExtractMediaByUrl,
|
|
|
|
};
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2020-03-30 01:01:08 +00:00
|
|
|
async function findHashDuplicates(medias) {
|
2021-11-20 22:59:15 +00:00
|
|
|
const hashes = medias.map((media) => media.meta?.hash || media.entry?.hash).filter(Boolean);
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2022-04-01 22:32:23 +00:00
|
|
|
const existingHashMediaEntries = await chunk(hashes, 2).reduce(async (chain, hashesChunk) => {
|
|
|
|
const accHashes = await chain;
|
|
|
|
const existingHashes = await knex('media').whereIn('hash', hashesChunk);
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2022-04-01 22:32:23 +00:00
|
|
|
return [...accHashes, ...existingHashes];
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
const existingHashMediaEntriesByHash = itemsByKey(existingHashMediaEntries, 'hash');
|
2021-11-20 22:59:15 +00:00
|
|
|
const uniqueHashMedias = medias.filter((media) => !media.entry && !existingHashMediaEntriesByHash[media.meta?.hash]);
|
2020-04-01 23:10:50 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const { selfDuplicateMedias, selfUniqueMediasByHash } = uniqueHashMedias.reduce((acc, media) => {
|
|
|
|
if (!media.meta?.hash) {
|
|
|
|
return acc;
|
|
|
|
}
|
2020-04-08 12:50:43 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (acc.selfUniqueMediasByHash[media.meta.hash]) {
|
|
|
|
acc.selfDuplicateMedias.push({
|
|
|
|
...media,
|
|
|
|
use: acc.selfUniqueMediasByHash[media.meta.hash].id,
|
|
|
|
});
|
2020-04-01 23:10:50 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return acc;
|
|
|
|
}
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
acc.selfUniqueMediasByHash[media.meta.hash] = media;
|
2020-04-01 23:10:50 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return acc;
|
|
|
|
}, {
|
|
|
|
selfDuplicateMedias: [],
|
|
|
|
selfUniqueMediasByHash: {},
|
|
|
|
});
|
2020-04-01 23:10:50 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const selfUniqueHashMedias = Object.values(selfUniqueMediasByHash);
|
2020-04-01 23:10:50 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const existingHashMedias = medias
|
2021-11-20 22:59:15 +00:00
|
|
|
.filter((media) => existingHashMediaEntriesByHash[media.entry?.hash || media.meta?.hash])
|
|
|
|
.map((media) => ({
|
2020-05-14 02:26:05 +00:00
|
|
|
...media,
|
|
|
|
entry: existingHashMediaEntriesByHash[media.entry?.hash || media.meta?.hash],
|
|
|
|
}))
|
|
|
|
.concat(selfDuplicateMedias);
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2021-08-29 23:13:32 +00:00
|
|
|
return { uniqueHashMedias: selfUniqueHashMedias, existingHashMedias };
|
2020-03-30 01:01:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function extractSource(baseSource, { existingExtractMediaByUrl }) {
|
2023-07-01 19:46:44 +00:00
|
|
|
if (typeof baseSource.defer === 'function') {
|
|
|
|
const src = await baseSource.defer();
|
|
|
|
|
|
|
|
return {
|
|
|
|
...baseSource,
|
|
|
|
...toBaseSource(src),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (typeof baseSource.extract !== 'function' || !baseSource.url) {
|
|
|
|
return baseSource;
|
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const existingExtractMedia = existingExtractMediaByUrl[baseSource.url];
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (existingExtractMedia) {
|
|
|
|
// media entry found by extract URL
|
|
|
|
return {
|
|
|
|
...baseSource,
|
|
|
|
entry: existingExtractMedia,
|
|
|
|
};
|
|
|
|
}
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const res = await get(baseSource.url);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (res.ok) {
|
|
|
|
const src = await baseSource.extract(res.item);
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return {
|
|
|
|
...baseSource,
|
2023-07-01 19:46:44 +00:00
|
|
|
...toBaseSource(src),
|
2020-05-14 02:26:05 +00:00
|
|
|
};
|
|
|
|
}
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
throw new Error(`Could not extract source from ${baseSource.url}: ${res.status}`);
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2021-02-22 01:33:39 +00:00
|
|
|
async function storeS3Object(filepath, media) {
|
|
|
|
const fullFilepath = path.join(config.media.path, filepath);
|
|
|
|
const file = fs.createReadStream(fullFilepath);
|
|
|
|
|
2023-11-30 02:12:47 +00:00
|
|
|
const status = await new Upload({
|
|
|
|
client: s3,
|
|
|
|
params: {
|
|
|
|
Bucket: config.s3.bucket,
|
|
|
|
Body: file,
|
|
|
|
Key: filepath,
|
|
|
|
ContentType: media.meta.mimetype,
|
|
|
|
},
|
|
|
|
}).done();
|
2021-02-22 01:33:39 +00:00
|
|
|
|
|
|
|
await fsPromises.unlink(fullFilepath);
|
|
|
|
|
2021-02-22 23:54:19 +00:00
|
|
|
logger.silly(`Uploaded '${media.id}' from ${media.src} to S3 bucket '${status.Bucket}' at ${status.Location}`);
|
|
|
|
|
2021-02-22 01:33:39 +00:00
|
|
|
return status;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function writeImage(image, media, info, filepath, isProcessed) {
|
|
|
|
if (isProcessed && info.pages) {
|
|
|
|
// convert animated image to WebP and write to permanent location
|
|
|
|
await image
|
|
|
|
.webp()
|
|
|
|
.toFile(path.join(config.media.path, filepath));
|
2021-03-26 00:47:40 +00:00
|
|
|
|
|
|
|
return;
|
2021-02-22 01:33:39 +00:00
|
|
|
}
|
|
|
|
|
2022-02-12 16:16:20 +00:00
|
|
|
await image
|
|
|
|
.resize({
|
|
|
|
height: config.media.maxSize,
|
|
|
|
withoutEnlargement: true,
|
|
|
|
})
|
|
|
|
.jpeg({ quality: config.media.quality })
|
|
|
|
.toFile(path.join(config.media.path, filepath));
|
2021-02-22 01:33:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function writeThumbnail(image, thumbpath) {
|
|
|
|
return image
|
2023-08-28 00:53:35 +00:00
|
|
|
.jpeg({ quality: config.media.thumbnailQuality })
|
2021-02-22 01:33:39 +00:00
|
|
|
.resize({
|
|
|
|
height: config.media.thumbnailSize,
|
|
|
|
withoutEnlargement: true,
|
|
|
|
})
|
2021-04-04 19:52:19 +00:00
|
|
|
.rotate()
|
2021-02-22 01:33:39 +00:00
|
|
|
.toFile(path.join(config.media.path, thumbpath));
|
|
|
|
}
|
|
|
|
|
|
|
|
async function writeLazy(image, lazypath) {
|
|
|
|
return image
|
|
|
|
.resize({
|
|
|
|
height: config.media.lazySize,
|
|
|
|
withoutEnlargement: true,
|
|
|
|
})
|
|
|
|
.jpeg({ quality: config.media.lazyQuality })
|
2021-04-04 19:52:19 +00:00
|
|
|
.rotate()
|
2021-02-22 01:33:39 +00:00
|
|
|
.toFile(path.join(config.media.path, lazypath));
|
|
|
|
}
|
|
|
|
|
2020-12-20 03:21:28 +00:00
|
|
|
async function storeImageFile(media, hashDir, hashSubDir, filename, filedir, filepath, options) {
|
2020-10-30 16:37:10 +00:00
|
|
|
logger.silly(`Storing permanent media files for ${media.id} from ${media.src} at ${filepath}`);
|
2021-12-05 01:54:55 +00:00
|
|
|
logger.debug(`Memory usage at image storage: ${process.memoryUsage.rss() / 1000000} MB (${media.src})`);
|
2020-10-30 16:37:10 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
try {
|
2021-02-22 23:54:19 +00:00
|
|
|
const thumbdir = config.s3.enabled ? path.join(media.role, 'thumbs') : path.join(media.role, 'thumbs', hashDir, hashSubDir);
|
2020-09-21 03:11:24 +00:00
|
|
|
const thumbpath = path.join(thumbdir, filename);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2021-02-22 23:54:19 +00:00
|
|
|
const lazydir = config.s3.enabled ? path.join(media.role, 'lazy') : path.join(media.role, 'lazy', hashDir, hashSubDir);
|
2020-09-21 03:11:24 +00:00
|
|
|
const lazypath = path.join(lazydir, filename);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
await Promise.all([
|
|
|
|
fsPromises.mkdir(path.join(config.media.path, filedir), { recursive: true }),
|
|
|
|
fsPromises.mkdir(path.join(config.media.path, thumbdir), { recursive: true }),
|
|
|
|
fsPromises.mkdir(path.join(config.media.path, lazydir), { recursive: true }),
|
|
|
|
]);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2023-08-28 00:53:35 +00:00
|
|
|
const image = sharp(media.file.path, { pages: ['trailer', 'teaser'].includes(media.role) ? -1 : 1 }); // don't store posters as animation
|
2020-09-21 03:11:24 +00:00
|
|
|
const isProcessed = media.meta.subtype !== 'jpeg' || media.process;
|
2020-07-10 01:42:08 +00:00
|
|
|
|
2020-12-20 03:21:28 +00:00
|
|
|
const [info, stats] = await Promise.all([
|
|
|
|
image.metadata(),
|
|
|
|
options?.stats && image.stats(),
|
|
|
|
]);
|
2020-12-19 22:01:17 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
if (media.process) {
|
2020-12-20 03:21:28 +00:00
|
|
|
Object.entries(media.process).forEach(([operation, processOptions]) => {
|
2020-09-21 03:11:24 +00:00
|
|
|
if (image[operation]) {
|
2020-12-20 03:21:28 +00:00
|
|
|
image[operation](...(Array.isArray(processOptions) ? processOptions : [processOptions]));
|
2020-09-21 03:11:24 +00:00
|
|
|
return;
|
|
|
|
}
|
2020-07-10 01:42:08 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
if (operation === 'crop') {
|
2020-12-20 03:21:28 +00:00
|
|
|
image.extract(...(Array.isArray(processOptions) ? processOptions : [processOptions]));
|
2020-09-21 03:11:24 +00:00
|
|
|
return;
|
|
|
|
}
|
2020-07-10 01:42:08 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
logger.warn(`Unknown image operation on ${media.id} (${media.src}): ${operation}`);
|
|
|
|
});
|
|
|
|
}
|
2020-07-10 01:42:08 +00:00
|
|
|
|
2022-02-12 16:16:20 +00:00
|
|
|
await writeImage(image, media, info, filepath, isProcessed);
|
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
await Promise.all([
|
2023-08-28 00:53:35 +00:00
|
|
|
writeThumbnail(image, thumbpath, info),
|
|
|
|
writeLazy(image, lazypath, info),
|
2020-09-21 03:11:24 +00:00
|
|
|
]);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2022-02-12 16:16:20 +00:00
|
|
|
/*
|
2020-09-21 03:11:24 +00:00
|
|
|
if (isProcessed) {
|
2021-02-22 01:33:39 +00:00
|
|
|
// file already stored, remove temporary file
|
2020-09-21 03:11:24 +00:00
|
|
|
await fsPromises.unlink(media.file.path);
|
|
|
|
} else {
|
2021-02-22 01:33:39 +00:00
|
|
|
// image not processed, simply move temporary file to final location
|
2020-09-21 03:11:24 +00:00
|
|
|
await fsPromises.rename(media.file.path, path.join(config.media.path, filepath));
|
|
|
|
}
|
2022-02-12 16:16:20 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
await fsPromises.unlink(media.file.path);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2021-02-22 01:33:39 +00:00
|
|
|
if (config.s3.enabled) {
|
|
|
|
await Promise.all([
|
|
|
|
storeS3Object(filepath, media),
|
|
|
|
storeS3Object(thumbpath, media),
|
|
|
|
storeS3Object(lazypath, media),
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
logger.silly(`Stored thumbnail, lazy and permanent media file for ${media.id} from ${media.src} at ${filepath}`);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
return {
|
|
|
|
...media,
|
|
|
|
file: {
|
|
|
|
path: filepath,
|
|
|
|
thumbnail: thumbpath,
|
|
|
|
lazy: lazypath,
|
|
|
|
},
|
|
|
|
meta: {
|
|
|
|
...media.meta,
|
2021-04-04 19:52:19 +00:00
|
|
|
// 6 or 8 implies image is sideways, and size is not inherently adjusted for orientation
|
|
|
|
width: info.orientation === 6 || info.orientation === 8 ? info.height : info.width,
|
|
|
|
height: info.orientation === 6 || info.orientation === 8 ? info.width : info.height,
|
2020-12-20 03:21:28 +00:00
|
|
|
entropy: stats?.entropy || null,
|
|
|
|
sharpness: stats?.sharpness || null,
|
2020-09-21 03:11:24 +00:00
|
|
|
},
|
|
|
|
};
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(`Failed to store ${media.id} from ${media.src} at ${filepath}: ${error.message}`);
|
|
|
|
|
|
|
|
await fsPromises.unlink(media.file.path);
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
2020-05-06 23:53:07 +00:00
|
|
|
}
|
|
|
|
|
2020-12-20 03:21:28 +00:00
|
|
|
async function storeFile(media, options) {
|
2020-05-14 02:26:05 +00:00
|
|
|
try {
|
|
|
|
const hashDir = media.meta.hash.slice(0, 2);
|
|
|
|
const hashSubDir = media.meta.hash.slice(2, 4);
|
2021-02-22 23:54:19 +00:00
|
|
|
const hashFilename = config.s3.enabled ? media.meta.hash : media.meta.hash.slice(4);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
|
|
|
const filename = media.quality
|
|
|
|
? `${hashFilename}_${media.quality}.${media.meta.extension}`
|
|
|
|
: `${hashFilename}.${media.meta.extension}`;
|
|
|
|
|
2021-02-22 23:54:19 +00:00
|
|
|
const filedir = config.s3.enabled ? media.role : path.join(media.role, hashDir, hashSubDir);
|
2020-05-14 02:26:05 +00:00
|
|
|
const filepath = path.join(filedir, filename);
|
|
|
|
|
2023-07-02 19:06:38 +00:00
|
|
|
if (argv.forceMedia) {
|
2020-09-21 03:11:24 +00:00
|
|
|
try {
|
|
|
|
// remove old file to in case rename() does not overwrite (possibly on NFS setups)
|
|
|
|
await fsPromises.unlink(path.join(config.media.path, filepath));
|
|
|
|
} catch (error) {
|
|
|
|
// file probably didn't exist
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-11 00:46:11 +00:00
|
|
|
if (media.meta.type === 'image') {
|
2020-12-20 03:21:28 +00:00
|
|
|
return storeImageFile(media, hashDir, hashSubDir, filename, filedir, filepath, options);
|
2020-05-14 02:26:05 +00:00
|
|
|
}
|
|
|
|
|
2023-07-25 01:03:41 +00:00
|
|
|
if (['posters', 'photos', 'caps', 'covers'].includes(media.role)) {
|
2021-02-13 03:49:00 +00:00
|
|
|
throw new Error(`Media for '${media.role}' must be an image, but '${media.meta.mimetype}' was detected`);
|
|
|
|
}
|
|
|
|
|
2021-02-27 17:05:06 +00:00
|
|
|
if (['teasers', 'trailers'].includes(media.role) && media.meta.type !== 'video') {
|
|
|
|
throw new Error(`Media for '${media.role}' must be a video, but '${media.meta.mimetype}' was detected in ${media.src}`);
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const [stat] = await Promise.all([
|
|
|
|
fsPromises.stat(media.file.path),
|
|
|
|
fsPromises.mkdir(path.join(config.media.path, filedir), { recursive: true }),
|
|
|
|
]);
|
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
// move temp file to permanent location
|
2020-05-14 02:26:05 +00:00
|
|
|
await fsPromises.rename(media.file.path, path.join(config.media.path, filepath));
|
|
|
|
|
2021-02-22 23:54:19 +00:00
|
|
|
if (config.s3.enabled) {
|
|
|
|
// upload the file to S3 storage, will remove original
|
|
|
|
await storeS3Object(filepath, media);
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
logger.silly(`Stored permanent media file for ${media.id} from ${media.src} at ${filepath}`);
|
|
|
|
|
|
|
|
return {
|
|
|
|
...media,
|
|
|
|
file: {
|
|
|
|
path: filepath,
|
|
|
|
},
|
|
|
|
meta: {
|
|
|
|
...media.meta,
|
|
|
|
size: stat.size,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
} catch (error) {
|
|
|
|
logger.warn(`Failed to store ${media.src}: ${error.message}`);
|
|
|
|
|
2023-08-28 00:53:35 +00:00
|
|
|
try {
|
|
|
|
await fsPromises.unlink(media.file.path);
|
|
|
|
} catch (unlinkError) {
|
|
|
|
logger.warn(`Failed to unlink ${media.file.path} from ${media.src}: ${unlinkError.message}`);
|
|
|
|
}
|
2020-11-22 03:07:09 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return null;
|
|
|
|
}
|
2020-03-31 02:05:31 +00:00
|
|
|
}
|
|
|
|
|
2020-07-10 00:01:23 +00:00
|
|
|
async function fetchHttpSource(source, tempFileTarget, hashStream) {
|
|
|
|
const res = await http.get(source.src, {
|
2020-11-22 03:07:09 +00:00
|
|
|
headers: {
|
|
|
|
...(source.referer && { referer: source.referer }),
|
|
|
|
...(source.host && { host: source.host }),
|
|
|
|
},
|
2020-07-10 00:01:23 +00:00
|
|
|
stream: true, // sources are fetched in parallel, don't gobble up memory
|
|
|
|
transforms: [hashStream],
|
|
|
|
destination: tempFileTarget,
|
2020-11-22 23:38:22 +00:00
|
|
|
...(source.interval && { interval: source.interval }),
|
|
|
|
...(source.concurrency && { concurrency: source.concurrency }),
|
2020-07-10 00:01:23 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
throw new Error(`Response ${res.status} not OK`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2021-08-09 08:31:12 +00:00
|
|
|
mimetype: (source.expectType
|
|
|
|
? source.expectType[res.headers['content-type']]
|
|
|
|
: res.headers['content-type'])
|
|
|
|
|| mime.getType(new URL(source.src).pathname),
|
2020-07-10 00:01:23 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-08-17 13:53:20 +00:00
|
|
|
streamQueue.define('fetchStreamSource', async ({ source, tempFileTarget, hashStream }) => {
|
2020-07-17 01:39:13 +00:00
|
|
|
const meta = { mimetype: 'video/mp4' };
|
2020-07-10 00:01:23 +00:00
|
|
|
|
2020-07-17 01:39:13 +00:00
|
|
|
const video = ffmpeg(source.stream)
|
|
|
|
.format('mp4')
|
|
|
|
.outputOptions(['-movflags frag_keyframe+empty_moov'])
|
2021-11-20 22:59:15 +00:00
|
|
|
.on('start', (cmd) => logger.verbose(`Fetching stream from ${source.stream} with "${cmd}"`))
|
|
|
|
.on('error', (error) => logger.error(`Failed to fetch stream from ${source.stream}: ${error.message}`))
|
2020-07-17 01:39:13 +00:00
|
|
|
.pipe();
|
2020-07-10 00:01:23 +00:00
|
|
|
|
2023-06-10 23:17:37 +00:00
|
|
|
// await pipeline(video, hashStream, tempFileTarget);
|
|
|
|
await stream.promises.pipeline(video, hashStream, tempFileTarget);
|
2020-07-10 00:01:23 +00:00
|
|
|
|
2020-07-17 01:39:13 +00:00
|
|
|
logger.verbose(`Finished fetching stream from ${source.stream}`);
|
|
|
|
|
|
|
|
return meta;
|
2020-08-17 13:53:20 +00:00
|
|
|
}, {
|
|
|
|
concurrency: config.media.streamConcurrency,
|
|
|
|
});
|
2020-07-10 00:01:23 +00:00
|
|
|
|
2020-04-26 01:51:59 +00:00
|
|
|
async function fetchSource(source, baseMedia) {
|
2023-07-05 22:30:04 +00:00
|
|
|
const maxAttempts = source.attempts || argv.mediaAttempts;
|
2020-09-17 00:30:58 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
logger.silly(`Fetching media from ${source.src}`);
|
2021-12-27 16:29:23 +00:00
|
|
|
logger.debug(`Memory usage before media fetch: ${process.memoryUsage.rss() / 1000000} MB (${source.src})`);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2023-06-18 00:12:13 +00:00
|
|
|
if (source.stream && !config.media.fetchStreams) {
|
|
|
|
throw new Error(`Stream fetching disabled, ignoring ${source.stream}`);
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
async function attempt(attempts = 1) {
|
2020-07-10 00:01:23 +00:00
|
|
|
const hasher = new blake2.Hash('blake2b', { digestLength: 24 });
|
2021-02-05 02:13:10 +00:00
|
|
|
let hasherReady = true;
|
2020-07-10 00:01:23 +00:00
|
|
|
hasher.setEncoding('hex');
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
try {
|
|
|
|
const tempFilePath = path.join(config.media.path, 'temp', `${baseMedia.id}`);
|
|
|
|
const tempFileTarget = fs.createWriteStream(tempFilePath);
|
2020-07-10 00:01:23 +00:00
|
|
|
const hashStream = new stream.PassThrough();
|
2020-05-14 02:26:05 +00:00
|
|
|
let size = 0;
|
|
|
|
|
2022-04-01 22:32:23 +00:00
|
|
|
hashStream.on('data', (streamChunk) => {
|
|
|
|
size += streamChunk.length;
|
2021-02-05 02:13:10 +00:00
|
|
|
|
|
|
|
if (hasherReady) {
|
2022-04-01 22:32:23 +00:00
|
|
|
hasher.write(streamChunk);
|
2021-02-05 02:13:10 +00:00
|
|
|
}
|
2020-05-14 02:26:05 +00:00
|
|
|
});
|
|
|
|
|
2020-07-10 00:01:23 +00:00
|
|
|
const { mimetype } = source.stream
|
2020-08-17 13:53:20 +00:00
|
|
|
? await streamQueue.push('fetchStreamSource', { source, tempFileTarget, hashStream })
|
2020-07-10 00:01:23 +00:00
|
|
|
: await fetchHttpSource(source, tempFileTarget, hashStream);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
|
|
|
hasher.end();
|
|
|
|
|
|
|
|
const hash = hasher.read();
|
|
|
|
const [type, subtype] = mimetype.split('/');
|
|
|
|
const extension = mime.getExtension(mimetype);
|
|
|
|
|
2020-09-17 00:30:58 +00:00
|
|
|
if (source.verifyType && source.verifyType !== type) {
|
|
|
|
throw Object.assign(new Error(`Type '${type}' does not match type '${source.verifyType}' specified by source`), { code: 'VERIFY_TYPE' });
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return {
|
|
|
|
...source,
|
|
|
|
file: {
|
|
|
|
path: tempFilePath,
|
|
|
|
},
|
|
|
|
meta: {
|
|
|
|
hash,
|
|
|
|
mimetype,
|
|
|
|
extension,
|
|
|
|
type,
|
|
|
|
subtype,
|
|
|
|
size,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
} catch (error) {
|
2021-02-05 02:13:10 +00:00
|
|
|
hasherReady = false;
|
2020-07-10 00:01:23 +00:00
|
|
|
hasher.end();
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2020-09-17 00:30:58 +00:00
|
|
|
if (error.code !== 'VERIFY_TYPE') {
|
|
|
|
logger.warn(`Failed attempt ${attempts}/${maxAttempts} to fetch ${source.src}: ${error.message}`);
|
2020-07-01 02:47:05 +00:00
|
|
|
|
2020-09-17 00:30:58 +00:00
|
|
|
if (attempts < maxAttempts) {
|
|
|
|
await Promise.delay(1000);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2020-09-17 00:30:58 +00:00
|
|
|
return attempt(attempts + 1);
|
|
|
|
}
|
2020-05-14 02:26:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`Failed to fetch ${source.src}: ${error.message}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return attempt(1);
|
2020-03-30 01:01:08 +00:00
|
|
|
}
|
|
|
|
|
2020-04-26 01:51:59 +00:00
|
|
|
async function trySource(baseSource, existingMedias, baseMedia) {
|
2020-05-14 02:26:05 +00:00
|
|
|
// catch error and try the next source
|
|
|
|
const extractedSource = await extractSource(baseSource, existingMedias);
|
|
|
|
const existingSourceMedia = existingMedias.existingSourceMediaByUrl[extractedSource.src];
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2023-07-02 19:06:38 +00:00
|
|
|
if (!argv.forceMedia && extractedSource.entry) {
|
2020-05-14 02:26:05 +00:00
|
|
|
logger.silly(`Media page URL already in database, not extracting ${baseSource.url}`);
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
// media entry found during extraction, don't fetch
|
|
|
|
return extractedSource;
|
|
|
|
}
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2023-07-02 19:06:38 +00:00
|
|
|
if (!argv.forceMedia && existingSourceMedia) {
|
2020-05-14 02:26:05 +00:00
|
|
|
logger.silly(`Media source URL already in database, skipping ${baseSource.src}`);
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
// media entry found by source URL, don't fetch
|
|
|
|
return {
|
|
|
|
...baseSource,
|
|
|
|
entry: existingSourceMedia,
|
|
|
|
};
|
|
|
|
}
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2021-02-21 21:17:25 +00:00
|
|
|
const source = await fetchSource(extractedSource, baseMedia);
|
|
|
|
|
|
|
|
return {
|
|
|
|
...source,
|
|
|
|
entry: extractedSource.entry || existingSourceMedia,
|
|
|
|
};
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchMedia(baseMedia, existingMedias) {
|
2020-05-14 02:26:05 +00:00
|
|
|
try {
|
|
|
|
const source = await baseMedia.sources.reduce(
|
|
|
|
// try each source until success
|
|
|
|
(result, baseSource, baseSourceIndex) => result.catch(async (error) => {
|
|
|
|
if (error.message) {
|
|
|
|
logger.warn(error.message);
|
|
|
|
}
|
|
|
|
|
|
|
|
return trySource(baseSource, existingMedias, baseMedia, baseSourceIndex);
|
|
|
|
}),
|
|
|
|
Promise.reject(new Error()),
|
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
...baseMedia,
|
|
|
|
...source,
|
|
|
|
};
|
|
|
|
} catch (error) {
|
|
|
|
logger.warn(error.message);
|
|
|
|
|
|
|
|
return baseMedia;
|
|
|
|
}
|
2020-03-30 01:01:08 +00:00
|
|
|
}
|
|
|
|
|
2020-03-31 02:05:31 +00:00
|
|
|
function curateMediaEntry(media, index) {
|
2020-05-14 02:26:05 +00:00
|
|
|
if (media.entry) {
|
|
|
|
return media;
|
|
|
|
}
|
|
|
|
|
|
|
|
const curatedMediaEntry = {
|
|
|
|
id: media.id,
|
|
|
|
path: media.file.path,
|
|
|
|
thumbnail: media.file.thumbnail,
|
|
|
|
lazy: media.file.lazy,
|
2021-02-22 01:33:39 +00:00
|
|
|
is_s3: config.s3.enabled,
|
2020-05-14 02:26:05 +00:00
|
|
|
index,
|
|
|
|
mime: media.meta.mimetype,
|
|
|
|
hash: media.meta.hash,
|
|
|
|
size: media.meta.size,
|
|
|
|
width: media.meta.width,
|
|
|
|
height: media.meta.height,
|
2021-02-04 02:06:19 +00:00
|
|
|
is_vr: media.vr,
|
2020-05-14 02:26:05 +00:00
|
|
|
entropy: media.meta.entropy,
|
2020-12-20 03:21:28 +00:00
|
|
|
sharpness: media.meta.sharpness,
|
2020-05-14 02:26:05 +00:00
|
|
|
source: media.src,
|
|
|
|
source_page: media.url,
|
|
|
|
scraper: media.scraper,
|
2020-07-15 01:24:47 +00:00
|
|
|
credit: media.credit,
|
2020-05-14 02:26:05 +00:00
|
|
|
comment: media.comment,
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
...media,
|
|
|
|
newEntry: true,
|
|
|
|
entry: curatedMediaEntry,
|
|
|
|
};
|
2020-03-31 02:05:31 +00:00
|
|
|
}
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-12-20 03:21:28 +00:00
|
|
|
async function storeMedias(baseMedias, options) {
|
2020-05-14 02:26:05 +00:00
|
|
|
await fsPromises.mkdir(path.join(config.media.path, 'temp'), { recursive: true });
|
2020-04-26 01:51:59 +00:00
|
|
|
|
2021-08-29 23:13:32 +00:00
|
|
|
const { existingSourceMediaByUrl, existingExtractMediaByUrl } = await findSourceDuplicates(baseMedias);
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const fetchedMedias = await Promise.map(
|
|
|
|
baseMedias,
|
2021-11-20 22:59:15 +00:00
|
|
|
async (baseMedia) => fetchMedia(baseMedia, { existingSourceMediaByUrl, existingExtractMediaByUrl }),
|
2021-12-05 01:54:55 +00:00
|
|
|
// { concurrency: 100 }, // don't overload disk (or network, although this has its own throttling)
|
|
|
|
{ concurrency: 10 }, // don't overload disk (or network, although this has its own throttling)
|
2020-05-14 02:26:05 +00:00
|
|
|
);
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2021-08-29 23:13:32 +00:00
|
|
|
const { uniqueHashMedias, existingHashMedias } = await findHashDuplicates(fetchedMedias);
|
2020-05-06 23:53:07 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const savedMedias = await Promise.map(
|
2020-07-12 22:12:01 +00:00
|
|
|
uniqueHashMedias,
|
2021-11-20 22:59:15 +00:00
|
|
|
async (baseMedia) => storeFile(baseMedia, options),
|
2020-10-30 16:37:10 +00:00
|
|
|
{ concurrency: 100 }, // don't overload disk
|
2020-05-14 02:26:05 +00:00
|
|
|
);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2023-07-02 19:06:38 +00:00
|
|
|
if (argv.forceMedia) {
|
2020-07-12 22:12:01 +00:00
|
|
|
// overwrite files in case image processing was changed
|
|
|
|
await Promise.map(
|
|
|
|
existingHashMedias,
|
2021-11-20 22:59:15 +00:00
|
|
|
async (baseMedia) => storeFile(baseMedia, options),
|
2020-10-30 16:37:10 +00:00
|
|
|
{ concurrency: 100 }, // don't overload disk
|
2020-07-12 22:12:01 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-11-22 03:07:09 +00:00
|
|
|
const newMediaWithEntries = savedMedias.filter(Boolean).map((media, index) => curateMediaEntry(media, index));
|
2021-11-20 22:59:15 +00:00
|
|
|
const newMediaEntries = newMediaWithEntries.filter((media) => media.newEntry).map((media) => media.entry);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2021-02-08 03:29:12 +00:00
|
|
|
try {
|
2021-08-29 23:13:32 +00:00
|
|
|
await bulkInsert('media', newMediaEntries, false);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2021-02-08 03:29:12 +00:00
|
|
|
return [...newMediaWithEntries, ...existingHashMedias];
|
|
|
|
} catch (error) {
|
|
|
|
throw Object.assign(error, { entries: newMediaEntries });
|
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2020-08-20 02:57:38 +00:00
|
|
|
async function associateReleaseMedia(releases, type = 'release') {
|
2020-05-14 02:26:05 +00:00
|
|
|
if (!argv.media) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const baseMediasByReleaseId = releases.reduce((acc, release) => ({
|
|
|
|
...acc,
|
|
|
|
[release.id]: [
|
|
|
|
...(argv.images && argv.poster ? toBaseMedias([release.poster], 'posters') : []),
|
2020-11-01 01:58:21 +00:00
|
|
|
...(argv.images && argv.covers ? toBaseMedias(release.covers, 'covers') : []),
|
2020-05-14 02:26:05 +00:00
|
|
|
...(argv.images && argv.photos ? toBaseMedias(release.photos, 'photos') : []),
|
2023-07-25 01:03:41 +00:00
|
|
|
...(argv.images && argv.caps ? toBaseMedias(release.caps, 'caps') : []),
|
2020-05-14 02:26:05 +00:00
|
|
|
...(argv.videos && argv.trailer ? toBaseMedias([release.trailer], 'trailers') : []),
|
|
|
|
...(argv.videos && argv.teaser ? toBaseMedias([release.teaser], 'teasers') : []),
|
|
|
|
],
|
|
|
|
}), {});
|
|
|
|
|
|
|
|
const baseMediasByRole = Object.values(baseMediasByReleaseId)
|
|
|
|
.flat()
|
|
|
|
.filter(Boolean)
|
|
|
|
.reduce((acc, baseMedia) => {
|
|
|
|
if (!acc[baseMedia.role]) acc[baseMedia.role] = [];
|
|
|
|
acc[baseMedia.role].push(baseMedia);
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, {});
|
|
|
|
|
2023-07-25 01:03:41 +00:00
|
|
|
await Promise.reduce(['posters', 'covers', 'photos', 'caps', 'teasers', 'trailers'], async (chain, role) => {
|
2020-05-14 02:26:05 +00:00
|
|
|
// stage by role so posters are prioritized over photos and videos
|
|
|
|
await chain;
|
|
|
|
|
|
|
|
const baseMedias = baseMediasByRole[role];
|
|
|
|
|
|
|
|
if (!baseMedias) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-02-05 02:37:04 +00:00
|
|
|
try {
|
|
|
|
const storedMedias = await storeMedias(baseMedias);
|
|
|
|
const storedMediasById = itemsByKey(storedMedias, 'id');
|
|
|
|
|
|
|
|
const associations = Object
|
|
|
|
.entries(baseMediasByReleaseId)
|
|
|
|
.reduce((acc, [releaseId, releaseBaseMedias]) => {
|
|
|
|
releaseBaseMedias.forEach((baseMedia) => {
|
|
|
|
const media = storedMediasById[baseMedia.id];
|
2023-07-02 21:59:49 +00:00
|
|
|
const mediaId = (storedMediasById[media?.use] && media?.use) || media?.entry?.id;
|
2021-02-05 02:37:04 +00:00
|
|
|
|
2022-02-07 00:57:09 +00:00
|
|
|
if (mediaId) {
|
2021-02-05 02:37:04 +00:00
|
|
|
acc.push({
|
|
|
|
[`${type}_id`]: releaseId,
|
2022-01-28 03:05:29 +00:00
|
|
|
media_id: mediaId,
|
2021-02-05 02:37:04 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, [])
|
|
|
|
.filter(Boolean);
|
|
|
|
|
2022-01-30 21:15:07 +00:00
|
|
|
if (associations.length > 0) {
|
|
|
|
await bulkInsert(`${type}s_${role}`, associations, false);
|
2021-02-05 02:37:04 +00:00
|
|
|
}
|
|
|
|
} catch (error) {
|
2022-01-28 03:05:29 +00:00
|
|
|
if (error.entries) {
|
|
|
|
logger.error(util.inspect(error.entries, null, null, { color: true }));
|
|
|
|
}
|
|
|
|
|
2023-07-29 21:59:17 +00:00
|
|
|
logger.error(`Failed to store ${type} ${role}: ${error.message} (${error.detail || 'no detail'})`);
|
2020-05-14 02:26:05 +00:00
|
|
|
}
|
|
|
|
}, Promise.resolve());
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2020-05-16 02:36:45 +00:00
|
|
|
async function associateAvatars(profiles) {
|
|
|
|
if (!argv.media) {
|
|
|
|
return profiles;
|
|
|
|
}
|
|
|
|
|
2021-11-20 22:59:15 +00:00
|
|
|
const profilesWithBaseMedias = profiles.map((profile) => (profile.avatar
|
2020-05-16 02:36:45 +00:00
|
|
|
? {
|
|
|
|
...profile,
|
|
|
|
avatarBaseMedia: toBaseMedias([profile.avatar], 'avatars', {
|
2020-12-19 22:01:17 +00:00
|
|
|
credit: profile.credit || profile.entity?.name || null,
|
2020-05-16 02:36:45 +00:00
|
|
|
scraper: profile.scraper || null,
|
2020-12-20 03:21:28 +00:00
|
|
|
})[0],
|
2020-05-16 02:36:45 +00:00
|
|
|
}
|
|
|
|
: profile
|
|
|
|
));
|
|
|
|
|
2021-11-20 22:59:15 +00:00
|
|
|
const baseMedias = profilesWithBaseMedias.map((profile) => profile.avatarBaseMedia).filter(Boolean);
|
2020-05-16 02:36:45 +00:00
|
|
|
|
2020-12-20 03:21:28 +00:00
|
|
|
const storedMedias = await storeMedias(baseMedias, { stats: true });
|
2020-05-16 02:36:45 +00:00
|
|
|
const storedMediasById = itemsByKey(storedMedias, 'id');
|
|
|
|
|
|
|
|
const profilesWithAvatarIds = profilesWithBaseMedias.map((profile) => {
|
|
|
|
const media = storedMediasById[profile.avatarBaseMedia?.id];
|
|
|
|
|
|
|
|
if (media) {
|
|
|
|
return {
|
|
|
|
...profile,
|
|
|
|
avatarMediaId: media.use || media.entry.id,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return profile;
|
|
|
|
});
|
|
|
|
|
|
|
|
return profilesWithAvatarIds;
|
|
|
|
}
|
|
|
|
|
2021-02-23 00:30:38 +00:00
|
|
|
async function deleteS3Objects(media) {
|
|
|
|
const objects = media
|
2021-11-20 22:59:15 +00:00
|
|
|
.map((item) => [
|
2021-02-23 00:30:38 +00:00
|
|
|
{ Key: item.path },
|
|
|
|
{ Key: item.thumbnail },
|
|
|
|
{ Key: item.lazy },
|
|
|
|
])
|
|
|
|
.flat()
|
2021-11-20 22:59:15 +00:00
|
|
|
.filter((item) => item.Key);
|
2021-02-23 00:30:38 +00:00
|
|
|
|
|
|
|
const status = await s3.deleteObjects({
|
|
|
|
Bucket: config.s3.bucket,
|
|
|
|
Delete: {
|
|
|
|
Objects: objects,
|
|
|
|
Quiet: false,
|
|
|
|
},
|
2023-11-30 02:12:47 +00:00
|
|
|
});
|
2021-02-23 00:30:38 +00:00
|
|
|
|
|
|
|
logger.info(`Removed ${status.Deleted.length} media files from S3 bucket '${config.s3.bucket}', ${status.Errors.length} errors`);
|
|
|
|
|
|
|
|
return status;
|
|
|
|
}
|
|
|
|
|
2020-10-24 22:52:40 +00:00
|
|
|
async function flushOrphanedMedia() {
|
|
|
|
const orphanedMedia = await knex('media')
|
|
|
|
.where('is_sfw', false)
|
|
|
|
.whereNotExists(
|
|
|
|
knex
|
|
|
|
.from(
|
|
|
|
knex('tags_posters')
|
|
|
|
.select('media_id')
|
|
|
|
.unionAll(
|
|
|
|
knex('tags_photos').select('media_id'),
|
|
|
|
knex('releases_posters').select('media_id'),
|
|
|
|
knex('releases_photos').select('media_id'),
|
2023-07-25 01:03:41 +00:00
|
|
|
knex('releases_caps').select('media_id'),
|
2020-10-27 01:40:30 +00:00
|
|
|
knex('releases_covers').select('media_id'),
|
2020-10-24 22:52:40 +00:00
|
|
|
knex('releases_trailers').select('media_id'),
|
|
|
|
knex('releases_teasers').select('media_id'),
|
|
|
|
knex('movies_covers').select('media_id'),
|
|
|
|
knex('movies_trailers').select('media_id'),
|
2020-12-30 01:23:43 +00:00
|
|
|
knex('actors').select(knex.raw('avatar_media_id as media_id')),
|
2020-10-27 01:34:06 +00:00
|
|
|
knex('actors_profiles').select(knex.raw('avatar_media_id as media_id')),
|
2020-10-24 22:52:40 +00:00
|
|
|
knex('actors_photos').select('media_id'),
|
2021-02-26 23:37:22 +00:00
|
|
|
knex('chapters_photos').select('media_id'),
|
|
|
|
knex('chapters_posters').select('media_id'),
|
2020-10-24 22:52:40 +00:00
|
|
|
)
|
|
|
|
.as('associations'),
|
|
|
|
)
|
|
|
|
.whereRaw('associations.media_id = media.id'),
|
|
|
|
)
|
2021-02-23 00:30:38 +00:00
|
|
|
.returning(['media.id', 'media.is_s3', 'media.path', 'media.thumbnail', 'media.lazy'])
|
2020-10-24 22:52:40 +00:00
|
|
|
.delete();
|
|
|
|
|
2023-06-03 00:51:42 +00:00
|
|
|
if (argv.flushMediaFiles) {
|
|
|
|
await Promise.all(orphanedMedia.filter((media) => !media.is_s3).map((media) => Promise.all([
|
|
|
|
media.path && fsPromises.unlink(path.join(config.media.path, media.path)).catch(() => { /* probably file not found */ }),
|
|
|
|
media.thumbnail && fsPromises.unlink(path.join(config.media.path, media.thumbnail)).catch(() => { /* probably file not found */ }),
|
|
|
|
media.lazy && fsPromises.unlink(path.join(config.media.path, media.lazy)).catch(() => { /* probably file not found */ }),
|
|
|
|
])));
|
2020-10-24 22:52:40 +00:00
|
|
|
|
2023-06-03 00:51:42 +00:00
|
|
|
if (config.s3.enabled) {
|
|
|
|
await deleteS3Objects(orphanedMedia.filter((media) => media.is_s3));
|
|
|
|
}
|
2020-10-24 22:52:40 +00:00
|
|
|
|
2023-06-03 00:51:42 +00:00
|
|
|
logger.info(`Removed ${orphanedMedia.length} media files from database and storage`);
|
|
|
|
} else {
|
|
|
|
logger.info(`Removed ${orphanedMedia.length} media files from database, but not from storage`);
|
2021-02-23 00:30:38 +00:00
|
|
|
}
|
|
|
|
|
2022-03-04 22:31:59 +00:00
|
|
|
try {
|
|
|
|
await fsPromises.rm(path.join(config.media.path, 'temp'), { recursive: true });
|
|
|
|
logger.info('Cleared temporary media directory');
|
|
|
|
} catch (error) {
|
|
|
|
logger.warn(`Failed to clear temporary media directory: ${error.message}`);
|
|
|
|
}
|
2020-10-24 22:52:40 +00:00
|
|
|
}
|
|
|
|
|
2020-03-29 02:00:46 +00:00
|
|
|
module.exports = {
|
2020-05-16 02:36:45 +00:00
|
|
|
associateAvatars,
|
2020-05-14 02:26:05 +00:00
|
|
|
associateReleaseMedia,
|
2020-10-24 22:52:40 +00:00
|
|
|
flushOrphanedMedia,
|
2019-11-11 02:20:00 +00:00
|
|
|
};
|