diff --git a/.gitignore b/.gitignore index 154b271..9c1ddb1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ node_modules/ /tests/ /services/backup-api/test/ +/cloud-log-sync/ PROJECT_MEMORY.md .dev-runner.lock release/ diff --git a/README.md b/README.md index 6aa7ef0..d6d6cfb 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,14 @@ You can always install manually from the [GitHub releases page](https://github.c - Use the [latest release page](https://github.com/Sucukdeluxe/Multi-Hoster-Upload/releases/latest) for a manual download. - If the changelog cannot be loaded, the application can still show the fallback release description when one is available. +## Clouddrop log sync + +Settings → Logs & Support includes an optional Clouddrop connection for upload logs. Enter an unrestricted Clouddrop API key and select **Verify and enable**. Verification creates an empty test file in a folder named after the device's public IP address; ipify provides the public IP. The key is stored using the operating system's credential encryption. + +New successful upload entries for hosts with file logging enabled are synchronized automatically as TXT files. The single-file, daily and per-session log modes apply. Files have unique suffixes so separate instances using the same key do not overwrite one another. Large logs are split into separate files before they reach the text API size limit. Existing local log contents are not imported automatically. + +The panel shows the connection state, IP folder, last successful sync and pending files. Changes are queued locally, retried after connection failures and resumed after restarting the application. Disabling sync retains pending entries but stops collecting new ones. A revoked key requires verification with a valid key. Local pending data is tied to its Clouddrop account and is never sent to another account after changing keys. + ## Development and Windows builds Install dependencies and start the Electron application: diff --git a/lib/cloud-log-sync.js b/lib/cloud-log-sync.js new file mode 100644 index 0000000..e6bc8ff --- /dev/null +++ b/lib/cloud-log-sync.js @@ -0,0 +1,305 @@ +const fs = require('node:fs/promises'); +const path = require('node:path'); +const { randomUUID, createHash } = require('node:crypto'); +const { EventEmitter } = require('node:events'); +const { ClouddropLogApi, CloudLogError } = require('./clouddrop-log-api'); + +const MAX_DOCUMENT_BYTES = 700000; +const hash = value => createHash('sha256').update(value).digest('hex'); +const validId = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,100}$/.test(value); + +class CloudLogSync extends EventEmitter { + constructor({ directory, loadSettings, saveSettings, apiFactory, now = Date.now, delayMs = 750 }) { + super(); + this.directory = directory; + this.loadSettings = loadSettings; + this.saveSettings = saveSettings; + this.apiFactory = apiFactory || (key => new ClouddropLogApi(key)); + this.now = now; + this.delayMs = delayMs; + this.documents = new Map(); + this.dirty = new Set(); + this.localWrites = Promise.resolve(); + this.diskWrites = Promise.resolve(); + this.control = Promise.resolve(); + this.ready = null; + this.connection = null; + this.timer = null; + this.worker = null; + this.controller = null; + this.phase = 'disabled'; + this.errorCode = ''; + this.failures = 0; + this.closed = false; + this.retryBlocked = false; + this.documentTime = 0; + } + + async initialize() { + if (!this.ready) this.ready = this._load(); + await this.ready; + } + + async _load() { + await fs.mkdir(this.directory, { recursive: true }); + for (const name of await fs.readdir(this.directory)) { + if (!/^[a-f0-9-]{36}\.json$/.test(name)) continue; + let doc; + try { doc = JSON.parse(await fs.readFile(path.join(this.directory, name), 'utf8')); } + catch { throw new CloudLogError('LOCAL_STATE_INVALID'); } + if (doc.id + '.json' !== name || !validId(doc.accountId) || typeof doc.content !== 'string' + || Buffer.byteLength(doc.content) > MAX_DOCUMENT_BYTES || !validId(doc.folderId) + || !/^[a-f0-9]{64}$/.test(doc.source) || typeof doc.filename !== 'string') { + throw new CloudLogError('LOCAL_STATE_INVALID'); + } + this.documents.set(doc.id, doc); + doc.contentHash = hash(doc.content); + this.documentTime = Math.max(this.documentTime, Number(doc.createdAt) || 0); + } + } + + status() { + const settings = this.loadSettings() || {}; + const accountId = this.connection?.accountId || settings.accountId; + const docs = [...this.documents.values()].filter(doc => doc.accountId === accountId); + const pending = docs.filter(doc => doc.syncedHash !== doc.contentHash); + return { + enabled: settings.enabled === true, hasApiKey: Boolean(settings.apiKey), + phase: this.phase, errorCode: this.errorCode, + ip: this.connection?.ip || settings.ip || '', + pendingFiles: pending.length, + lastSyncedAt: Math.max(0, ...docs.map(doc => Number(doc.lastSyncedAt) || 0)), + fileCount: docs.length + }; + } + + notify() { this.emit('status', this.status()); } + + configure({ apiKey, enabled }) { + const operation = this.control.then(() => this._configure(apiKey, enabled)); + this.control = operation.catch(() => {}); + return operation; + } + + async _configure(apiKey, enabled) { + await this.initialize(); + clearTimeout(this.timer); + this.timer = null; + this.controller?.abort(); + if (this.worker) await this.worker; + await this.flushLocal(); + const previous = this.loadSettings() || {}; + this.retryBlocked = false; + this.connection = null; + if (!enabled) { + await this.saveSettings({ ...previous, enabled: false }); + this.phase = 'disabled'; + this.errorCode = ''; + this.notify(); + return this.status(); + } + this.phase = 'checking'; + this.errorCode = ''; + this.notify(); + const key = String(apiKey || previous.apiKey || '').trim(); + const api = this.apiFactory(key); + const controller = new AbortController(); + this.controller = controller; + try { + const identity = await api.identify(controller.signal); + if (!validId(identity.accountId)) throw new CloudLogError('INVALID_RESPONSE'); + const folderId = await api.ensureFolder(identity.folderName, controller.signal); + if (!validId(folderId)) throw new CloudLogError('INVALID_RESPONSE'); + const connection = { ...identity, folderId, api }; + const source = hash('connection-check'); + let probe = [...this.documents.values()].find(doc => doc.accountId === identity.accountId + && doc.folderId === folderId && doc.source === source); + if (!probe) { + probe = this._newDocument(connection, source, 'fileuploader-connection', ''); + await this._saveDocument(probe); + this.documents.set(probe.id, probe); + } + if (!probe.remoteId) { + probe.remoteId = await api.createFile(folderId, probe.filename, probe.id, controller.signal); + await this._saveDocument(probe); + } + await api.writeFile(probe.remoteId, '', controller.signal); + const verification = await api.readFile(probe.remoteId, controller.signal); + if (verification.content !== '') throw new CloudLogError('VERIFICATION_FAILED'); + probe.syncedHash = hash(''); + probe.lastSyncedAt = this.now(); + await this._saveDocument(probe); + await this.saveSettings({ enabled: true, apiKey: key, accountId: identity.accountId, ip: identity.ip, folderId }); + this.connection = connection; + this.phase = 'ready'; + this.failures = 0; + this.notify(); + this.schedule(); + return this.status(); + } catch (error) { + this.phase = 'error'; + this.errorCode = this._errorCode(error); + this.retryBlocked = ['INVALID_KEY', 'ACCESS_DENIED', 'UNRESTRICTED_KEY_REQUIRED', 'LOCAL_STATE_INVALID'].includes(this.errorCode); + this.notify(); + throw new CloudLogError(this.errorCode); + } finally { + if (this.controller === controller) this.controller = null; + } + } + + async start() { + try { + await this.initialize(); + if (this.loadSettings()?.enabled) await this.configure({ enabled: true }); + } catch (error) { + this.phase = 'error'; + this.errorCode = this._errorCode(error); + this.retryBlocked = ['INVALID_KEY', 'ACCESS_DENIED', 'UNRESTRICTED_KEY_REQUIRED', 'LOCAL_STATE_INVALID'].includes(this.errorCode); + this.notify(); + if (!['INVALID_KEY', 'ACCESS_DENIED', 'UNRESTRICTED_KEY_REQUIRED', 'LOCAL_STATE_INVALID'].includes(this.errorCode)) { + this.timer = setTimeout(() => { this.timer = null; void this.start(); }, 30000); + this.timer.unref?.(); + } + } + } + + _newDocument(connection, source, stem, content) { + const id = randomUUID(); + this.documentTime = Math.max(this.now(), this.documentTime + 1); + return { + id, accountId: connection.accountId, folderId: connection.folderId, source, + filename: `${stem.replace(/[^\p{L}\p{N}._-]/gu, '_').slice(0, 110)}-${id}.txt`, + content, contentHash: hash(content), remoteId: null, syncedHash: null, lastSyncedAt: 0, createdAt: this.documentTime + }; + } + + async append(sourcePath, line) { + await this.initialize(); + const settings = this.loadSettings() || {}; + if (!settings.enabled || !settings.accountId || typeof line !== 'string' || !line) return; + if (Buffer.byteLength(line) > MAX_DOCUMENT_BYTES) { + this.errorCode = 'LINE_TOO_LARGE'; + this.phase = 'error'; + this.notify(); + return; + } + const connection = this.connection || { + accountId: settings.accountId, folderId: settings.folderId, ip: settings.ip + }; + const known = [...this.documents.values()].filter(doc => doc.accountId === settings.accountId && doc.source !== hash('connection-check')); + if (!connection.folderId) connection.folderId = [...this.documents.values()] + .find(doc => doc.accountId === settings.accountId && doc.source === hash('connection-check'))?.folderId; + if (!connection.folderId) return; + const source = hash(`${sourcePath}|${connection.ip}|${connection.folderId}`); + let doc = known.filter(item => item.source === source).sort((a, b) => b.createdAt - a.createdAt)[0]; + if (!doc || Buffer.byteLength(doc.content) + Buffer.byteLength(line) > MAX_DOCUMENT_BYTES) { + doc = this._newDocument(connection, source, path.basename(sourcePath, path.extname(sourcePath)), ''); + this.documents.set(doc.id, doc); + } + doc.content += line; + doc.contentHash = hash(doc.content); + this.dirty.add(doc.id); + await this.flushLocal().then(() => this.schedule()).catch(error => { + this.phase = 'error'; + this.errorCode = this._errorCode(error); + this.notify(); + this.schedule(); + }); + } + + async _saveDocument(doc) { + const destination = path.join(this.directory, doc.id + '.json'); + const temporary = destination + '.tmp'; + const content = JSON.stringify(doc); + const operation = this.diskWrites.then(async () => { + await fs.writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 }); + await fs.rename(temporary, destination); + }); + this.diskWrites = operation.catch(() => {}); + return operation; + } + + flushLocal() { + const operation = this.localWrites.then(async () => { + for (const id of [...this.dirty]) { + const doc = this.documents.get(id); + const content = doc.content; + await this._saveDocument({ ...doc, content }); + if (doc.content === content) this.dirty.delete(id); + } + }); + this.localWrites = operation.catch(() => {}); + return operation; + } + + schedule(delay = this.delayMs) { + if (this.closed || this.retryBlocked || this.timer || this.worker || !this.loadSettings()?.enabled) return; + this.timer = setTimeout(() => { + this.timer = null; + if (!this.connection) { void this.start(); return; } + this.worker = this._sync().finally(() => { this.worker = null; }); + }, delay); + this.timer.unref?.(); + } + + async _sync() { + const connection = this.connection; + const controller = new AbortController(); + this.controller = controller; + try { + await this.flushLocal(); + this.phase = 'syncing'; + this.notify(); + for (const doc of this.documents.values()) { + if (doc.accountId !== connection.accountId || doc.syncedHash === doc.contentHash) continue; + const content = doc.content; + const contentHash = doc.contentHash; + if (!doc.remoteId) { + doc.remoteId = await connection.api.createFile(doc.folderId, doc.filename, doc.id, controller.signal); + await this._saveDocument(doc); + } + await connection.api.writeFile(doc.remoteId, content, controller.signal); + doc.syncedHash = contentHash; + doc.lastSyncedAt = this.now(); + await this._saveDocument(doc); + this.notify(); + } + this.phase = 'ready'; + this.errorCode = ''; + this.failures = 0; + } catch (error) { + this.phase = 'error'; + this.errorCode = this._errorCode(error); + this.failures++; + this.retryBlocked = ['INVALID_KEY', 'ACCESS_DENIED', 'UNRESTRICTED_KEY_REQUIRED'].includes(this.errorCode); + } finally { + if (this.controller === controller) this.controller = null; + this.notify(); + const pending = [...this.documents.values()].some(doc => doc.accountId === connection.accountId && doc.syncedHash !== doc.contentHash); + if (pending && !controller.signal.aborted && !this.retryBlocked && !this.closed) { + const delay = this.failures ? Math.min(300000, 5000 * 2 ** Math.min(this.failures - 1, 6)) : this.delayMs; + this.timer = setTimeout(() => { this.timer = null; this.schedule(0); }, delay); + this.timer.unref?.(); + } + } + } + + _errorCode(error) { + if (error instanceof CloudLogError) return error.code; + if (String(error?.code || '').startsWith('SECRET_STORE_')) return 'KEY_STORAGE_UNAVAILABLE'; + if (['EACCES', 'EPERM', 'ENOSPC', 'EIO'].includes(error?.code)) return 'LOCAL_WRITE_FAILED'; + return 'CONNECTION_FAILED'; + } + + async close() { + this.closed = true; + clearTimeout(this.timer); + this.timer = null; + this.controller?.abort(); + if (this.worker) await this.worker; + await this.flushLocal(); + await this.diskWrites; + } +} + +module.exports = { CloudLogSync, MAX_DOCUMENT_BYTES }; diff --git a/lib/clouddrop-log-api.js b/lib/clouddrop-log-api.js new file mode 100644 index 0000000..ab9c5c7 --- /dev/null +++ b/lib/clouddrop-log-api.js @@ -0,0 +1,119 @@ +const { request } = require('undici'); +const { isIP } = require('node:net'); + +class CloudLogError extends Error { + constructor(code, status = 0) { + super(code); + this.code = code; + this.status = status; + } +} + +class ClouddropLogApi { + constructor(apiKey, options = {}) { + this.apiKey = String(apiKey || '').trim(); + this.request = options.request || request; + } + + async call(route, { method = 'GET', body, signal, idempotencyKey } = {}) { + const response = await this.request(`https://clouddrop.cc/api/cloud${route}`, { + method, signal, maxRedirections: 0, headersTimeout: 20000, bodyTimeout: 20000, + headers: { + Authorization: `Bearer ${this.apiKey}`, + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': 'Multi-Hoster-Upload Log Sync', + ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}) + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) + }); + const chunks = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.length; + if (size > 2 * 1024 * 1024) { + response.body.destroy(); + throw new CloudLogError('RESPONSE_TOO_LARGE'); + } + chunks.push(chunk); + } + if (response.statusCode < 200 || response.statusCode >= 300) { + const code = response.statusCode === 401 ? 'INVALID_KEY' + : response.statusCode === 403 ? 'ACCESS_DENIED' + : response.statusCode === 429 ? 'RATE_LIMIT' : 'REMOTE_ERROR'; + throw new CloudLogError(code, response.statusCode); + } + let data; + try { data = JSON.parse(Buffer.concat(chunks).toString('utf8')); } + catch { throw new CloudLogError('INVALID_RESPONSE', response.statusCode); } + return data; + } + + async identify(signal) { + if (!/^cd_[a-f0-9]{32}$/.test(this.apiKey)) throw new CloudLogError('INVALID_KEY'); + const user = await this.call('/me', { signal }); + if (typeof user.id !== 'string' || !user.id) throw new CloudLogError('INVALID_RESPONSE'); + const response = await this.request('https://api64.ipify.org?format=json', { + signal, maxRedirections: 0, headersTimeout: 15000, bodyTimeout: 15000, + headers: { Accept: 'application/json' } + }); + const text = await response.body.text(); + let ip; + try { ip = JSON.parse(text).ip; } catch {} + if (response.statusCode !== 200 || !isIP(ip || '')) throw new CloudLogError('IP_UNAVAILABLE'); + return { accountId: user.id, ip, folderName: ip.replaceAll(':', '_') }; + } + + async ensureFolder(name, signal) { + const folders = await this.call('/folders?limit=5000', { signal }); + if (!Array.isArray(folders)) throw new CloudLogError('INVALID_RESPONSE'); + const existing = folders.find(folder => folder.name === name && !folder.parentId); + if (existing) return String(existing.id); + try { + const created = await this.call('/folder', { method: 'POST', signal, body: { name, parentId: null } }); + if (!created.id || created.file?.parentId) throw new CloudLogError('UNRESTRICTED_KEY_REQUIRED'); + return String(created.id); + } catch (error) { + if (error.status !== 409) throw error; + const refreshed = await this.call('/folders?limit=5000', { signal }); + const folder = refreshed.find(item => item.name === name && !item.parentId); + if (!folder) throw new CloudLogError('UNRESTRICTED_KEY_REQUIRED'); + return String(folder.id); + } + } + + async createFile(folderId, name, id, signal) { + let created; + try { + created = await this.call('/create-file', { + method: 'POST', signal, idempotencyKey: `mhu-log:${id}`, + body: { parentId: folderId, name } + }); + } catch (error) { + if (error.status !== 409) throw error; + const existing = await this.call(`/files?parent=${encodeURIComponent(folderId)}&limit=2500&sync=${encodeURIComponent(id)}`, { signal }); + const file = existing.files?.find(item => item.filename === name && item.parentId === folderId && !item.isFolder); + if (!file) throw error; + created = { id: file.id, filename: file.filename }; + } + if (!created.id || created.filename !== name) throw new CloudLogError('INVALID_RESPONSE'); + const listing = await this.call(`/files?parent=${encodeURIComponent(folderId)}&limit=2500&sync=${encodeURIComponent(id)}`, { signal }); + if (!Array.isArray(listing.files) || !listing.files.some(file => file.id === created.id && file.parentId === folderId)) { + throw new CloudLogError('UNRESTRICTED_KEY_REQUIRED'); + } + return String(created.id); + } + + async writeFile(id, content, signal) { + const data = await this.call(`/files/${encodeURIComponent(id)}/content`, { + method: 'PUT', signal, body: { content } + }); + if (data.ok !== true || data.size !== Buffer.byteLength(content)) throw new CloudLogError('INVALID_RESPONSE'); + } + + async readFile(id, signal) { + return this.call(`/files/${encodeURIComponent(id)}/content`, { signal }); + } +} + +module.exports = { ClouddropLogApi, CloudLogError }; diff --git a/lib/config-store.js b/lib/config-store.js index 99e327a..af85d8c 100644 --- a/lib/config-store.js +++ b/lib/config-store.js @@ -62,6 +62,7 @@ const DEFAULTS = { alwaysOnTop: false, shutdownAfterFinish: 'nothing', // nothing | sleep | shutdown | restart logFilePath: '', + cloudLogSync: { enabled: false, apiKey: '', accountId: '', ip: '', folderId: '' }, sessionLog: false, // legacy boolean (kept for back-compat reads); normalized into logMode on load logVerbose: false, // when true, [DEBUG] level entries are written to debug.log webhookUrl: '', // POST target on batch-done (Discord or generic JSON) @@ -499,7 +500,7 @@ class ConfigStore { const hosters = this._clone(config.hosters || {}); const globalSettings = this._clone(config.globalSettings || {}); delete globalSettings.allowPlaintextCredentialStorage; - secretStore.encryptCredentials({ hosters }); + secretStore.encryptCredentials({ hosters, globalSettings }); return JSON.stringify({ ...config, globalSettings, hosters }, null, 2); } @@ -721,6 +722,7 @@ class ConfigStore { uploadRecovery: currentGlobalSettings.uploadRecovery ?? null, lastBrowseDirectory: currentGlobalSettings.lastBrowseDirectory || '', diagnostics: this._clone(currentGlobalSettings.diagnostics || {}), + cloudLogSync: this._clone(currentGlobalSettings.cloudLogSync || {}), historyRetention: currentGlobalSettings.historyRetention || 'all', folderMonitor: { ...currentFolderMonitor, @@ -738,6 +740,15 @@ class ConfigStore { }); } + saveCloudLogSettings(settings) { + const snapshot = this._clone(settings); + return this._enqueueWrite(() => { + const current = this.load(); + current.globalSettings.cloudLogSync = snapshot; + return this._commit(current); + }); + } + saveRemoteSettings(remoteSettings, createToken) { const incoming = this._clone(remoteSettings || {}); return this._enqueueWrite(async () => { diff --git a/lib/secret-store.js b/lib/secret-store.js index 8539336..5597a62 100644 --- a/lib/secret-store.js +++ b/lib/secret-store.js @@ -77,6 +77,9 @@ function decryptField(value) { } function mapHosterAccounts(config, fn) { + if (config?.globalSettings?.cloudLogSync?.apiKey) { + config.globalSettings.cloudLogSync.apiKey = fn(config.globalSettings.cloudLogSync.apiKey); + } if (!config || !config.hosters || typeof config.hosters !== 'object') return config; for (const accounts of Object.values(config.hosters)) { if (!Array.isArray(accounts)) continue; diff --git a/lib/settings-backup.js b/lib/settings-backup.js index 1044d80..8a5f175 100644 --- a/lib/settings-backup.js +++ b/lib/settings-backup.js @@ -35,6 +35,11 @@ function createPortableSettingsSnapshot(config) { snapshot.globalSettings.pendingQueue = null; snapshot.globalSettings.uploadRecovery = null; snapshot.globalSettings.lastBrowseDirectory = ''; + if (snapshot.globalSettings.cloudLogSync) { + delete snapshot.globalSettings.cloudLogSync.accountId; + delete snapshot.globalSettings.cloudLogSync.ip; + delete snapshot.globalSettings.cloudLogSync.folderId; + } if (snapshot.globalSettings.folderMonitor && typeof snapshot.globalSettings.folderMonitor === 'object') { snapshot.globalSettings.folderMonitor.paused = false; snapshot.globalSettings.folderMonitor.pausedAt = null; diff --git a/main.js b/main.js index a1a61ba..dee0002 100644 --- a/main.js +++ b/main.js @@ -17,6 +17,7 @@ const DoodstreamUploader = require('./lib/doodstream-upload'); const { createDoodstreamOtpCoordinator, selectUploadAuth } = require('./lib/account-auth'); const { createAccountCooldownController, createAccountPicker, selectFallbackAccount } = require('./lib/account-rotation'); const ClouddropUploader = require('./lib/clouddrop-upload'); +const { CloudLogSync } = require('./lib/cloud-log-sync'); const { checkForUpdate, prepareUpdate, launchPreparedUpdate, abortUpdate, createUpdateAnnouncementState } = require('./lib/updater'); const backupCrypto = require('./lib/backup-crypto'); const { downloadOnlineBackup, downloadRecoveryPublicKey, normalizeOnlineBackupRetention } = require('./lib/online-backup'); @@ -127,6 +128,17 @@ let dropTargetWindow = null; let tray = null; let _cachedLogSettings = null; const configStore = new ConfigStore(app); +const cloudLogWrites = new Set(); +let cloudLogSettingsCache = null; +const cloudLogSync = new CloudLogSync({ + directory: path.join(app.getPath('userData'), 'cloud-log-sync'), + loadSettings: () => cloudLogSettingsCache || (cloudLogSettingsCache = configStore.load().globalSettings?.cloudLogSync || {}), + saveSettings: async settings => { + await configStore.saveCloudLogSettings(settings); + cloudLogSettingsCache = settings; + } +}); +cloudLogSync.on('status', status => safeSend('cloud-log:status', status)); configStore.setPerfLog((m) => { try { logInfo(m); } catch {} }); const onlineBackupKeyring = createOnlineBackupKeyring({ filePath: path.join(app.getPath('userData'), 'online-backup-keys.json') @@ -182,6 +194,8 @@ function assertConfigWriteAllowed() { } async function waitForConfigStoreWrites() { + await Promise.all([...cloudLogWrites]); + await cloudLogSync.flushLocal(); await configStore.drainWrites(); await configStore.drainAutomationCompletionWrites(); } @@ -1028,7 +1042,13 @@ function shouldLogHosterToFile(hoster) { } function appendUploadLog(hoster, link, fileName) { - _uploadLogBuffer.push(formatUploadLogLine(new Date(), hoster, link, fileName)); + const line = formatUploadLogLine(new Date(), hoster, link, fileName); + _uploadLogBuffer.push(line); + const cloudWrite = cloudLogSync.append(getLogFilePath(), line).catch(() => { + debugLog('cloud-log: local queue write failed'); + }); + cloudLogWrites.add(cloudWrite); + void cloudWrite.finally(() => cloudLogWrites.delete(cloudWrite)); if (!_uploadLogFlushTimer) { _uploadLogFlushTimer = setTimeout(() => { _uploadLogFlushTimer = null; @@ -1775,6 +1795,7 @@ app.whenReady().then(async () => { } createWindow(); createTray(); + void cloudLogSync.start(); // Minimize to tray instead of taskbar mainWindow.on('minimize', () => { @@ -1896,8 +1917,29 @@ ipcMain.handle('get-config', () => { return configStore.load(); }); +ipcMain.handle('cloud-log:status', event => { + if (!isTrustedOnlineBackupIpcEvent(event)) return null; + return cloudLogSync.status(); +}); + +ipcMain.handle('cloud-log:configure', async (event, payload = {}) => { + if (!isTrustedOnlineBackupIpcEvent(event)) return { ok: false, errorCode: 'ACCESS_DENIED' }; + assertConfigWriteAllowed(); + if (!payload || typeof payload !== 'object' || Array.isArray(payload) + || typeof payload.enabled !== 'boolean' || (payload.apiKey !== undefined && typeof payload.apiKey !== 'string')) { + return { ok: false, errorCode: 'INVALID_KEY' }; + } + try { + const status = await cloudLogSync.configure({ enabled: payload.enabled, apiKey: payload.apiKey?.slice(0, 200) }); + return { ok: true, status }; + } catch { + return { ok: false, errorCode: cloudLogSync.status().errorCode || 'CONNECTION_FAILED', status: cloudLogSync.status() }; + } +}); + ipcMain.handle('save-config', async (_event, config) => { assertConfigWriteAllowed(); + if (config?.globalSettings) config.globalSettings.cloudLogSync = configStore.load().globalSettings.cloudLogSync; await configStore.save(config); if (config && config.globalSettings) _invalidateLogSettings(config.globalSettings); try { @@ -2967,6 +3009,15 @@ ipcMain.handle('clear-history', async () => { }); async function syncImportedRuntime(config) { + cloudLogSettingsCache = config.globalSettings?.cloudLogSync || {}; + try { + await cloudLogSync.configure({ + enabled: config.globalSettings?.cloudLogSync?.enabled === true, + apiKey: config.globalSettings?.cloudLogSync?.apiKey || '' + }); + } catch { + debugLog('cloud-log: imported settings could not connect'); + } const warnings = []; try { setLogVerbose(!!config.globalSettings.logVerbose); diff --git a/preload.js b/preload.js index 5016126..945a7ef 100644 --- a/preload.js +++ b/preload.js @@ -80,6 +80,13 @@ contextBridge.exposeInMainWorld('api', { // Log import readOwnUploadLog: () => ipcRenderer.invoke('read-own-upload-log'), importUploadLog: () => ipcRenderer.invoke('import-upload-log'), + getCloudLogStatus: () => ipcRenderer.invoke('cloud-log:status'), + configureCloudLog: (settings) => ipcRenderer.invoke('cloud-log:configure', settings), + onCloudLogStatus: callback => { + const listener = (_event, status) => callback(status); + ipcRenderer.on('cloud-log:status', listener); + return () => ipcRenderer.removeListener('cloud-log:status', listener); + }, // Clipboard copyToClipboard: (text) => ipcRenderer.invoke('copy-to-clipboard', text), diff --git a/renderer/app.js b/renderer/app.js index 26f81fa..cc8079d 100644 --- a/renderer/app.js +++ b/renderer/app.js @@ -40,6 +40,7 @@ function refreshLocalizedRuntimeUi() { updateStatusBar(); refreshAutomationControlCenter(); refreshAutomationTestOverlay(); + renderCloudLogStatus(cloudLogLastStatus); const activeRecentTab = document.querySelector('.recent-tab.active'); const hint = document.getElementById('recentFilesHint'); if (hint && activeRecentTab) hint.textContent = localizeUiText(activeRecentTab.dataset.panel === 'statsTab' ? 'Upload-Statistiken' : 'Zuletzt erzeugte Upload-Links'); @@ -6384,6 +6385,69 @@ async function runHealthCheck(mode = 'manual', requestedHosters = null) { } // --- Settings --- +let cloudLogBusy = false; +let cloudLogLastStatus = null; +const cloudLogErrors = { + KEY_STORAGE_UNAVAILABLE: 'Der API-Key konnte nicht im sicheren Zugangsdaten-Speicher gesichert werden.', + INVALID_KEY: 'Der Clouddrop-API-Key ist ungültig oder wurde widerrufen.', + ACCESS_DENIED: 'Der API-Key hat keine Berechtigung für diese Aktion.', + UNRESTRICTED_KEY_REQUIRED: 'Für die Synchronisierung wird ein API-Key ohne Zielordner-Bindung benötigt.', + IP_UNAVAILABLE: 'Die öffentliche IP-Adresse konnte nicht ermittelt werden.', + CONNECTION_FAILED: 'Clouddrop ist nicht erreichbar. Ausstehende Einträge bleiben lokal gespeichert.', + RATE_LIMIT: 'Clouddrop begrenzt die Anfragen. Die Synchronisierung wird automatisch erneut versucht.', + LOCAL_WRITE_FAILED: 'Die lokale Synchronisierungsdatei konnte nicht gespeichert werden. Bitte Speicherplatz und Zugriffsrechte prüfen.', + LOCAL_STATE_INVALID: 'Die lokale Synchronisierungsdatei konnte nicht gelesen werden.', + REMOTE_ERROR: 'Clouddrop hat die Aktualisierung abgelehnt. Ausstehende Einträge bleiben lokal gespeichert.', + INVALID_RESPONSE: 'Clouddrop hat eine unerwartete Antwort geliefert.', + VERIFICATION_FAILED: 'Die Testdatei konnte nicht verifiziert werden.', + RESPONSE_TOO_LARGE: 'Die Clouddrop-Antwort überschreitet die zulässige Größe.', + LINE_TOO_LARGE: 'Ein Log-Eintrag überschreitet die zulässige Größe.' +}; + +function renderCloudLogStatus(status) { + if (status) cloudLogLastStatus = status; + if (!status || !document.getElementById('cloudLogPhase')) return; + const phases = { disabled: 'Inaktiv', checking: 'Verbindung wird geprüft…', ready: 'Aktiv', syncing: 'Wird synchronisiert…', error: 'Synchronisierung fehlgeschlagen' }; + document.getElementById('cloudLogPhase').textContent = localizeUiText(phases[status.phase] || phases.disabled); + document.getElementById('cloudLogIp').textContent = status.ip ? status.ip.replaceAll(':', '_') : '—'; + document.getElementById('cloudLogLastSync').textContent = status.lastSyncedAt + ? new Date(status.lastSyncedAt).toLocaleString(getUiLocale()) : localizeUiText('Noch nicht synchronisiert'); + document.getElementById('cloudLogPending').textContent = (Number(status.pendingFiles) || 0).toLocaleString(getUiLocale()); + const key = document.getElementById('cloudLogKeyInput'); + key.placeholder = localizeUiText(status.hasApiKey ? 'Gespeicherten API-Key verwenden' : 'API-Key eingeben'); + document.getElementById('cloudLogActivateBtn').disabled = cloudLogBusy; + document.getElementById('cloudLogDisableBtn').disabled = cloudLogBusy || !status.enabled; + const error = document.getElementById('cloudLogError'); + error.hidden = !status.errorCode; + error.textContent = status.errorCode ? localizeUiText(cloudLogErrors[status.errorCode] || cloudLogErrors.CONNECTION_FAILED) : ''; +} + +async function refreshCloudLogStatus() { + try { renderCloudLogStatus(await window.api.getCloudLogStatus?.()); } catch {} +} + +async function configureCloudLog(enabled) { + if (cloudLogBusy) return; + cloudLogBusy = true; + const key = document.getElementById('cloudLogKeyInput'); + document.getElementById('cloudLogActivateBtn').disabled = true; + document.getElementById('cloudLogDisableBtn').disabled = true; + try { + const result = await window.api.configureCloudLog({ enabled, apiKey: key?.value.trim() || '' }); + if (result?.ok) { + if (key) key.value = ''; + showCopyToast(enabled ? 'Clouddrop-Log-Synchronisierung ist aktiv.' : 'Clouddrop-Log-Synchronisierung ist deaktiviert.'); + } else { + showCopyToast(cloudLogErrors[result?.errorCode] || cloudLogErrors.CONNECTION_FAILED, 6500, 'error'); + } + } catch { + showCopyToast(cloudLogErrors.CONNECTION_FAILED, 6500, 'error'); + } finally { + cloudLogBusy = false; + await refreshCloudLogStatus(); + } +} + async function _renderLogPathsList(el) { if (!el || !window.api || !window.api.getLogPaths) return; try { @@ -6754,6 +6818,24 @@ function renderSettings() { +
Erfolgreiche Uploads automatisch als TXT in einem Clouddrop-Ordner mit der öffentlichen IP-Adresse dieses Geräts speichern. Die Übertragung beginnt mit der Aktivierung und folgt dem gewählten Log-Datei-Modus.
+API-Key ohne Zielordner-Bindung verwenden. Bei der Prüfung wird eine leere Testdatei im IP-Ordner erstellt. Die öffentliche IP wird über ipify ermittelt.
+