Ora / app /main.cjs
umer-wasim's picture
Ora 0.6.0: Automations with your own n8n, Campaigns, step-by-step setup
6acd609 verified
Raw History Blame Contribute Delete
52.8 kB
'use strict';
// Ora: a step-by-step marketing plan (brand, personas, competitors, campaign, content calendar, results,
// presentation) with AI help and pictures made online on the user's own free Cloudflare account.
// The renderer talks to this file over IPC (preload.cjs); online calls live in remote.cjs.
const { app, BrowserWindow, ipcMain, dialog, shell, protocol, net, nativeTheme } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const crypto = require('node:crypto');
const { spawn } = require('node:child_process');
const { pathToFileURL } = require('node:url');
const core = require('./core.cjs');
const { createRemote } = require('./remote.cjs');
// PLAN_USER_DATA / PLAN_SAVE_DIR (development only): a separate app folder and output folder for test runs
if (!app.isPackaged && process.env.PLAN_USER_DATA) app.setPath('userData', process.env.PLAN_USER_DATA);
const DATA = app.getPath('userData');
// pictures live where Ora 0.4 (the video app) kept its pictures, so plans made there keep their logos and portraits;
// the videos it also kept there are left alone (only pictures are listed)
const PICS = path.join(DATA, 'videos'); // one folder per picture job: meta.json, img_00.jpg, poster_00.png
const DEV_OUT = !app.isPackaged && process.env.PLAN_SAVE_DIR;
const PIC_DIR = DEV_OUT ? path.join(DEV_OUT, 'pictures') : path.join(app.getPath('pictures'), 'Ora'); // copies for posting
const DOC_DIR = DEV_OUT ? path.join(DEV_OUT, 'documents') : path.join(app.getPath('documents'), 'Ora'); // exports
const PLAN = path.join(DATA, 'plan.json');
const remote = createRemote(DATA);
// PLAN_FAKE_CF (development only): a pretend Cloudflare that returns a bundled photo and short texts, for testing
// the picture queue and captions without an account
if (!app.isPackaged && process.env.PLAN_FAKE_CF) {
const real = remote.status;
remote.status = () => ({ ...real(), cloudflare: { connected: true, account: 'fake00…' } });
remote.runCloudflare = async (_p, _s, steps, count, onImage) => { await new Promise(r => setTimeout(r, 300)); onImage(1, 1); return { images: [fs.readFileSync(path.join(__dirname, 'renderer', 'demo', 'latte.jpg'))], neurons: count * remote.cfNeurons(steps) }; };
remote.cfText = async () => 'A fresh latte to start your day ☕\n\nCome by this week.\n\n#coffee #latte';
}
let win = null;
let job = null; // { id, cancelled } while pictures are being made online
protocol.registerSchemesAsPrivileged([{ scheme: 'ora', privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true, stream: true } }]);
if (!app.requestSingleInstanceLock()) app.quit();
app.on('second-instance', () => { if (win) { if (win.isMinimized()) win.restore(); win.show(); win.focus(); } });
function send(channel, payload) { if (win && !win.isDestroyed()) win.webContents.send(channel, payload); }
// --- pictures ----------------------------------------------------------------------------------------------------
async function listPictures() {
let dirs = [];
try { dirs = await fsp.readdir(PICS); } catch { return []; }
const out = [];
for (const d of dirs) {
try {
const meta = JSON.parse(await fsp.readFile(path.join(PICS, d, 'meta.json'), 'utf8'));
if (meta.status === 'done' && meta.kind === 'image' && Array.isArray(meta.images) && meta.images.length) out.push(meta);
} catch { }
}
return out.sort((a, b) => b.created.localeCompare(a.created));
}
async function writeMeta(dir, meta) { await fsp.writeFile(path.join(dir, 'meta.json'), JSON.stringify(meta, null, 2)); }
function insidePics(id) {
const dir = path.resolve(PICS, String(id));
if (path.dirname(dir) !== path.resolve(PICS)) throw new Error('bad id');
return dir;
}
function newId(title, project) {
return `${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}-${project ? `${project.index}-` : ''}${core.slug(title, 24)}`;
}
// The poster text Ora draws over a picture (never drawn by the model, so the spelling is exact)
function cleanPoster(p) {
if (!p || typeof p !== 'object') return undefined;
const str = (v, n) => typeof v === 'string' ? v.slice(0, n) : '';
const out = { title: str(p.title, 90), sub: str(p.sub, 140), details: str(p.details, 300), cta: str(p.cta, 40),
layout: ['top', 'band', 'card', 'left'].includes(p.layout) ? p.layout : 'top',
font: ['modern', 'serif', 'display'].includes(p.font) ? p.font : 'modern',
accent: /^#[0-9a-f]{6}$/i.test(p.accent || '') ? p.accent : '#1c1530',
format: ['insta', 'portrait', 'square', 'landscape', 'linkedin'].includes(p.format) ? p.format : 'insta' };
if (p.carousel && Array.isArray(p.slides)) { out.carousel = true; out.slides = p.slides.slice(0, 6).map(x => str(x, 140)); }
if (p.logo && typeof p.logo.id === 'string' && /^[\w.-]+\.(png|jpe?g|webp)$/i.test(p.logo.file || '')) out.logo = { id: p.logo.id, file: p.logo.file };
return out;
}
function baseMeta(id, req, extra) {
return {
id, kind: 'image', created: new Date().toISOString(), status: 'running', prompt: req.prompt, count: req.count, seed: req.seed, poster: cleanPoster(req.poster),
project: req.project ? { folder: req.project.folder, index: req.project.index, total: req.project.total, title: req.project.title } : undefined, ...extra,
};
}
// Copies the finished pictures to Pictures/Ora/<batch>/ as "01 title.jpg" and tells the renderer.
async function finishImages({ id, dir, meta, req }) {
const images = (await fsp.readdir(dir)).filter(f => /^img_\d+\.(png|jpg)$/.test(f)).sort();
if (!images.length) return failed(id, dir, meta, 'No picture came back.');
const dirOut = path.join(PIC_DIR, req.project ? req.project.folder : '');
await fsp.mkdir(dirOut, { recursive: true });
const base = req.project ? `${String(req.project.index).padStart(2, '0')} ${core.folderName(req.project.title, 40)}` : `Ora ${meta.created.slice(0, 10)} ${core.slug(req.prompt, 40)}`;
meta.savedFiles = [];
for (const [i, f] of images.entries()) {
const ext = path.extname(f);
let target = path.join(dirOut, `${base}${i ? ` ${i + 1}` : ''}${ext}`), n = 2;
while (fs.existsSync(target)) target = path.join(dirOut, `${base}${i ? ` ${i + 1}` : ''} (${n++})${ext}`);
await fsp.copyFile(path.join(dir, f), target);
meta.savedFiles.push(target);
}
Object.assign(meta, { status: 'done', images, savedTo: meta.savedFiles[0] });
await writeMeta(dir, meta);
send('job:end', { id, meta, done: true });
}
async function failed(id, dir, meta, error) {
meta.status = 'failed'; meta.error = error;
await writeMeta(dir, meta).catch(() => { });
send('job:end', { id, error });
}
// Cloudflare Workers AI: FLUX.1-schnell, 1024x1024 JPEGs, a few seconds each, counted against today's free Neurons.
async function imagesOnCloudflare(input) {
if (job) throw new Error('Pictures are already being made. Wait until they are finished, or stop them.');
const req = { ...input, count: 1, seed: crypto.randomInt(0, 2 ** 31 - 1) };
const errors = core.validateProject(req.project);
if (typeof req.prompt !== 'string' || req.prompt.trim().length < 3) errors.push('Describe the picture first.');
if (errors.length) throw new Error(errors.join(' '));
req.prompt = req.prompt.slice(0, 2000);
const steps = 4;
const usage = usageSummary().cloudflare;
if (usage.left < remote.cfNeurons(steps)) throw new Error(`Not enough free Cloudflare Neurons left today (${Math.round(usage.left)} left). They reset at 00:00 UTC.`);
const id = newId(req.project ? req.project.title : req.prompt, req.project);
const dir = path.join(PICS, id);
await fsp.mkdir(dir, { recursive: true });
const meta = baseMeta(id, req, { model: 'cf-flux1s', modelLabel: 'FLUX.1-schnell (Cloudflare)', width: 1024, height: 1024, where: 'cloudflare' });
await writeMeta(dir, meta);
job = { id, cancelled: false };
send('job:update', { id, stage: 'running', where: 'cloudflare' });
let res;
try {
res = await remote.runCloudflare(req.prompt, req.seed, steps, 1, () => { }, () => job && job.cancelled);
} catch (e) {
job = null;
return failed(id, dir, meta, e.message);
}
const cancelled = job && job.cancelled;
job = null;
recordNeurons(res.neurons);
if (cancelled && !res.images.length) { await fsp.rm(dir, { recursive: true, force: true }); send('job:end', { id, cancelled: true }); return; }
for (const [i, b] of res.images.entries()) await fsp.writeFile(path.join(dir, `img_${String(i).padStart(2, '0')}.jpg`), b);
return finishImages({ id, dir, meta, req });
}
// --- online usage: Cloudflare's free Neurons today ---------------------------------------------------------------
const USAGE = path.join(DATA, 'online-usage.json');
function readUsage() { try { return JSON.parse(fs.readFileSync(USAGE, 'utf8')); } catch { return {}; } }
function writeUsage(u) { fs.mkdirSync(DATA, { recursive: true }); fs.writeFileSync(USAGE, JSON.stringify(u, null, 2)); }
function recordNeurons(n) {
const u = readUsage(), today = new Date().toISOString().slice(0, 10); // the free Neurons reset at 00:00 UTC
u.cf = { day: today, neurons: (u.cf && u.cf.day === today ? u.cf.neurons : 0) + n };
writeUsage(u);
}
function usageSummary() {
const u = readUsage(), today = new Date().toISOString().slice(0, 10);
const cf = u.cf && u.cf.day === today ? u.cf.neurons : 0;
return { cloudflare: { today: Math.round(cf), left: Math.max(0, 10000 - cf), perImage: remote.cfNeurons(4) } };
}
// --- window --------------------------------------------------------------------------------------------------------
function createWindow() {
win = new BrowserWindow({
width: 1280, height: 840, minWidth: 960, minHeight: 640, title: 'Ora', backgroundColor: '#f6f4f0',
webPreferences: { preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true, backgroundThrottling: !process.env.PLAN_SMOKE },
});
win.removeMenu();
win.loadFile(path.join(__dirname, 'renderer', 'index.html'));
win.webContents.setWindowOpenHandler(({ url }) => { if (/^https:\/\//.test(url)) shell.openExternal(url); return { action: 'deny' }; });
win.webContents.on('will-navigate', e => e.preventDefault());
// PLAN_SMOKE=<dir> (development): run PLAN_SMOKE_JS, save screenshots to <dir> (more at PLAN_SMOKE_SHOTS ms, each
// after the matching "||"-separated step of PLAN_SMOKE_STEP_JS), then quit
if (process.env.PLAN_SMOKE) {
if (process.env.PLAN_SMOKE_DARK) nativeTheme.themeSource = 'dark';
win.webContents.on('console-message', e => fs.appendFileSync(path.join(process.env.PLAN_SMOKE, 'console.log'), `${e.level}: ${e.message} (${e.sourceId}:${e.lineNumber})\n`));
win.webContents.once('did-finish-load', async () => {
const dir = process.env.PLAN_SMOKE, wait = ms => new Promise(r => setTimeout(r, ms));
// a window in the background may not repaint: force a fresh frame before each screenshot
const shot = async () => { win.webContents.invalidate(); await wait(300); return (await win.webContents.capturePage()).toPNG(); };
await wait(1200);
if (process.env.PLAN_SMOKE_JS) {
const out = await win.webContents.executeJavaScript(process.env.PLAN_SMOKE_JS).catch(e => `error: ${e.message}`);
fs.writeFileSync(path.join(dir, 'smoke.json'), JSON.stringify(out, null, 2));
await wait(800);
}
fs.writeFileSync(path.join(dir, 'screen.png'), await shot());
const times = (process.env.PLAN_SMOKE_SHOTS || '').split(',').filter(Boolean).map(Number);
const steps = (process.env.PLAN_SMOKE_STEP_JS || '').split('||');
for (const [i, t] of times.entries()) {
if (steps[i]) await win.webContents.executeJavaScript(steps[i]).catch(e => fs.writeFileSync(path.join(dir, `error-${i + 1}.txt`), e.message));
await wait(t);
fs.writeFileSync(path.join(dir, `screen-${i + 1}.png`), await shot());
}
app.quit();
});
}
}
app.whenReady().then(() => {
// ora://pic/<id>/<file>: the pictures (and the poster copies with their text) for the renderer
protocol.handle('ora', async req => {
const u = new URL(req.url);
const parts = decodeURIComponent(u.pathname).split('/').filter(Boolean);
if (u.host !== 'pic' || parts.length !== 2) return new Response('not found', { status: 404 });
let file;
try { file = path.resolve(insidePics(parts[0]), parts[1]); } catch { return new Response('bad', { status: 400 }); }
if (path.dirname(file) !== path.resolve(PICS, parts[0]) || !fs.existsSync(file)) return new Response('not found', { status: 404 });
const res = await net.fetch(pathToFileURL(file).toString());
const headers = new Headers(res.headers);
headers.set('Access-Control-Allow-Origin', '*');
return new Response(res.body, { status: res.status, headers });
});
ipcMain.handle('state', async () => ({ version: app.getVersion(), pictures: await listPictures(), picDir: PIC_DIR, docDir: DOC_DIR, running: job ? job.id : null }));
ipcMain.handle('project:create', async (_e, name) => {
const base = `${new Date().toISOString().slice(0, 10)} ${core.folderName(name, 50)}`;
let folder = base, n = 2;
while (fs.existsSync(path.join(PIC_DIR, folder))) folder = `${base} ${n++}`;
return folder; // created when the first picture is saved
});
ipcMain.handle('image:start', (_e, input) => { imagesOnCloudflare(input || {}).catch(e => send('job:end', { error: e.message })); return true; });
ipcMain.handle('job:cancel', () => { if (job) job.cancelled = true; return true; });
// a logo or a persona photo: copied into Ora's pictures folder so it can be shown and used offline
ipcMain.handle('photo:pick', async (_e, purpose) => {
const r = await dialog.showOpenDialog(win, {
title: purpose === 'logo' ? 'Choose your logo (PNG with transparency works best)' : 'Choose a photo',
properties: ['openFile'], filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],
});
if (r.canceled || !r.filePaths[0]) return null;
const src = r.filePaths[0];
if ((await fsp.stat(src)).size > 40e6) throw new Error('That picture is larger than 40 MB.');
const ext = path.extname(src).toLowerCase().replace('.jpeg', '.jpg');
if (!/^\.(png|jpg|webp)$/.test(ext)) throw new Error('Ora cannot use this kind of file.');
const id = `upload-${Date.now()}`;
await fsp.mkdir(path.join(PICS, id), { recursive: true });
await fsp.copyFile(src, path.join(PICS, id, `photo${ext}`));
return { id, file: `photo${ext}`, name: path.basename(src) };
});
// a poster with its text, drawn by the renderer: kept beside the picture (poster_00.png, shown in the app) and as a
// file in Pictures/Ora, replacing an earlier save of the same poster
ipcMain.handle('poster:save', async (_e, id, index, bytes, posterSpec) => {
const dir = insidePics(id);
const meta = JSON.parse(await fsp.readFile(path.join(dir, 'meta.json'), 'utf8'));
if (!Number.isInteger(index) || index < 0 || index > 5 || !bytes || bytes.byteLength > 40e6) throw new Error('bad poster');
const buf = Buffer.from(bytes);
const own = `poster_${String(index).padStart(2, '0')}.png`;
await fsp.writeFile(path.join(dir, own), buf);
const dirOut = path.join(PIC_DIR, meta.project ? meta.project.folder : '');
await fsp.mkdir(dirOut, { recursive: true });
const base = meta.project ? `${String(meta.project.index).padStart(2, '0')} ${core.folderName((posterSpec && posterSpec.title) || meta.project.title, 40)}` : `Ora poster ${meta.created.slice(0, 10)}`;
const target = path.join(dirOut, `${base} poster${index ? ` ${index + 1}` : ''}.png`);
await fsp.writeFile(target, buf);
meta.posterImages = meta.posterImages || []; meta.posterImages[index] = own;
meta.posterFiles = meta.posterFiles || []; meta.posterFiles[index] = target;
if (posterSpec) meta.poster = cleanPoster(posterSpec);
await writeMeta(dir, meta);
return meta;
});
ipcMain.handle('picture:delete', async (_e, id) => { await fsp.rm(insidePics(id), { recursive: true, force: true }); return listPictures(); });
// shows a saved file in Finder / Explorer (only Ora's own output folders)
ipcMain.handle('reveal', (_e, p) => {
const ok = typeof p === 'string' && [PIC_DIR, DOC_DIR].some(d => path.resolve(p).startsWith(path.resolve(d) + path.sep)) && fs.existsSync(p);
if (ok) shell.showItemInFolder(p);
return ok;
});
ipcMain.handle('open:folder', async (_e, which) => { const d = which === 'docs' ? DOC_DIR : PIC_DIR; await fsp.mkdir(d, { recursive: true }); return shell.openPath(d); });
// connections
ipcMain.handle('online:status', () => ({ ...remote.status(), usage: usageSummary() }));
ipcMain.handle('online:cloudflare', (_e, account, token) => remote.connectCloudflare(account, token));
ipcMain.handle('online:cfTest', () => remote.cfTest());
ipcMain.handle('online:disconnect', (_e, which) => remote.disconnect(which === 'n8n' ? 'n8n' : 'cloudflare'));
// n8n: connect (a new link) or test again (no link), send posts, and save Ora's automation for importing into n8n
ipcMain.handle('n8n:test', (_e, url) => remote.n8nTest(url));
ipcMain.handle('n8n:sheet', (_e, link) => remote.n8nSetSheet(link));
ipcMain.handle('n8n:email', (_e, address) => remote.n8nSetEmail(address));
ipcMain.handle('n8n:account', (_e, id, use) => remote.n8nAccount(id, !!use));
// LinkedIn posts: each { postAt (ISO), caption, picture (a picture id) }; the poster (with its text) goes with it
ipcMain.handle('n8n:linkedin', async (_e, list) => {
if (!Array.isArray(list) || !list.length || list.length > 60) throw new Error('No LinkedIn posts to set.');
let set = 0; const cancels = [];
for (const p of list) {
const at = Date.parse(p && p.postAt);
if (!Number.isFinite(at)) { cancels.push(null); continue; }
const dir = insidePics(p.picture);
const meta = JSON.parse(await fsp.readFile(path.join(dir, 'meta.json'), 'utf8'));
const file = (meta.posterImages || [])[0] || (meta.images || [])[0];
if (!file) { cancels.push(null); continue; }
const bytes = await fsp.readFile(path.join(dir, file));
if (bytes.length > 8e6) throw new Error('A picture is too big to send to LinkedIn (8 MB at most).');
const j = await remote.n8nLinkedIn({ postAt: new Date(at).toISOString(), caption: String(p.caption || '').slice(0, 2900), image: bytes.toString('base64'),
fileName: `${core.folderName((meta.poster && meta.poster.title) || 'Ora post', 40)}${path.extname(file)}`, mimeType: /\.png$/i.test(file) ? 'image/png' : 'image/jpeg' });
cancels.push((j && j.cancel) || null);
set++;
}
return { set, cancels };
});
// Plan › Campaigns: delete sheet rows by ID, and stop waiting reminders and LinkedIn posts by their cancel links
ipcMain.handle('n8n:unlog', (_e, ids) => {
const list = (Array.isArray(ids) ? ids : []).map(String).filter(x => x && x.length <= 200).slice(0, 400);
if (!list.length) return { deleted: 0 };
return remote.n8nUnlog(list);
});
ipcMain.handle('n8n:cancel', async (_e, links) => {
let cancelled = 0, gone = 0;
for (const l of (Array.isArray(links) ? links : []).slice(0, 200)) { const r = await remote.n8nCancel(l); if (r.cancelled) cancelled++; else gone++; }
return { cancelled, gone };
});
// reminders: each { remindAt (ISO time), subject, text }, scheduled one by one (n8n waits for each)
ipcMain.handle('n8n:remind', async (_e, list) => {
if (!Array.isArray(list) || !list.length || list.length > 60) throw new Error('No reminders to set.');
// cancels: one per reminder, in order: its cancel link from n8n (Plan › Campaigns can stop it), or null
let set = 0; const cancels = [];
for (const r of list) {
const at = Date.parse(r && r.remindAt);
if (!Number.isFinite(at)) { cancels.push(null); continue; }
const j = await remote.n8nRemind({ remindAt: new Date(at).toISOString(), subject: String(r.subject || '').slice(0, 200), text: String(r.text || '').slice(0, 8000) });
cancels.push((j && j.cancel) || null);
set++;
}
return { set, cancels };
});
ipcMain.handle('n8n:send', (_e, posts) => {
if (!Array.isArray(posts) || !posts.length || posts.length > 60) throw new Error('Nothing to send.');
const s = (v, n) => (typeof v === 'string' ? v.slice(0, n) : '');
const clean = posts.map(p => ({ id: s(p.id, 120), date: s(p.date, 10), time: s(p.time, 5), title: s(p.title, 200), picture: s(p.picture, 200),
platforms: (Array.isArray(p.platforms) ? p.platforms : []).filter(x => ['instagram', 'facebook', 'linkedin'].includes(x)),
captions: Object.fromEntries(['instagram', 'facebook', 'linkedin'].map(k => [k, s((p.captions || {})[k], 3000)])) }));
return remote.n8nSend(clean);
});
const AUTOMATIONS = 'Google Sheets log + Gmail reminders + LinkedIn posts'; // what Ora's automation does
// Each saved automation is its own: a name with the plan and the time, its own webhook address and its own ids,
// so two of them in one n8n never clash (n8n will not publish two workflows that listen at the same address)
ipcMain.handle('n8n:workflow', async (_e, label) => {
const wf = JSON.parse(await fsp.readFile(path.join(__dirname, 'n8n', 'ora-automation.json'), 'utf8'));
const now = new Date(), pad = n => String(n).padStart(2, '0');
const when = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
const plan = String(label || '').replace(/\s+/g, ' ').trim().slice(0, 40) || 'my plan';
const key = crypto.randomBytes(5).toString('hex');
// what it does, for which plan, when it was saved, and a code that matches the end of its link (ora-…)
wf.name = `Ora · ${AUTOMATIONS} · ${plan} · ${when} · ${key.slice(0, 4)}`;
for (const node of wf.nodes) {
if (node.webhookId) node.webhookId = crypto.randomUUID();
// a readable, unique address: what it does, the plan, and the code shown in its name
if (node.type === 'n8n-nodes-base.webhook') node.parameters.path = `ora-auto-${core.slug(plan, 24)}-${key.slice(0, 4)}`;
}
// the file name says the same (folder-safe), so it is easy to find in Documents/Ora
const target = await uniqueDoc(wf.name.replace(/\+/g, 'and'), 'json', 120);
await fsp.writeFile(target, JSON.stringify(wf, null, 2));
shell.showItemInFolder(target);
return { file: target, name: wf.name, folder: path.dirname(target) };
});
ipcMain.handle('online:open', (_e, which) => shell.openExternal({
cloudflare: 'https://dash.cloudflare.com/?to=/:account/ai/workers-ai', cloudflareSignup: 'https://dash.cloudflare.com/sign-up', cloudflareSite: 'https://www.cloudflare.com/developer-platform/products/workers-ai/',
n8nSignup: 'https://n8n.io/', n8nApp: 'https://app.n8n.cloud/', googleSheets: 'https://sheets.new',
}[which] || 'https://dash.cloudflare.com/sign-up'));
// A text model that declines answers with an apology instead of the text: never paste that into the plan
const refused = t => /^(i('| a)m sorry|i can('|no)t|i cannot|sorry,|i'm not able|i am not able|i won't|as an ai)/i.test(String(t).trim());
const lineList = (t, test, n) => t.split('\n').map(x => x.replace(/^\s*(\d+[.)]|[-•*])\s*/, '').trim()).filter(test).slice(0, n);
// ✨ Suggest: campaign names, content ideas, taglines and a mission (Cloudflare's small text model). The renderer
// falls back to its own offline suggestions when this throws "offline".
ipcMain.handle('prompt:improve', async (_e, text, kind) => {
text = String(text || '').slice(0, 1200).trim();
if (text.length < 2) throw new Error('Write a few words first.');
if (!remote.status().cloudflare.connected) throw new Error('offline');
if (kind === 'campaign') {
const out = await remote.cfText('You plan marketing campaigns for small businesses. From the facts given, suggest 3 campaign ideas, each on one line as "Name | key message": the name at most 4 words, the message one sentence of at most 14 words. No numbering, no quotes, no emojis. Use only the facts given.', text);
if (refused(out)) throw new Error('declined');
const lines = lineList(out.replace(/["“”]/g, ''), x => x.includes('|'), 3);
if (!lines.length) throw new Error('offline');
return lines.join('\n');
}
if (kind === 'ideas') {
const out = await remote.cfText('You plan social media content for a small business. From the brand facts given, write 10 post ideas, one per line, as "type: idea". type is one of educational, storytelling, behind-the-scenes, community, lifestyle, promotion; use each type at least once. Each idea is at most 12 words, concrete and doable with a phone or simple pictures. No numbering, no emojis, no hashtags. Use only the facts given.', text);
if (refused(out)) throw new Error('declined');
const lines = lineList(out, x => /^[a-z -]+:/i.test(x), 12);
if (lines.length < 3) throw new Error('offline');
return lines.join('\n');
}
if (kind === 'tagline' || kind === 'mission') {
const sys = kind === 'tagline'
? 'You write brand taglines for small businesses. From the brand facts given, write 3 short taglines (at most 7 words each), one per line, no numbering, no quotes. Use only the facts given.'
: 'You write brand mission statements for small businesses. From the facts given, write one clear mission statement of at most 30 words: who the brand serves, what it does and why. Reply with the sentence only.';
const out = await remote.cfText(sys, text);
if (refused(out)) throw new Error('declined');
return lineList(out, Boolean, 3).map(x => x.replace(/^["“]|["”]$/g, '')).join('\n');
}
// a persona's portrait shows a woman or a man: whether this first name is usually one or the other (or unsure)
if (kind === 'gender') {
const out = (await remote.cfText('You know first names from all countries and cultures. Is the given first name usually a woman\'s name or a man\'s name? Reply with exactly one word: woman, man, or unsure (for names used for both, or names you do not know).', text.slice(0, 40), { maxTokens: 5 })).toLowerCase();
return /\bwoman\b/.test(out) ? 'woman' : /\bman\b/.test(out) ? 'man' : 'unsure';
}
// ✨ Another idea: one photo for a post or a portrait, described for the picture model (no text in it)
if (kind === 'picture') {
const out = await remote.cfText('You are an art director for small business social media. From the topic and the brand facts, describe ONE realistic photo for a post in 20 to 35 words: the subject, where it is, the light, the camera angle and the mood. Leave calm space for a headline. No text, letters, logos or signs in the picture. Reply with the description only, as one sentence, no quotes.', text, { maxTokens: 120 });
if (refused(out)) throw new Error('declined');
const line = out.split('\n').map(x => x.replace(/^["“]|["”]$/g, '').trim()).find(x => x.length > 15);
if (!line) throw new Error('offline');
return line.slice(0, 400);
}
throw new Error('bad kind');
});
// Plan: read and write the whole plan (the renderer owns its shape; main only bounds its size).
// slot "demo" is the worked example (plan-demo.json), kept apart from the person's own plan.
const planFile = slot => slot === 'demo' ? path.join(DATA, 'plan-demo.json') : PLAN;
ipcMain.handle('plan:get', async (_e, slot) => { try { return JSON.parse(await fsp.readFile(planFile(slot), 'utf8')); } catch { return {}; } });
ipcMain.handle('plan:set', async (_e, plan, slot) => {
const text = JSON.stringify(plan && typeof plan === 'object' ? plan : {});
if (text.length > 4e6) throw new Error('The plan is too big to save.');
await fsp.mkdir(DATA, { recursive: true });
const f = planFile(slot);
await fsp.writeFile(`${f}.tmp`, text); await fsp.rename(`${f}.tmp`, f);
return true;
});
// The demo: pictures for the café Bean & Bloom, bundled in renderer/demo, installed as ordinary pictures (marked demo)
const DEMO = [
['latte', 'Latte with heart latte art on a wooden table, warm morning light', 512, 640, null],
['cakes', 'Homemade cakes on a wooden café counter, warm light', 512, 640, { title: 'Autumn Cake Week', sub: 'A new homemade cake every day', details: 'Free cake with your second coffee', cta: 'Visit us today', layout: 'band', font: 'serif', accent: '#7b4a2a', format: 'insta' }],
['carousel', 'Café pictures for a tips carousel', 512, 640, { carousel: true, title: '3 ways to enjoy your coffee break', sub: 'Bean & Bloom', slides: ['3 ways to enjoy your coffee break', 'Slow down: sit, sip, look out of the window', 'Pair it right: latte with carrot cake', 'Bring a friend: second coffee, free cake'], cta: 'Visit us today', layout: 'card', font: 'serif', accent: '#7b4a2a', format: 'insta' }, ['latte', 'barista', 'interior', 'cakes']],
['interior', 'Cosy small café interior with plants and morning sunlight', 640, 368, null],
['sofia', 'Portrait of Sofia, 34, remote designer', 512, 512, null],
['jean', 'Portrait of Jean, 67, retired teacher', 512, 512, null],
];
const DEMO_FOLDER = 'Ora demo - Bean & Bloom';
ipcMain.handle('demo:install', async () => {
const src = path.join(__dirname, 'renderer', 'demo');
const out = {};
const picDir = path.join(PIC_DIR, DEMO_FOLDER);
for (const [i, [name, prompt, w, h, posterSpec, files]] of DEMO.entries()) {
const id = `demo-${name}`, dir = path.join(PICS, id);
out[name] = id;
if (fs.existsSync(path.join(dir, 'meta.json'))) continue;
await fsp.mkdir(dir, { recursive: true }); await fsp.mkdir(picDir, { recursive: true });
const list = files || [name], images = [], saved = [];
for (const [k, f] of list.entries()) {
const file = `img_${String(k).padStart(2, '0')}.jpg`;
// read + write (not copyFile): the source is inside app.asar in the packaged app
const bytes = await fsp.readFile(path.join(src, `${f}.jpg`));
await fsp.writeFile(path.join(dir, file), bytes);
const copy = path.join(picDir, `${String(i + 1).padStart(2, '0')} ${name}${list.length > 1 ? ` ${k + 1}` : ''}.jpg`);
await fsp.writeFile(copy, bytes);
images.push(file); saved.push(copy);
}
const meta = { id, kind: 'image', demo: true, created: new Date(Date.UTC(2026, 0, 5 + i)).toISOString(), status: 'done', prompt, model: 'zimage', modelLabel: 'Z-Image-Turbo (demo)',
images, savedFiles: saved, savedTo: saved[0], width: w, height: h, count: images.length,
project: { folder: DEMO_FOLDER, index: i + 1, total: DEMO.length, title: prompt.split(',')[0] }, poster: posterSpec || undefined };
await writeMeta(dir, meta);
}
return out;
});
// Remove the demo: its pictures, the copies in Pictures/Ora and the demo plan (never the person's own work)
ipcMain.handle('demo:remove', async () => {
let n = 0;
for (const d of await fsp.readdir(PICS).catch(() => [])) {
if (!/^demo-[a-z]+$/.test(d)) continue;
const meta = JSON.parse(await fsp.readFile(path.join(PICS, d, 'meta.json'), 'utf8').catch(() => '{}'));
if (!meta.demo) continue;
await fsp.rm(path.join(PICS, d), { recursive: true, force: true }); n++;
}
await fsp.rm(path.join(PIC_DIR, DEMO_FOLDER), { recursive: true, force: true });
await fsp.rm(path.join(DATA, 'plan-demo.json'), { force: true });
return n;
});
// AI drafts, coaching and insights (Cloudflare, the 70B model). Answers are JSON; main checks and trims them.
const PERSONALITY = ['Friendly', 'Premium', 'Playful', 'Bold', 'Calm', 'Expert', 'Warm', 'Modern', 'Natural', 'Trustworthy', 'Creative', 'Energetic'];
const ONLINE = ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'YouTube', 'Google', 'Email', 'WhatsApp'];
const CHANNELS = ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'Google Business', 'Website', 'Email', 'Paid ads'];
const PRESENCE = ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'YouTube', 'Website', 'Google Business profile', 'Email newsletter', 'WhatsApp'];
const COMP_WHERE = ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'YouTube', 'Website', 'Google'];
const jsonOf = t => { const m = String(t).match(/[[{][\s\S]*[\]}]/); if (!m) throw new Error('unreadable'); try { return JSON.parse(m[0]); } catch { throw new Error('unreadable'); } };
const str = (v, n) => typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, n) : '';
const pick = (arr, allowed, n) => (Array.isArray(arr) ? arr : []).map(x => allowed.find(a => a.toLowerCase() === String(x).toLowerCase())).filter(Boolean).filter((x, i, a) => a.indexOf(x) === i).slice(0, n);
const AI_TASKS = {
brand: [`You are a marketing coach helping a beginner define a small business brand. From the facts, draft the brand identity. Reply with JSON only: {"mission": one sentence of 15-30 words saying who the brand serves, what it does and why, "values": 3 to 4 comma-separated words, "personality": 3 items chosen only from ${JSON.stringify(PERSONALITY)}, "tone": a short description of the tone of voice, "tagline": at most 7 words}. Use only the facts given; do not invent prices or awards.`, 500,
o => ({ mission: str(o.mission, 400), values: str(Array.isArray(o.values) ? o.values.join(', ') : o.values, 160), personality: pick(o.personality, PERSONALITY, 3), tone: str(o.tone, 160), tagline: str(o.tagline, 80) })],
personas: [`You are a marketing coach. From the brand facts, write two different customer personas a beginner can use. Reply with JSON only: {"personas": an array of 2 objects {"name": a first name, "gender": "woman" or "man", matching the first name, "age": a number as text, "job": job or situation (max 8 words), "needs": max 20 words, "pains": frustrations, max 20 words, "motivations": what makes them choose a brand, max 15 words, "where": 2 or 3 items chosen only from ${JSON.stringify(ONLINE)}, "quote": a short sentence in their words}}. Make them realistic for the brand's place and offer.`, 700,
o => (Array.isArray(o) ? o : o.personas || []).slice(0, 2).map(p => ({ name: str(p.name, 40), gender: ['woman', 'man'].includes(String(p.gender).toLowerCase()) ? String(p.gender).toLowerCase() : '', age: str(String(p.age || ''), 20), job: str(p.job, 80), needs: str(p.needs, 300), pains: str(p.pains, 300), motivations: str(p.motivations, 200), where: pick(p.where, ONLINE, 4), quote: str(p.quote, 140).replace(/^["“]|["”]$/g, '') }))],
campaign: [`You are a marketing coach helping a beginner plan one campaign for a small business. From the facts, draft it. Reply with JSON only: {"name": at most 4 words, "goal": one of "awareness","engagement","leads","sales","visits", "message": one sentence of at most 14 words, "value": why choose this brand, max 15 words, "offer": a simple offer or "", "cta": a call to action of at most 4 words, "channels": 2 or 3 items chosen only from ${JSON.stringify(CHANNELS)}, "funnel": {"awareness": one sentence, "engagement": one sentence, "conversion": one sentence} each describing one concrete piece of content for that step, "metrics": exactly 3 objects {"id": one of "reach","impressions","er","followers","clicks", "target": a realistic number for a small local business in one month (er is a percentage)}}. Use only the facts given.`, 700,
o => ({ name: str(o.name, 70), goal: ['awareness', 'engagement', 'leads', 'sales', 'visits'].includes(o.goal) ? o.goal : 'awareness', message: str(o.message, 200), value: str(o.value, 160), offer: str(o.offer, 80), cta: str(o.cta, 40), channels: pick(o.channels, CHANNELS, 4),
funnel: Object.fromEntries(['awareness', 'engagement', 'conversion'].map(k => [k, { what: str((o.funnel || {})[k], 300) }])),
metrics: (Array.isArray(o.metrics) ? o.metrics : []).filter(m => ['reach', 'impressions', 'er', 'followers', 'clicks'].includes(m.id)).slice(0, 3).map(m => ({ id: m.id, target: String(Math.max(0, +m.target || 0) || '') })) })],
market: [`You are a marketing coach helping a small business choose where to be online. From the facts (brand, customers and the competitors they listed), reply with JSON only: {"presence": 2 to 4 objects {"channel": one of ${JSON.stringify(PRESENCE)}, "purpose": what this channel is for, max 14 words, "freq": how often to post or update, max 6 words}, "competitors": 2 objects for the KINDS of competitor this business really faces {"name": the kind, described generically (for example "Large padel club chain" or "Family restaurant nearby"), never the name of a real business, "where": 1 to 3 items chosen only from ${JSON.stringify(COMP_WHERE)}, "works": what usually works on social media for that kind of competitor, max 20 words, "position": how that kind usually presents itself and what it misses, max 20 words}, "difference": one or two sentences (max 40 words) on how this brand can stand out from the competitors (the listed ones when there are any)}. Never invent facts about a named, real competitor; use only what is given about them.`, 800,
o => ({ competitors: (Array.isArray(o.competitors) ? o.competitors : []).slice(0, 3).map(c => ({ name: str(c.name, 60), where: pick(c.where, COMP_WHERE, 3), works: str(c.works, 300), position: str(c.position, 300) })).filter(c => c.name), presence: (Array.isArray(o.presence) ? o.presence : []).map(x => ({ channel: PRESENCE.find(c => c.toLowerCase() === String(x.channel || '').toLowerCase()), purpose: str(x.purpose, 160), freq: str(x.freq, 60) })).filter(x => x.channel).slice(0, 5), difference: str(o.difference, 400) })],
insights: [`You are a social media analyst explaining results to a small business owner. From the numbers given (per post and per kind of content), reply with JSON only: {"headline": one sentence with the most important finding, "insights": 2 or 3 short findings that quote the numbers, "actions": 2 or 3 concrete things to do next month (each max 20 words)}. Base everything on the numbers; do not invent data.`, 500,
o => ({ headline: str(o.headline, 240), insights: (Array.isArray(o.insights) ? o.insights : []).map(x => str(x, 220)).filter(Boolean).slice(0, 3), actions: (Array.isArray(o.actions) ? o.actions : []).map(x => str(x, 200)).filter(Boolean).slice(0, 3) })],
coach: [`You are a friendly, honest marketing trainer giving feedback to a beginner on one exercise of a digital marketing course. Judge the work against the criteria given. Reply with JSON only: {"good": one sentence on what is already good, "improve": 2 or 3 short, concrete suggestions (each max 25 words, quoting the part to change), "score": a whole number from 1 to 5}. Be specific to their words; no generic advice.`, 450,
o => ({ good: str(o.good, 300), improve: (Array.isArray(o.improve) ? o.improve : [o.improve]).map(x => str(x, 220)).filter(Boolean).slice(0, 3), score: Math.max(1, Math.min(5, Math.round(+o.score) || 3)) })],
};
ipcMain.handle('plan:ai', async (_e, task, facts) => {
const t = AI_TASKS[task];
if (!t) throw new Error('bad task');
if (!remote.status().cloudflare.connected) throw new Error('offline');
const text = String(facts || '').slice(0, 6000);
if (text.trim().length < 3) throw new Error('Fill in the basics first.');
// drafts read like a real small business wrote them: full sentences inside the word ranges, never a few keywords
const style = ['brand', 'campaign', 'market', 'insights'].includes(task) ? ' Write complete, specific, natural sentences that name the brand, its product and its place where it fits; stay inside the word ranges given (not shorter); never answer with a few keywords.' : '';
// a free answer first (fuller writing); if it is not valid JSON, once more in Workers AI's JSON mode
for (const json of [false, true]) {
const raw = await remote.cfText(t[0] + style + (json ? ' Your whole reply must be valid JSON: every key and every text value in double quotes, nothing before or after it.' : ''), text, { big: true, maxTokens: t[1], json });
if (process.env.PLAN_SMOKE) fs.appendFileSync(path.join(process.env.PLAN_SMOKE, 'ai-raw.txt'), `--- ${task}\n${raw.slice(0, 1200)}\n`);
if (refused(raw)) throw new Error('declined');
try { return t[2](jsonOf(raw)); } catch (e) { if (json) throw e; }
}
});
// exports (Brand Identity Summary, presentation, calendar, results, the plan file) go to Documents/Ora
async function uniqueDoc(name, ext, max = 60) {
await fsp.mkdir(DOC_DIR, { recursive: true });
const base = core.folderName(String(name || 'Ora'), max);
let target = path.join(DOC_DIR, `${base}.${ext}`), n = 2;
while (fs.existsSync(target)) target = path.join(DOC_DIR, `${base} ${n++}.${ext}`);
return target;
}
ipcMain.handle('plan:export', async (_e, name, bytes, ext) => {
if (!['png', 'csv', 'ics', 'json', 'pptx'].includes(ext) || !bytes || bytes.byteLength > 80e6) throw new Error('bad export');
const target = await uniqueDoc(name, ext);
await fsp.writeFile(target, Buffer.from(bytes));
if (!process.env.PLAN_SMOKE) shell.showItemInFolder(target);
return target;
});
// PDF pages: the renderer builds them as HTML; a hidden window prints them (A4, or 16:9 slides)
ipcMain.handle('plan:pdf', async (_e, name, html, page) => {
if (typeof html !== 'string' || html.length > 8e6) throw new Error('bad slides');
const tmp = path.join(app.getPath('temp'), `ora-plan-${Date.now()}.html`);
await fsp.writeFile(tmp, html);
const a4 = page === 'a4';
const w = new BrowserWindow({ show: false, width: a4 ? 794 : 1280, height: a4 ? 1123 : 720, webPreferences: { sandbox: true, contextIsolation: true, javascript: false } });
try {
await w.loadFile(tmp);
await new Promise(r => setTimeout(r, 600)); // pictures (ora://) finish loading
const pdf = await w.webContents.printToPDF({ pageSize: a4 ? 'A4' : { width: 13.333, height: 7.5 }, printBackground: true, margins: { marginType: 'none' } });
const target = await uniqueDoc(name || 'Ora presentation', 'pdf');
await fsp.writeFile(target, pdf);
if (!process.env.PLAN_SMOKE) shell.showItemInFolder(target);
return target;
} finally { w.destroy(); fsp.rm(tmp, { force: true }).catch(() => { }); }
});
// Captions: one per platform, in the brand's tone (Cloudflare's text model; the renderer has an offline fallback)
const PLATFORM_RULES = {
instagram: 'Instagram: a strong first line (hook), 2 to 4 short lines, 1 to 3 fitting emojis, a clear call to action, then 8 to 12 relevant hashtags on the last line.',
facebook: 'Facebook: friendly and conversational, 2 to 4 sentences, at most 2 emojis, a clear call to action, at most 3 hashtags.',
linkedin: 'LinkedIn: professional and useful, a first line that earns the click, 3 to 5 short sentences or a short list, no more than 1 emoji, a clear call to action, 3 to 5 hashtags at the end.',
};
ipcMain.handle('caption:write', async (_e, ctx, platform) => {
if (!PLATFORM_RULES[platform]) throw new Error('Pick a platform.');
if (!remote.status().cloudflare.connected) throw new Error('offline');
const c = ctx && typeof ctx === 'object' ? ctx : {};
const s = (v, n) => typeof v === 'string' ? v.trim().slice(0, n) : '';
const facts = [
['What the post shows', s(c.about, 600)], ['Headline', s(c.title, 120)], ['Offer', s(c.offer, 120)],
['Call to action', s(c.cta, 60)], ['Brand', s(c.brand, 60)], ['Brand tone and words', s(c.tone, 200)], ['Audience', s(c.audience, 200)],
].filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`).join('\n');
if (!facts) throw new Error('Nothing to write about yet.');
const system = `You write social media captions for small businesses. ${PLATFORM_RULES[platform]} Use only the facts given; do not invent prices, dates, numbers or claims. Write in English. Reply with the caption only, no preface, no quotes.`;
const out = await remote.cfText(system, facts);
if (refused(out) || out.length < 10) throw new Error('declined');
return out.replace(/^["“]|["”]$/g, '').trim().slice(0, 2200);
});
// --- updates: the newest Ora on Hugging Face (Devseis/ora-releases, folder releases/: Ora 0.5 and later; the root
// keeps Ora 0.1–0.4, the video app, which reads its own latest.json there). The file is checked against the
// published SHA256SUMS; Ora then closes, a small script swaps the new version in where this one is (keeping the old
// one until the new one is in place) and opens it again.
const RELEASES = 'https://huggingface.co/datasets/Devseis/ora-releases/resolve/main/releases';
const newer = (a, b) => { const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number); for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0); return false; };
async function latestRelease() {
const r = await net.fetch(`${RELEASES}/latest.json?t=${Date.now()}`, { cache: 'no-store' });
if (!r.ok) throw new Error('Could not reach Hugging Face to look for updates.');
return r.json();
}
const updateFile = l => (process.platform === 'darwin' ? l.files.mac : process.platform === 'win32' ? l.files.windows : process.env.APPIMAGE ? l.files.linux_appimage : l.files.linux_deb);
ipcMain.handle('update:check', async () => {
const l = await latestRelease();
return { current: app.getVersion(), latest: l.version, date: l.date, available: newer(l.version, app.getVersion()), canInstall: app.isPackaged && !!(updateFile(l) || {}).file, bytes: (updateFile(l) || {}).bytes };
});
let updating = false;
ipcMain.handle('update:install', async () => {
if (updating) throw new Error('The update is already on its way.');
if (job) throw new Error('Pictures are being made: update when they are finished.');
if (!app.isPackaged) throw new Error('Updates work in the installed Ora, not in the development version.');
const l = await latestRelease();
if (!newer(l.version, app.getVersion())) throw new Error(`Ora ${app.getVersion()} is already the newest version.`);
const f = updateFile(l);
if (!f || !/^Ora-[\w.-]+$/.test(f.file)) throw new Error('No update for this system.');
updating = true;
try {
const sums = await (await net.fetch(`${RELEASES}/SHA256SUMS?t=${Date.now()}`, { cache: 'no-store' })).text();
const want = (sums.split('\n').map(x => x.trim().split(/\s+/)).find(x => x[1] === f.file) || [])[0];
if (!want) throw new Error('The update is not in the published checksums.');
const tmp = await fsp.mkdtemp(path.join(os.tmpdir(), 'ora-update-'));
const file = path.join(tmp, f.file);
// download with progress, hashing as it arrives
const res = await net.fetch(`${RELEASES}/${f.file}`);
if (!res.ok || !res.body) throw new Error('The download failed.');
const total = +res.headers.get('content-length') || f.bytes || 0, hash = crypto.createHash('sha256'), out = fs.createWriteStream(file);
let done = 0, last = 0;
const reader = res.body.getReader();
for (;;) {
const { value, done: end } = await reader.read();
if (end) break;
hash.update(value); done += value.length;
if (!out.write(value)) await new Promise(r => out.once('drain', r));
if (Date.now() - last > 300) { last = Date.now(); send('update:progress', { done, total }); }
}
await new Promise((r, j) => out.end(e => (e ? j(e) : r())));
if (hash.digest('hex') !== want) throw new Error('The download does not match the published checksum. Nothing was changed.');
send('update:progress', { done: total, total, installing: true });
const sh = body => { const sp = path.join(tmp, 'apply.sh'); fs.writeFileSync(sp, `#!/bin/bash\n${body}\n`, { mode: 0o755 }); return sp; };
const q = v => `'${String(v).replace(/'/g, `'\\''`)}'`;
if (process.platform === 'darwin') {
const bundle = path.resolve(app.getPath('exe'), '..', '..', '..'); // …/Ora.app
if (!bundle.endsWith('.app')) throw new Error('Ora could not find where it is installed.');
try { fs.accessSync(path.dirname(bundle), fs.constants.W_OK); } catch { throw new Error(`Ora cannot write to ${path.dirname(bundle)}. Download the new version from the Ora page instead.`); }
await new Promise((r, j) => spawn('ditto', ['-x', '-k', file, path.join(tmp, 'x')]).on('exit', c => (c === 0 ? r() : j(new Error('Could not unpack the update.')))));
const fresh = [path.join(tmp, 'x', 'Ora.app'), path.join(tmp, 'x', 'Ora', 'Ora.app')].find(p => fs.existsSync(p));
if (!fresh) throw new Error('Ora.app was not found in the update.');
spawn('/bin/bash', [sh(`while kill -0 ${process.pid} 2>/dev/null; do sleep 0.5; done
APP=${q(bundle)}; NEW=${q(fresh)}
rm -rf "$APP.old"; mv "$APP" "$APP.old" || exit 1
if ditto "$NEW" "$APP"; then rm -rf "$APP.old"; else rm -rf "$APP"; mv "$APP.old" "$APP"; fi
xattr -dr com.apple.quarantine "$APP" 2>/dev/null
open "$APP"; rm -rf ${q(tmp)}`)], { detached: true, stdio: 'ignore' }).unref();
} else if (process.platform === 'win32') {
// the NSIS setup, silent, opens Ora again when it is done (it waits a moment so this Ora has closed)
spawn('cmd.exe', ['/c', `timeout /t 3 /nobreak >nul & "${file}" /S --force-run`], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
} else if (process.env.APPIMAGE) {
spawn('/bin/bash', [sh(`while kill -0 ${process.pid} 2>/dev/null; do sleep 0.5; done
install -m 755 ${q(file)} ${q(process.env.APPIMAGE)} && (nohup ${q(process.env.APPIMAGE)} >/dev/null 2>&1 &); rm -rf ${q(tmp)}`)], { detached: true, stdio: 'ignore' }).unref();
} else {
spawn('/bin/bash', [sh(`while kill -0 ${process.pid} 2>/dev/null; do sleep 0.5; done
if command -v pkexec >/dev/null; then pkexec apt-get install -y ${q(file)} && (nohup /opt/Ora/ora >/dev/null 2>&1 &); else xdg-open ${q(file)}; fi`)], { detached: true, stdio: 'ignore' }).unref();
}
setTimeout(() => app.quit(), 400);
return { version: l.version };
} catch (e) { updating = false; throw e; }
});
createWindow();
});
app.on('window-all-closed', () => { if (job) job.cancelled = true; app.quit(); });