channel-worker 1.1.9 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -128,6 +128,24 @@ if (cmd === 'pair') {
128
128
  const daemon = new Daemon(config);
129
129
  daemon.start();
130
130
 
131
+ } else if (cmd === 'update') {
132
+ const { checkAndUpdate, getLocalVersion } = require('../lib/updater');
133
+ console.log(`[channel-worker] Current version: ${getLocalVersion()}`);
134
+ (async () => {
135
+ try {
136
+ const result = await checkAndUpdate({ autoRestart: false });
137
+ if (result.updated) {
138
+ console.log(`[channel-worker] Updated: ${result.local} → ${result.latest}`);
139
+ console.log('[channel-worker] Restart the daemon to use the new version.');
140
+ } else {
141
+ console.log(`[channel-worker] Already up to date (${result.local})`);
142
+ }
143
+ } catch (err) {
144
+ console.error(`[channel-worker] Update failed: ${err.message}`);
145
+ process.exit(1);
146
+ }
147
+ })();
148
+
131
149
  } else if (cmd === 'config') {
132
150
  const config = loadConfig();
133
151
  // Hide token in display
@@ -142,7 +160,8 @@ channel-worker — Channel Manager worker daemon
142
160
  Commands:
143
161
  pair Pair with dashboard using a one-time code (recommended)
144
162
  init Configure worker manually
145
- start Start the daemon
163
+ start Start the daemon (auto-checks for updates every 5min)
164
+ update Check and install updates manually
146
165
  config Show current config
147
166
 
148
167
  Pairing (recommended):
package/lib/api-client.js CHANGED
@@ -62,12 +62,32 @@ class ApiClient {
62
62
 
63
63
  // Commands
64
64
  async getNextCommand(workerId) {
65
- return this.request('GET', `/workers/commands?worker_id=${workerId}`);
65
+ const workerTypes = 'launch_profile,close_profile,save_file,set_thumbnail,set_tags,set_file_input,click_and_upload,type_text,verify_logins,update_extension';
66
+ return this.request('GET', `/workers/commands?worker_id=${workerId}&types=${encodeURIComponent(workerTypes)}`);
66
67
  }
67
68
 
68
69
  async updateCommand(commandId, data) {
69
70
  return this.request('PUT', `/workers/commands/${commandId}`, data);
70
71
  }
72
+
73
+ // Extension download
74
+ async getExtensionVersion() {
75
+ const data = await this.request('GET', '/extension-download/version');
76
+ return data.version;
77
+ }
78
+
79
+ async downloadExtension(destPath) {
80
+ const url = `${this.baseUrl}/extension-download/zip`;
81
+ const res = await fetch(url, {
82
+ headers: { 'x-worker-token': this.workerToken },
83
+ });
84
+ if (!res.ok) throw new Error(`Download failed: ${res.status}`);
85
+
86
+ const fs = require('fs');
87
+ const buffer = Buffer.from(await res.arrayBuffer());
88
+ fs.writeFileSync(destPath, buffer);
89
+ return destPath;
90
+ }
71
91
  }
72
92
 
73
93
  module.exports = { ApiClient };
@@ -1,4 +1,5 @@
1
1
  const { NstManager } = require('./nst-manager');
2
+ const { checkAndUpdateExtension } = require('./extension-updater');
2
3
 
3
4
  class CommandPoller {
4
5
  constructor(api, config) {
@@ -64,6 +65,9 @@ class CommandPoller {
64
65
  case 'type_text':
65
66
  await this.handleTypeText(command);
66
67
  break;
68
+ case 'update_extension':
69
+ await this.handleUpdateExtension(command);
70
+ break;
67
71
  default:
68
72
  // Other commands (scan_facebook_pages, etc.) handled by extension
69
73
  console.log(`[commands] Skipping ${command.type} — handled by extension`);
@@ -827,6 +831,25 @@ class CommandPoller {
827
831
  await this.api.updateCommand(command._id, { status: 'done' });
828
832
  }
829
833
 
834
+ async handleUpdateExtension(command) {
835
+ console.log('[commands] Updating extension...');
836
+ try {
837
+ if (!this.config.extension_path) {
838
+ throw new Error('No extension_path configured');
839
+ }
840
+ const result = await checkAndUpdateExtension(this.api, this.config.extension_path);
841
+ if (result.updated) {
842
+ console.log(`[commands] Extension updated: ${result.from || 'none'} → ${result.to}`);
843
+ } else {
844
+ console.log(`[commands] Extension already up to date (v${result.local})`);
845
+ }
846
+ await this.api.updateCommand(command._id, { status: 'done', result });
847
+ } catch (err) {
848
+ console.error(`[commands] Extension update failed: ${err.message}`);
849
+ await this.api.updateCommand(command._id, { status: 'failed', error: err.message });
850
+ }
851
+ }
852
+
830
853
  async handleVerifyLogins(command) {
831
854
  const { profile_id, channel_id } = command.payload || {};
832
855
  console.log(`[commands] Verifying logins for profile: ${profile_id}`);
package/lib/daemon.js CHANGED
@@ -2,6 +2,8 @@ const { ApiClient } = require('./api-client');
2
2
  const { Heartbeat } = require('./heartbeat');
3
3
  const { JobPoller } = require('./job-poller');
4
4
  const { CommandPoller } = require('./command-poller');
5
+ const { UpdateChecker, getLocalVersion } = require('./updater');
6
+ const { checkAndUpdateExtension } = require('./extension-updater');
5
7
 
6
8
  class Daemon {
7
9
  constructor(config) {
@@ -10,12 +12,14 @@ class Daemon {
10
12
  this.heartbeat = new Heartbeat(this.api, config.worker_id);
11
13
  this.poller = new JobPoller(this.api, config);
12
14
  this.commandPoller = new CommandPoller(this.api, config);
15
+ this.updateChecker = new UpdateChecker(5 * 60 * 1000); // check every 5min
13
16
  }
14
17
 
15
18
  async start() {
19
+ const version = getLocalVersion();
16
20
  console.log(`
17
21
  ╔══════════════════════════════════════╗
18
- ║ channel-worker v1.0.0
22
+ ║ channel-worker v${version.padEnd(14)}
19
23
  ╠══════════════════════════════════════╣
20
24
  ║ Worker ID: ${this.config.worker_id.padEnd(22)}║
21
25
  ║ API URL: ${this.config.api_url.padEnd(22)}║
@@ -31,6 +35,20 @@ class Daemon {
31
35
  max_concurrent: this.config.max_concurrent,
32
36
  });
33
37
  console.log('[daemon] Registered with dashboard ✓');
38
+
39
+ // Auto-update extension on startup
40
+ if (this.config.extension_path) {
41
+ try {
42
+ const result = await checkAndUpdateExtension(this.api, this.config.extension_path);
43
+ if (result.updated) {
44
+ console.log(`[daemon] Extension updated: ${result.from || 'none'} → ${result.to}`);
45
+ } else {
46
+ console.log(`[daemon] Extension up to date (v${result.local})`);
47
+ }
48
+ } catch (err) {
49
+ console.warn(`[daemon] Extension update check failed: ${err.message}`);
50
+ }
51
+ }
34
52
  } catch (err) {
35
53
  console.error(`[daemon] Failed to register: ${err.message}`);
36
54
  console.error('[daemon] Is the dashboard API running? Retrying in 10s...');
@@ -49,6 +67,10 @@ class Daemon {
49
67
  // Start command polling
50
68
  this.commandPoller.start();
51
69
  console.log('[daemon] Command poller started (every 3s)');
70
+
71
+ // Start auto-update checker
72
+ this.updateChecker.start();
73
+ console.log('[daemon] Auto-update checker started (every 5min)');
52
74
  console.log('[daemon] Waiting for jobs & commands...\n');
53
75
 
54
76
  // Graceful shutdown
@@ -57,6 +79,7 @@ class Daemon {
57
79
  this.heartbeat.stop();
58
80
  this.poller.stop();
59
81
  this.commandPoller.stop();
82
+ this.updateChecker.stop();
60
83
 
61
84
  // Mark offline
62
85
  try {
@@ -0,0 +1,78 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const { execSync } = require('child_process');
5
+
6
+ function getLocalExtensionVersion(extensionPath) {
7
+ try {
8
+ const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf8'));
9
+ return manifest.version || null;
10
+ } catch {
11
+ return null;
12
+ }
13
+ }
14
+
15
+ function isNewer(remote, local) {
16
+ const r = remote.split('.').map(Number);
17
+ const l = local.split('.').map(Number);
18
+ for (let i = 0; i < 3; i++) {
19
+ if ((r[i] || 0) > (l[i] || 0)) return true;
20
+ if ((r[i] || 0) < (l[i] || 0)) return false;
21
+ }
22
+ return false;
23
+ }
24
+
25
+ async function checkAndUpdateExtension(api, extensionPath) {
26
+ const local = getLocalExtensionVersion(extensionPath);
27
+ const remote = await api.getExtensionVersion();
28
+
29
+ if (local && !isNewer(remote, local)) {
30
+ return { updated: false, local, remote };
31
+ }
32
+
33
+ console.log(`[ext-updater] ${local ? `Update available: ${local} → ${remote}` : `Downloading extension v${remote}...`}`);
34
+
35
+ // Download to temp
36
+ const tmpArchive = path.join(os.tmpdir(), `channel-manager-ext-${Date.now()}.tar.gz`);
37
+ const tmpExtract = path.join(os.tmpdir(), `channel-manager-ext-new-${Date.now()}`);
38
+
39
+ try {
40
+ await api.downloadExtension(tmpArchive);
41
+
42
+ // Extract
43
+ fs.mkdirSync(tmpExtract, { recursive: true });
44
+ execSync(`tar -xzf "${tmpArchive}" -C "${tmpExtract}"`, { timeout: 30000 });
45
+
46
+ // tar extracts into a subfolder named "channel-manager-ext"
47
+ const extracted = path.join(tmpExtract, 'channel-manager-ext');
48
+ const sourceDir = fs.existsSync(extracted) ? extracted : tmpExtract;
49
+
50
+ // Replace existing extension dir
51
+ if (fs.existsSync(extensionPath)) {
52
+ fs.rmSync(extensionPath, { recursive: true, force: true });
53
+ }
54
+ fs.mkdirSync(extensionPath, { recursive: true });
55
+
56
+ // Copy files
57
+ const files = fs.readdirSync(sourceDir);
58
+ for (const f of files) {
59
+ const src = path.join(sourceDir, f);
60
+ const dest = path.join(extensionPath, f);
61
+ const stat = fs.statSync(src);
62
+ if (stat.isFile()) {
63
+ fs.copyFileSync(src, dest);
64
+ } else if (stat.isDirectory()) {
65
+ fs.cpSync(src, dest, { recursive: true });
66
+ }
67
+ }
68
+
69
+ console.log(`[ext-updater] Extension updated to v${remote}`);
70
+ return { updated: true, from: local, to: remote };
71
+ } finally {
72
+ // Cleanup temp files
73
+ try { fs.unlinkSync(tmpArchive); } catch {}
74
+ try { fs.rmSync(tmpExtract, { recursive: true, force: true }); } catch {}
75
+ }
76
+ }
77
+
78
+ module.exports = { checkAndUpdateExtension, getLocalExtensionVersion };
package/lib/updater.js ADDED
@@ -0,0 +1,93 @@
1
+ const { execSync } = require('child_process');
2
+ const path = require('path');
3
+
4
+ const PKG_NAME = 'channel-worker';
5
+
6
+ function getLocalVersion() {
7
+ const pkg = require(path.join(__dirname, '..', 'package.json'));
8
+ return pkg.version;
9
+ }
10
+
11
+ async function getLatestVersion() {
12
+ const res = await fetch(`https://registry.npmjs.org/${PKG_NAME}/latest`);
13
+ if (!res.ok) throw new Error(`npm registry returned ${res.status}`);
14
+ const data = await res.json();
15
+ return data.version;
16
+ }
17
+
18
+ function isNewer(remote, local) {
19
+ const r = remote.split('.').map(Number);
20
+ const l = local.split('.').map(Number);
21
+ for (let i = 0; i < 3; i++) {
22
+ if (r[i] > l[i]) return true;
23
+ if (r[i] < l[i]) return false;
24
+ }
25
+ return false;
26
+ }
27
+
28
+ function installUpdate(version) {
29
+ console.log(`[updater] Installing ${PKG_NAME}@${version}...`);
30
+ execSync(`npm install -g ${PKG_NAME}@${version}`, { stdio: 'inherit' });
31
+ console.log(`[updater] Installed ${PKG_NAME}@${version}`);
32
+ }
33
+
34
+ async function checkAndUpdate({ autoRestart = false } = {}) {
35
+ const local = getLocalVersion();
36
+ const latest = await getLatestVersion();
37
+
38
+ if (!isNewer(latest, local)) {
39
+ return { updated: false, local, latest };
40
+ }
41
+
42
+ console.log(`[updater] Update available: ${local} → ${latest}`);
43
+ installUpdate(latest);
44
+
45
+ if (autoRestart) {
46
+ console.log('[updater] Restarting daemon...');
47
+ // Spawn detached process with same args, then exit current
48
+ const { spawn } = require('child_process');
49
+ const child = spawn(process.argv[0], process.argv.slice(1), {
50
+ detached: true,
51
+ stdio: 'ignore',
52
+ cwd: process.cwd(),
53
+ });
54
+ child.unref();
55
+ process.exit(0);
56
+ }
57
+
58
+ return { updated: true, local, latest };
59
+ }
60
+
61
+ class UpdateChecker {
62
+ constructor(intervalMs = 5 * 60 * 1000) {
63
+ this.intervalMs = intervalMs;
64
+ this.timer = null;
65
+ }
66
+
67
+ start() {
68
+ // Check on startup after 10s delay
69
+ setTimeout(() => this.check(), 10000);
70
+ // Then periodically
71
+ this.timer = setInterval(() => this.check(), this.intervalMs);
72
+ }
73
+
74
+ stop() {
75
+ if (this.timer) {
76
+ clearInterval(this.timer);
77
+ this.timer = null;
78
+ }
79
+ }
80
+
81
+ async check() {
82
+ try {
83
+ const result = await checkAndUpdate({ autoRestart: true });
84
+ if (!result.updated) {
85
+ // Silent — only log in verbose or when there's an update
86
+ }
87
+ } catch (err) {
88
+ console.warn(`[updater] Check failed: ${err.message}`);
89
+ }
90
+ }
91
+ }
92
+
93
+ module.exports = { checkAndUpdate, getLocalVersion, getLatestVersion, isNewer, UpdateChecker };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "channel-worker",
3
- "version": "1.1.9",
3
+ "version": "1.3.0",
4
4
  "description": "Channel Manager worker daemon — runs on remote machines to execute video pipeline jobs",
5
5
  "main": "lib/daemon.js",
6
6
  "bin": {