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
|
import fs from "fs";
import * as os from "os";
import path from "path";
import { execa } from "execa";
import { DequeuedJob, Runner } from "liteque";
import { db } from "@hoarder/db";
import { AssetTypes } from "@hoarder/db/schema";
import {
ASSET_TYPES,
getAssetSize,
newAssetId,
saveAssetFromFile,
silentDeleteAsset,
} from "@hoarder/shared/assetdb";
import serverConfig from "@hoarder/shared/config";
import logger from "@hoarder/shared/logger";
import {
VideoWorkerQueue,
ZVideoRequest,
zvideoRequestSchema,
} from "@hoarder/shared/queues";
import { withTimeout } from "./utils";
import { getBookmarkDetails, updateAsset } from "./workerUtils";
const TMP_FOLDER = path.join(os.tmpdir(), "video_downloads");
export class VideoWorker {
static build() {
logger.info("Starting video worker ...");
return new Runner<ZVideoRequest>(
VideoWorkerQueue,
{
run: withTimeout(
runWorker,
/* timeoutSec */ serverConfig.crawler.downloadVideoTimeout,
),
onComplete: async (job) => {
const jobId = job.id;
logger.info(
`[VideoCrawler][${jobId}] Video Download Completed successfully`,
);
return Promise.resolve();
},
onError: async (job) => {
const jobId = job.id;
logger.error(
`[VideoCrawler][${jobId}] Video Download job failed: ${job.error}`,
);
return Promise.resolve();
},
},
{
pollIntervalMs: 1000,
timeoutSecs: serverConfig.crawler.downloadVideoTimeout,
concurrency: 1,
validator: zvideoRequestSchema,
},
);
}
}
function prepareYtDlpArguments(url: string, assetPath: string) {
const ytDlpArguments = [url];
if (serverConfig.crawler.maxVideoDownloadSize > 0) {
ytDlpArguments.push(
"-f",
`best[filesize<${serverConfig.crawler.maxVideoDownloadSize}M]`,
);
}
ytDlpArguments.push(...serverConfig.crawler.ytDlpArguments);
ytDlpArguments.push("-o", assetPath);
ytDlpArguments.push("--no-playlist");
return ytDlpArguments;
}
async function runWorker(job: DequeuedJob<ZVideoRequest>) {
const jobId = job.id;
const { bookmarkId } = job.data;
const {
url,
userId,
videoAssetId: oldVideoAssetId,
} = await getBookmarkDetails(bookmarkId);
if (!serverConfig.crawler.downloadVideo) {
logger.info(
`[VideoCrawler][${jobId}] Skipping video download from "${url}", because it is disabled in the config.`,
);
return;
}
const videoAssetId = newAssetId();
let assetPath = `${TMP_FOLDER}/${videoAssetId}`;
await fs.promises.mkdir(TMP_FOLDER, { recursive: true });
const ytDlpArguments = prepareYtDlpArguments(url, assetPath);
try {
logger.info(
`[VideoCrawler][${jobId}] Attempting to download a file from "${url}" to "${assetPath}" using the following arguments: "${ytDlpArguments}"`,
);
await execa("yt-dlp", ytDlpArguments, {
cancelSignal: job.abortSignal,
});
const downloadPath = await findAssetFile(videoAssetId);
if (!downloadPath) {
logger.info(
"[VideoCrawler][${jobId}] yt-dlp didn't download anything. Skipping ...",
);
return;
}
assetPath = downloadPath;
} catch (e) {
const err = e as Error;
if (
err.message.includes("ERROR: Unsupported URL:") ||
err.message.includes("No media found")
) {
logger.info(
`[VideoCrawler][${jobId}] Skipping video download from "${url}", because it's not one of the supported yt-dlp URLs`,
);
return;
}
logger.error(
`[VideoCrawler][${jobId}] Failed to download a file from "${url}" to "${assetPath}"`,
);
await deleteLeftOverAssetFile(jobId, videoAssetId);
return;
}
logger.info(
`[VideoCrawler][${jobId}] Finished downloading a file from "${url}" to "${assetPath}"`,
);
await saveAssetFromFile({
userId,
assetId: videoAssetId,
assetPath,
metadata: { contentType: ASSET_TYPES.VIDEO_MP4 },
});
await db.transaction(async (txn) => {
await updateAsset(
oldVideoAssetId,
{
id: videoAssetId,
bookmarkId,
userId,
assetType: AssetTypes.LINK_VIDEO,
contentType: ASSET_TYPES.VIDEO_MP4,
size: await getAssetSize({ userId, assetId: videoAssetId }),
},
txn,
);
});
await silentDeleteAsset(userId, oldVideoAssetId);
logger.info(
`[VideoCrawler][${jobId}] Finished downloading video from "${url}" and adding it to the database`,
);
}
/**
* Deletes leftover assets in case the download fails
*
* @param jobId the id of the job
* @param assetId the id of the asset to delete
*/
async function deleteLeftOverAssetFile(
jobId: string,
assetId: string,
): Promise<void> {
let assetFile;
try {
assetFile = await findAssetFile(assetId);
} catch {
// ignore exception, no asset file was found
return;
}
if (!assetFile) {
return;
}
logger.info(
`[VideoCrawler][${jobId}] Deleting leftover video asset "${assetFile}".`,
);
try {
await fs.promises.rm(assetFile);
} catch (e) {
logger.error(
`[VideoCrawler][${jobId}] Failed deleting leftover video asset "${assetFile}".`,
);
}
}
/**
* yt-dlp automatically adds a file ending to the passed in filename --> we have to search it again in the folder
*
* @param assetId the id of the asset to search
* @returns the path to the downloaded asset
*/
async function findAssetFile(assetId: string): Promise<string | null> {
const files = await fs.promises.readdir(TMP_FOLDER);
for (const file of files) {
if (file.startsWith(assetId)) {
return path.join(TMP_FOLDER, file);
}
}
return null;
}
|