2019-10-18 03:11:35 +08:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const ws = require('./ws.js');
|
|
|
|
|
|
|
|
// taskId => TaskContext
|
|
|
|
const taskContexts = {};
|
|
|
|
|
|
|
|
class TaskContext {
|
|
|
|
constructor(taskId, taskType, data) {
|
|
|
|
this.taskId = taskId;
|
|
|
|
this.taskType = taskType;
|
|
|
|
this.data = data;
|
|
|
|
|
|
|
|
// progressCount is meant to represent just some progress - to indicate the task is not stuck
|
2020-01-05 04:59:28 +08:00
|
|
|
this.progressCount = -1; // we're incrementing immediatelly
|
|
|
|
this.lastSentCountTs = 0; // 0 will guarantee first message will be sent
|
2020-01-05 04:24:39 +08:00
|
|
|
|
|
|
|
// just the fact this has been initialized is a progress which should be sent to clients
|
|
|
|
// this is esp. important when importing big files/images which take long time to upload/process
|
|
|
|
// which means that first "real" increaseProgressCount() will be called quite late and user is without
|
|
|
|
// feedback until then
|
|
|
|
this.increaseProgressCount();
|
2019-10-18 03:11:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/** @return {TaskContext} */
|
2019-10-19 05:19:16 +08:00
|
|
|
static getInstance(taskId, taskType, data) {
|
2019-10-18 03:11:35 +08:00
|
|
|
if (!taskContexts[taskId]) {
|
2019-10-19 05:19:16 +08:00
|
|
|
taskContexts[taskId] = new TaskContext(taskId, taskType, data);
|
2019-10-18 03:11:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return taskContexts[taskId];
|
|
|
|
}
|
|
|
|
|
2019-10-29 01:42:22 +08:00
|
|
|
increaseProgressCount() {
|
2019-10-18 03:11:35 +08:00
|
|
|
this.progressCount++;
|
|
|
|
|
|
|
|
if (Date.now() - this.lastSentCountTs >= 300) {
|
|
|
|
this.lastSentCountTs = Date.now();
|
|
|
|
|
2019-10-29 01:42:22 +08:00
|
|
|
ws.sendMessageToAllClients({
|
2019-10-18 03:11:35 +08:00
|
|
|
type: 'task-progress-count',
|
|
|
|
taskId: this.taskId,
|
|
|
|
taskType: this.taskType,
|
2019-10-19 15:58:18 +08:00
|
|
|
data: this.data,
|
2019-10-18 03:11:35 +08:00
|
|
|
progressCount: this.progressCount
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-29 01:42:22 +08:00
|
|
|
reportError(message) {
|
|
|
|
ws.sendMessageToAllClients({
|
2019-10-18 03:11:35 +08:00
|
|
|
type: 'task-error',
|
|
|
|
taskId: this.taskId,
|
|
|
|
taskType: this.taskType,
|
2019-10-19 15:58:18 +08:00
|
|
|
data: this.data,
|
2019-10-18 03:11:35 +08:00
|
|
|
message: message
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-10-29 01:42:22 +08:00
|
|
|
taskSucceeded(result) {
|
|
|
|
ws.sendMessageToAllClients({
|
2019-10-18 03:11:35 +08:00
|
|
|
type: 'task-succeeded',
|
|
|
|
taskId: this.taskId,
|
|
|
|
taskType: this.taskType,
|
2019-10-19 15:58:18 +08:00
|
|
|
data: this.data,
|
2019-10-19 06:11:07 +08:00
|
|
|
result: result
|
2019-10-18 03:11:35 +08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = TaskContext;
|