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');
|
2020-03-29 02:00:46 +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');
|
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');
|
2020-03-29 02:00:46 +00:00
|
|
|
const { get } = require('./utils/qu');
|
|
|
|
|
2020-07-10 00:01:23 +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
|
|
|
|
2020-04-11 20:49:37 +00:00
|
|
|
function sampleMedias(medias, limit = config.media.limit, 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;
|
|
|
|
|
|
|
|
const groupedMedias = lastPreferredChunks.map((chunk) => {
|
|
|
|
// merge chunked medias into single media with grouped fallback priorities,
|
|
|
|
// so the first sources of each media is preferred over all second sources, etc.
|
|
|
|
const sources = chunk
|
|
|
|
.reduce((accSources, media) => {
|
|
|
|
media.sources.forEach((source, index) => {
|
|
|
|
if (!accSources[index]) {
|
|
|
|
accSources.push([source]);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
accSources[index].push(source);
|
|
|
|
});
|
|
|
|
|
|
|
|
return accSources;
|
|
|
|
}, [])
|
|
|
|
.flat();
|
|
|
|
|
|
|
|
return {
|
|
|
|
id: chunk[0].id,
|
|
|
|
role: chunk[0].role,
|
|
|
|
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
|
|
|
}
|
|
|
|
|
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
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (rawSource.src) baseSource.src = rawSource.src;
|
|
|
|
if (rawSource.quality) baseSource.quality = rawSource.quality;
|
|
|
|
if (rawSource.type) baseSource.type = rawSource.type;
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (rawSource.url) baseSource.url = rawSource.url;
|
|
|
|
if (rawSource.extract) baseSource.extract = rawSource.extract;
|
2020-03-29 02:00:46 +00:00
|
|
|
|
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;
|
|
|
|
if (rawSource.queueMethod) baseSource.queueMethod = rawSource.queueMethod;
|
2020-03-30 01:01:08 +00:00
|
|
|
|
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') {
|
|
|
|
return {
|
|
|
|
src: rawSource,
|
|
|
|
};
|
|
|
|
}
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return null;
|
2020-03-29 02:00:46 +00:00
|
|
|
}
|
|
|
|
|
2020-05-16 02:36:45 +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
|
|
|
}
|
|
|
|
|
2020-05-16 02:36:45 +00:00
|
|
|
function fallbackMediaToBaseMedia(rawMedia, role, metadata) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const baseSources = rawMedia
|
|
|
|
.map(source => toBaseSource(source))
|
|
|
|
.filter(Boolean);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-16 02:36:45 +00:00
|
|
|
return baseSourceToBaseMedia(baseSources, 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
|
|
|
|
.map(baseMedia => baseMedia.sources.map(source => source.src))
|
|
|
|
.flat()
|
|
|
|
.filter(Boolean);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const extractUrls = baseMedias
|
|
|
|
.map(baseMedia => baseMedia.sources.map(source => source.url))
|
|
|
|
.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([
|
|
|
|
knex('media').whereIn('source', sourceUrls),
|
|
|
|
knex('media').whereIn('source_page', extractUrls),
|
|
|
|
]);
|
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
|
|
|
|
2020-05-14 02:26:05 +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) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const hashes = medias.map(media => media.meta?.hash || media.entry?.hash).filter(Boolean);
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const existingHashMediaEntries = await knex('media').whereIn('hash', hashes);
|
|
|
|
const existingHashMediaEntriesByHash = itemsByKey(existingHashMediaEntries, 'hash');
|
2020-03-31 02:05:31 +00:00
|
|
|
|
2020-05-14 02:26:05 +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
|
|
|
|
.filter(media => existingHashMediaEntriesByHash[media.entry?.hash || media.meta?.hash])
|
|
|
|
.map(media => ({
|
|
|
|
...media,
|
|
|
|
entry: existingHashMediaEntriesByHash[media.entry?.hash || media.meta?.hash],
|
|
|
|
}))
|
|
|
|
.concat(selfDuplicateMedias);
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return [selfUniqueHashMedias, existingHashMedias];
|
2020-03-30 01:01:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function extractSource(baseSource, { existingExtractMediaByUrl }) {
|
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,
|
|
|
|
src,
|
|
|
|
};
|
|
|
|
}
|
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
|
|
|
}
|
|
|
|
|
2020-05-06 23:53:07 +00:00
|
|
|
async function storeImageFile(media, hashDir, hashSubDir, filename, filedir, filepath) {
|
2020-09-21 03:11:24 +00:00
|
|
|
try {
|
|
|
|
const thumbdir = path.join(media.role, 'thumbs', hashDir, hashSubDir);
|
|
|
|
const thumbpath = path.join(thumbdir, filename);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
const lazydir = path.join(media.role, 'lazy', hashDir, hashSubDir);
|
|
|
|
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
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
const image = sharp(media.file.path);
|
|
|
|
const info = await image.metadata();
|
|
|
|
const isProcessed = media.meta.subtype !== 'jpeg' || media.process;
|
2020-07-10 01:42:08 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
if (media.process) {
|
|
|
|
Object.entries(media.process).forEach(([operation, options]) => {
|
|
|
|
if (image[operation]) {
|
|
|
|
image[operation](...(Array.isArray(options) ? options : [options]));
|
|
|
|
return;
|
|
|
|
}
|
2020-07-10 01:42:08 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
if (operation === 'crop') {
|
|
|
|
image.extract(...(Array.isArray(options) ? options : [options]));
|
|
|
|
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
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
if (isProcessed) {
|
|
|
|
// convert to JPEG and write to permanent location
|
|
|
|
await image
|
|
|
|
.jpeg()
|
|
|
|
.toFile(path.join(config.media.path, filepath));
|
|
|
|
}
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
// generate thumbnail and lazy
|
|
|
|
await Promise.all([
|
|
|
|
image
|
|
|
|
.resize({
|
|
|
|
height: config.media.thumbnailSize,
|
|
|
|
withoutEnlargement: true,
|
|
|
|
})
|
|
|
|
.jpeg({ quality: config.media.thumbnailQuality })
|
|
|
|
.toFile(path.join(config.media.path, thumbpath)),
|
|
|
|
image
|
|
|
|
.resize({
|
|
|
|
height: config.media.lazySize,
|
|
|
|
withoutEnlargement: true,
|
|
|
|
})
|
|
|
|
.jpeg({ quality: config.media.lazyQuality })
|
|
|
|
.toFile(path.join(config.media.path, lazypath)),
|
|
|
|
]);
|
2020-05-14 02:26:05 +00:00
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
if (isProcessed) {
|
|
|
|
// remove temp file
|
|
|
|
await fsPromises.unlink(media.file.path);
|
|
|
|
} else {
|
|
|
|
// move temp file to permanent location
|
|
|
|
await fsPromises.rename(media.file.path, path.join(config.media.path, filepath));
|
|
|
|
}
|
2020-05-14 02:26:05 +00:00
|
|
|
|
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,
|
|
|
|
width: info.width,
|
|
|
|
height: info.height,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
} 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-04-26 01:51:59 +00:00
|
|
|
async function storeFile(media) {
|
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);
|
|
|
|
const hashFilename = media.meta.hash.slice(4);
|
|
|
|
|
|
|
|
const filename = media.quality
|
|
|
|
? `${hashFilename}_${media.quality}.${media.meta.extension}`
|
|
|
|
: `${hashFilename}.${media.meta.extension}`;
|
|
|
|
|
|
|
|
const filedir = path.join(media.role, hashDir, hashSubDir);
|
|
|
|
const filepath = path.join(filedir, filename);
|
|
|
|
|
2020-09-21 03:11:24 +00:00
|
|
|
if (argv.force) {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (media.meta.type === 'image') {
|
|
|
|
return storeImageFile(media, hashDir, hashSubDir, filename, filedir, filepath);
|
|
|
|
}
|
|
|
|
|
|
|
|
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));
|
|
|
|
|
|
|
|
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}`);
|
|
|
|
|
|
|
|
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, {
|
|
|
|
...(source.referer && { referer: source.referer }),
|
|
|
|
...(source.host && { host: source.host }),
|
|
|
|
}, {
|
|
|
|
stream: true, // sources are fetched in parallel, don't gobble up memory
|
|
|
|
transforms: [hashStream],
|
|
|
|
destination: tempFileTarget,
|
|
|
|
queueMethod: source.queueMethod || null, // use http module's default
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
throw new Error(`Response ${res.status} not OK`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
mimetype: res.headers['content-type'] || mime.getType(new URL(source.src).pathname),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
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'])
|
|
|
|
.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}`))
|
|
|
|
.pipe();
|
2020-07-10 00:01:23 +00:00
|
|
|
|
|
|
|
await pipeline(video, hashStream, tempFileTarget);
|
|
|
|
|
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) {
|
2020-09-17 00:30:58 +00:00
|
|
|
const maxAttempts = source.attempts || 3;
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
logger.silly(`Fetching media from ${source.src}`);
|
|
|
|
// attempts
|
|
|
|
|
|
|
|
async function attempt(attempts = 1) {
|
2020-07-10 00:01:23 +00:00
|
|
|
const hasher = new blake2.Hash('blake2b', { digestLength: 24 });
|
|
|
|
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;
|
|
|
|
|
|
|
|
hashStream.on('data', (chunk) => {
|
|
|
|
size += chunk.length;
|
|
|
|
hasher.write(chunk);
|
|
|
|
});
|
|
|
|
|
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) {
|
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
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (!argv.force && extractedSource.entry) {
|
|
|
|
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
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (!argv.force && existingSourceMedia) {
|
|
|
|
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
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return fetchSource(extractedSource, baseMedia);
|
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,
|
|
|
|
index,
|
|
|
|
mime: media.meta.mimetype,
|
|
|
|
hash: media.meta.hash,
|
|
|
|
size: media.meta.size,
|
|
|
|
width: media.meta.width,
|
|
|
|
height: media.meta.height,
|
|
|
|
entropy: media.meta.entropy,
|
|
|
|
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-03-31 02:05:31 +00:00
|
|
|
async function storeMedias(baseMedias) {
|
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
|
|
|
|
2020-05-14 02:26:05 +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,
|
|
|
|
async baseMedia => fetchMedia(baseMedia, { existingSourceMediaByUrl, existingExtractMediaByUrl }),
|
|
|
|
);
|
2020-03-30 01:01:08 +00:00
|
|
|
|
2020-05-14 02:26:05 +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,
|
2020-05-14 02:26:05 +00:00
|
|
|
async baseMedia => storeFile(baseMedia),
|
|
|
|
);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-07-12 22:12:01 +00:00
|
|
|
if (argv.force) {
|
|
|
|
// overwrite files in case image processing was changed
|
|
|
|
await Promise.map(
|
|
|
|
existingHashMedias,
|
|
|
|
async baseMedia => storeFile(baseMedia),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const newMediaWithEntries = savedMedias.map((media, index) => curateMediaEntry(media, index));
|
|
|
|
const newMediaEntries = newMediaWithEntries.filter(media => media.newEntry).map(media => media.entry);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-08-14 21:21:53 +00:00
|
|
|
await bulkInsert('media', newMediaEntries);
|
2020-03-29 02:00:46 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return [...newMediaWithEntries, ...existingHashMedias];
|
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') : []),
|
|
|
|
...(argv.images && argv.poster ? toBaseMedias(release.covers, 'covers') : []),
|
|
|
|
...(argv.images && argv.photos ? toBaseMedias(release.photos, 'photos') : []),
|
|
|
|
...(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;
|
|
|
|
}, {});
|
|
|
|
|
|
|
|
await Promise.reduce(['posters', 'covers', 'photos', 'teasers', 'trailers'], async (chain, role) => {
|
|
|
|
// stage by role so posters are prioritized over photos and videos
|
|
|
|
await chain;
|
|
|
|
|
|
|
|
const baseMedias = baseMediasByRole[role];
|
|
|
|
|
|
|
|
if (!baseMedias) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
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];
|
|
|
|
|
|
|
|
if (media) {
|
|
|
|
acc.push({
|
2020-08-20 02:57:38 +00:00
|
|
|
[`${type}_id`]: releaseId,
|
2020-05-14 02:26:05 +00:00
|
|
|
media_id: media.use || media.entry.id,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, [])
|
|
|
|
.filter(Boolean);
|
|
|
|
|
|
|
|
if (associations.length > 0) {
|
2020-08-20 02:57:38 +00:00
|
|
|
await bulkInsert(`${type}s_${role}`, associations, false);
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
const profilesWithBaseMedias = profiles.map(profile => (profile.avatar
|
|
|
|
? {
|
|
|
|
...profile,
|
|
|
|
avatarBaseMedia: toBaseMedias([profile.avatar], 'avatars', {
|
2020-07-15 01:24:47 +00:00
|
|
|
credit: (profile.credit !== undefined && (profile.network?.name || profile.site?.name)) || null,
|
2020-05-16 02:36:45 +00:00
|
|
|
scraper: profile.scraper || null,
|
|
|
|
})[0],
|
|
|
|
}
|
|
|
|
: profile
|
|
|
|
));
|
|
|
|
|
|
|
|
const baseMedias = profilesWithBaseMedias.map(profile => profile.avatarBaseMedia).filter(Boolean);
|
|
|
|
|
|
|
|
const storedMedias = await storeMedias(baseMedias);
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
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'),
|
|
|
|
knex('releases_trailers').select('media_id'),
|
|
|
|
knex('releases_teasers').select('media_id'),
|
|
|
|
knex('movies_covers').select('media_id'),
|
|
|
|
knex('movies_trailers').select('media_id'),
|
|
|
|
knex('actors_avatars').select('media_id'),
|
|
|
|
knex('actors_photos').select('media_id'),
|
|
|
|
knex('clips_photos').select('media_id'),
|
|
|
|
knex('clips_posters').select('media_id'),
|
|
|
|
)
|
|
|
|
.as('associations'),
|
|
|
|
)
|
|
|
|
.whereRaw('associations.media_id = media.id'),
|
|
|
|
)
|
|
|
|
.returning(['media.path', 'media.thumbnail', 'media.lazy'])
|
|
|
|
.delete();
|
|
|
|
|
|
|
|
await Promise.all(orphanedMedia.map(media => Promise.all([
|
2020-10-25 20:43:36 +00:00
|
|
|
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
|
|
|
])));
|
|
|
|
|
2020-10-25 20:43:36 +00:00
|
|
|
logger.info(`Removed ${orphanedMedia.length} media files from database and storage`);
|
2020-10-24 22:52:40 +00:00
|
|
|
|
|
|
|
await fsPromises.rmdir(path.join(config.media.path, 'temp'), { recursive: true });
|
|
|
|
|
|
|
|
logger.info('Removed temporary media directory');
|
|
|
|
}
|
|
|
|
|
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
|
|
|
};
|