trilium/src/services/task_context.js

65 lines
1.6 KiB
JavaScript
Raw Normal View History

"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
this.progressCount = 0;
this.lastSentCountTs = Date.now();
}
/** @return {TaskContext} */
2019-10-19 05:19:16 +08:00
static getInstance(taskId, taskType, data) {
if (!taskContexts[taskId]) {
2019-10-19 05:19:16 +08:00
taskContexts[taskId] = new TaskContext(taskId, taskType, data);
}
return taskContexts[taskId];
}
2019-10-29 01:42:22 +08:00
increaseProgressCount() {
this.progressCount++;
if (Date.now() - this.lastSentCountTs >= 300) {
this.lastSentCountTs = Date.now();
2019-10-29 01:42:22 +08:00
ws.sendMessageToAllClients({
type: 'task-progress-count',
taskId: this.taskId,
taskType: this.taskType,
data: this.data,
progressCount: this.progressCount
});
}
}
2019-10-29 01:42:22 +08:00
reportError(message) {
ws.sendMessageToAllClients({
type: 'task-error',
taskId: this.taskId,
taskType: this.taskType,
data: this.data,
message: message
});
}
2019-10-29 01:42:22 +08:00
taskSucceeded(result) {
ws.sendMessageToAllClients({
type: 'task-succeeded',
taskId: this.taskId,
taskType: this.taskType,
data: this.data,
2019-10-19 06:11:07 +08:00
result: result
});
}
}
module.exports = TaskContext;