summaryrefslogtreecommitdiffstats
path: root/src/tasks.ts
blob: 0646da540c1e26153831230d71479e38597afad7 (plain)
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
import { asyncExec } from "./utils";
import fs from "fs";
export const checkIfYtdlpIsInstalled = async () => {
  try {
    await asyncExec("yt-dlp --version");
    return true;
  } catch (e) {
    console.error("yt-dlp is not installed or available in PATH", e);
    return false;
  }
};

export const runDownloadUrlTask = async (task: Task) => {
  try {
    const filename = "veeti.mp4";
    // remove the file if it exists
    try {
      fs.rmSync(filename);
    } catch (e: any) {
      if (e.code !== "ENOENT") {
        console.error("Error deleting file", e);
      }
    }

    const { stdout } = await asyncExec(
      `yt-dlp -o "downloads/${filename}" "${task.url}"`,
    );
    console.log(stdout);
    task.respondWithFile(filename);
  } catch (e) {
    console.error("Error downloading URL", e);
    throw e;
  }
};

export type Task = {
  url: string;
  type: "download_url";
  respondWithFile: (file: string) => void;
  respondTaskFailed: (err: unknown) => void;
};

const taskQueue: Task[] = [];

export const addTask = (task: Task) => {
  taskQueue.push(task);
};

export const getTask = (): Task | undefined => {
  return taskQueue.shift();
};

export const numOfTasksInQueue = () => {
  return taskQueue.length;
};