File size: 2,055 Bytes
8ea0122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const jobs = {};
const JOB_CLEANUP_MS = 60 * 60 * 1000; 

// Clean up old jobs
setInterval(() => {
  const now = Date.now();
  Object.keys(jobs).forEach(id => { if (now - jobs[id].timestamp > JOB_CLEANUP_MS) delete jobs[id]; });
}, 60000);

function createJob(batchId = null) {
  const id = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
  jobs[id] = { 
    id, 
    batchId, 
    timestamp: Date.now(), 
    // Updated State Machine:
    status: 'queued', // queued, downloading, processing, ready, error
    progress: 0,      // 0-100 (approx)
    message: 'Waiting in queue...',
    fileUrl: null, 
    error: null, 
    videoTitle: "Pending..." 
  };
  return id;
}

function getJob(id) { return jobs[id]; }
function getBatchJobs(batchId) { return Object.values(jobs).filter(j => j.batchId === batchId); }

// --- GRANULAR UPDATES ---
function updateJobStatus(jobId, status, message, progress = 0) {
  if (jobs[jobId]) {
    jobs[jobId].status = status;
    jobs[jobId].message = message;
    if (progress > 0) jobs[jobId].progress = progress;
  }
}

function setJobFile(jobId, fileUrl) { 
  if (jobs[jobId]) {
    jobs[jobId].fileUrl = fileUrl;
    jobs[jobId].status = 'ready';
    jobs[jobId].message = 'Done';
    jobs[jobId].progress = 100;
  }
}

function setJobTitle(jobId, title) { if (jobs[jobId]) jobs[jobId].videoTitle = title; }

function setJobError(jobId, message) { 
  if (jobs[jobId]) { 
    jobs[jobId].status = 'error';
    jobs[jobId].error = message; 
    jobs[jobId].message = message; // Show error as main message
  } 
}

// --- RETRY LOGIC ---
function resetJob(jobId) {
  if (jobs[jobId]) {
    jobs[jobId].status = 'queued';
    jobs[jobId].error = null;
    jobs[jobId].message = 'Retrying...';
    jobs[jobId].progress = 0;
    jobs[jobId].fileUrl = null;
    // Timestamp update to prevent cleanup
    jobs[jobId].timestamp = Date.now();
    return true;
  }
  return false;
}

module.exports = { createJob, getJob, getBatchJobs, updateJobStatus, setJobFile, setJobTitle, setJobError, resetJob };