Compare commits
6 Commits
e165a41180
..
v1.0.7
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bc2e5bd49 | |||
| 2037144a5c | |||
| 1840227be6 | |||
| a15adfc3b1 | |||
| 82baef2b04 | |||
| e4b989c60f |
@@ -2,7 +2,7 @@
|
||||
#
|
||||
# Метки runs-on = labels твоих act_runner (Админка Gitea → Действия → Раннеры).
|
||||
# Не используем windows-latest/macos-latest — это только GitHub-hosted.
|
||||
# По умолчанию: одна Linux-сборка Win+NSIS (Wine). macOS — когда будет раннер (см. комментарий в build-macos).
|
||||
# По умолчанию: один job на ubuntu-22.04 — Win (Wine+NSIS), Linux AppImage (x64+arm64), sync в updates без затирания других ОС.
|
||||
#
|
||||
# Один job без actions/upload-artifact: официальный upload-artifact@v4 с GitHub на Gitea
|
||||
# падает (GHESNotSupportedError). Сборка и sync-update-feed идут в одном окружении.
|
||||
@@ -69,6 +69,58 @@ jobs:
|
||||
|
||||
- run: npm run build
|
||||
|
||||
# Linux AppImage (x64 + arm64) до подмешивания win32-sharp в node_modules.
|
||||
- name: Зависимости Linux AppImage и кросс-сборка arm64 на amd64
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
qemu-user-static \
|
||||
binfmt-support \
|
||||
desktop-file-utils \
|
||||
squashfs-tools
|
||||
|
||||
- name: electron-builder (linux AppImage x64, arm64)
|
||||
shell: bash
|
||||
env:
|
||||
DND_UPDATE_FEED_URL: ${{ secrets.DND_UPDATE_FEED_URL }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -z "${DND_UPDATE_FEED_URL:-}" ]]; then
|
||||
echo "Secret DND_UPDATE_FEED_URL is not set (URL со слэшем в конце)" >&2
|
||||
exit 1
|
||||
fi
|
||||
npx electron-builder --linux AppImage --x64 --arm64 --publish never \
|
||||
--config.publish.provider=generic \
|
||||
--config.publish.url="${DND_UPDATE_FEED_URL}"
|
||||
|
||||
- name: Каталог артефактов для feed (_linux)
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p _linux
|
||||
shopt -s nullglob || true
|
||||
for f in release/*; do
|
||||
[[ -f "$f" ]] || continue
|
||||
base=$(basename "$f")
|
||||
case "$base" in
|
||||
latest-linux.yml|*.yaml|*.AppImage|*.appimage|*.blockmap) cp -v "$f" _linux/ ;;
|
||||
esac
|
||||
done
|
||||
ls -la _linux
|
||||
|
||||
# Не используем `npm install`: на Linux npm падает с EBADPLATFORM для win32-пакета.
|
||||
- name: sharp (@img/sharp-win32-x64) для Windows-артефакта при сборке на Linux
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tmp="$(mktemp -d)"
|
||||
npm pack @img/sharp-win32-x64@0.34.5 --pack-destination "$tmp"
|
||||
mkdir -p node_modules/@img/sharp-win32-x64
|
||||
tar -xzf "$tmp/img-sharp-win32-x64-0.34.5.tgz" -C "$tmp"
|
||||
cp -a "$tmp/package/." node_modules/@img/sharp-win32-x64/
|
||||
test -f node_modules/@img/sharp-win32-x64/lib/sharp-win32-x64.node
|
||||
rm -rf "$tmp"
|
||||
|
||||
- name: electron-builder (win)
|
||||
shell: bash
|
||||
env:
|
||||
@@ -107,6 +159,7 @@ jobs:
|
||||
DND_UPDATES_PUSH_TOKEN: ${{ secrets.DND_UPDATES_PUSH_TOKEN }}
|
||||
ARTIFACT_WIN: ${{ github.workspace }}/_win
|
||||
ARTIFACT_MAC: ${{ github.workspace }}/_mac
|
||||
ARTIFACT_LINUX: ${{ github.workspace }}/_linux
|
||||
GIT_COMMIT_TAG: ${{ github.ref_name }}
|
||||
run: node scripts/sync-update-feed.mjs
|
||||
|
||||
|
||||
+2
-1
@@ -252,6 +252,7 @@ async function main() {
|
||||
registerHandler(ipcChannels.app.getVersion, () => ({
|
||||
version: getAppSemanticVersion(),
|
||||
buildNumber: getOptionalBuildNumber(),
|
||||
packaged: app.isPackaged,
|
||||
}));
|
||||
registerHandler(ipcChannels.license.getStatus, () => licenseService.getStatus());
|
||||
registerHandler(ipcChannels.license.setToken, async ({ token }) => licenseService.setToken(token));
|
||||
@@ -526,9 +527,9 @@ async function main() {
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
installAutoUpdater(licenseService, registerHandler);
|
||||
installIpcRouter();
|
||||
applyDockIconIfNeeded();
|
||||
installAutoUpdater(licenseService);
|
||||
await runStartupAfterHandlers(licenseService);
|
||||
|
||||
app.on('activate', () => {
|
||||
|
||||
@@ -36,6 +36,8 @@ export function registerHandler<K extends keyof IpcInvokeMap>(channel: K, handle
|
||||
handlers.set(channelStr, inner);
|
||||
}
|
||||
|
||||
export type IpcRegisterHandler = typeof registerHandler;
|
||||
|
||||
export function installIpcRouter(): void {
|
||||
for (const [channel, handler] of handlers.entries()) {
|
||||
ipcMain.handle(channel, async (_event, payload: unknown) => handler(payload));
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { app, dialog } from 'electron';
|
||||
import { autoUpdater } from 'electron-updater';
|
||||
|
||||
import {
|
||||
ipcChannels,
|
||||
type UpdaterCheckResponse,
|
||||
type UpdaterDownloadResponse,
|
||||
} from '../../shared/ipc/contracts';
|
||||
import type { IpcRegisterHandler } from '../ipc/router';
|
||||
import { addLicenseChangeListener } from '../license/licenseService';
|
||||
import type { LicenseService } from '../license/licenseService';
|
||||
|
||||
@@ -9,6 +15,10 @@ const STARTUP_CHECK_DELAY_MS = 12_000;
|
||||
const RE_CHECK_COOLDOWN_MS = 30_000;
|
||||
|
||||
let lastCheckAt = 0;
|
||||
/** Ручная установка: не показывать второй диалог из `update-downloaded`. */
|
||||
let suppressAutoInstallDialog = false;
|
||||
|
||||
type RegisterFn = IpcRegisterHandler;
|
||||
|
||||
function isLicensedForUpdates(licenseService: LicenseService): boolean {
|
||||
const snap = licenseService.getStatusSync();
|
||||
@@ -24,11 +34,53 @@ function maybeCheckForUpdates(licenseService: LicenseService, ignoreCooldown: bo
|
||||
void autoUpdater.checkForUpdates().catch(() => undefined);
|
||||
}
|
||||
|
||||
async function runManualUpdaterCheck(licenseService: LicenseService): Promise<UpdaterCheckResponse> {
|
||||
if (!app.isPackaged) {
|
||||
return { outcome: 'not_packaged' };
|
||||
}
|
||||
if (!isLicensedForUpdates(licenseService)) {
|
||||
return { outcome: 'no_license' };
|
||||
}
|
||||
try {
|
||||
const result = await autoUpdater.checkForUpdates();
|
||||
if (result && result.isUpdateAvailable && result.updateInfo.version) {
|
||||
return { outcome: 'available', version: result.updateInfo.version };
|
||||
}
|
||||
return { outcome: 'current', currentVersion: app.getVersion() };
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
return { outcome: 'error', message };
|
||||
}
|
||||
}
|
||||
|
||||
async function runManualDownloadAndRestart(): Promise<UpdaterDownloadResponse> {
|
||||
if (!app.isPackaged) {
|
||||
return { ok: false, message: 'NOT_PACKAGED' };
|
||||
}
|
||||
try {
|
||||
suppressAutoInstallDialog = true;
|
||||
await autoUpdater.downloadUpdate();
|
||||
autoUpdater.quitAndInstall(false, true);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
suppressAutoInstallDialog = false;
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
return { ok: false, message };
|
||||
}
|
||||
}
|
||||
|
||||
function registerUpdaterHandlers(register: RegisterFn, licenseService: LicenseService): void {
|
||||
register(ipcChannels.updater.check, () => runManualUpdaterCheck(licenseService));
|
||||
register(ipcChannels.updater.downloadAndRestart, () => runManualDownloadAndRestart());
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка обновлений: только упакованное приложение, только при активной лицензии.
|
||||
* Канал и URL задаются при сборке (`publish` → `app-update.yml` внутри установки).
|
||||
*/
|
||||
export function installAutoUpdater(licenseService: LicenseService): void {
|
||||
export function installAutoUpdater(licenseService: LicenseService, register: RegisterFn): void {
|
||||
registerUpdaterHandlers(register, licenseService);
|
||||
|
||||
if (!app.isPackaged) return;
|
||||
|
||||
const feedOverride = process.env.DND_UPDATE_FEED_URL?.trim();
|
||||
@@ -41,6 +93,10 @@ export function installAutoUpdater(licenseService: LicenseService): void {
|
||||
autoUpdater.autoInstallOnAppQuit = true;
|
||||
|
||||
autoUpdater.on('update-downloaded', (info) => {
|
||||
if (suppressAutoInstallDialog) {
|
||||
suppressAutoInstallDialog = false;
|
||||
return;
|
||||
}
|
||||
void dialog
|
||||
.showMessageBox({
|
||||
type: 'info',
|
||||
|
||||
@@ -4,6 +4,8 @@ import { app, BrowserWindow } from 'electron';
|
||||
|
||||
import { getAppSemanticVersion } from '../versionInfo';
|
||||
|
||||
import { loadBrandingWindowIcon } from './brandingIcon';
|
||||
|
||||
let bootSplashRef: BrowserWindow | null = null;
|
||||
|
||||
export function getBootSplashWindow(): BrowserWindow | null {
|
||||
@@ -37,6 +39,7 @@ function bootWebPreferences(): Electron.WebPreferences {
|
||||
* Показывать после `waitForBootWindowReady`.
|
||||
*/
|
||||
export function createBootWindow(): BrowserWindow {
|
||||
const icon = loadBrandingWindowIcon();
|
||||
const win = new BrowserWindow({
|
||||
width: 440,
|
||||
height: 420,
|
||||
@@ -50,8 +53,16 @@ export function createBootWindow(): BrowserWindow {
|
||||
transparent: false,
|
||||
backgroundColor: '#09090B',
|
||||
roundedCorners: true,
|
||||
...(icon ? { icon } : {}),
|
||||
webPreferences: bootWebPreferences(),
|
||||
});
|
||||
if (icon) {
|
||||
try {
|
||||
win.setIcon(icon);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
bootSplashRef = win;
|
||||
win.once('closed', () => {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { app, nativeImage } from 'electron';
|
||||
|
||||
let resolved = false;
|
||||
let cached: Electron.NativeImage | undefined;
|
||||
|
||||
/** ICO рядом с exe (вне asar): надёжно для `nativeImage` / панели задач на Windows. */
|
||||
function getPackagedBrandingIcoPath(): string | undefined {
|
||||
if (!app.isPackaged) return undefined;
|
||||
const p = path.join(process.resourcesPath, 'branding', 'icon.ico');
|
||||
try {
|
||||
if (fs.existsSync(p)) return p;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function brandingPngPaths(): string[] {
|
||||
const root = app.getAppPath();
|
||||
const relPack = path.join('dist', 'renderer', 'app-pack-icon.png');
|
||||
const relWindow = path.join('dist', 'renderer', 'app-window-icon.png');
|
||||
const paths: string[] = [];
|
||||
if (app.isPackaged) {
|
||||
const unpacked = path.join(process.resourcesPath, 'app.asar.unpacked');
|
||||
paths.push(path.join(unpacked, relPack), path.join(unpacked, relWindow));
|
||||
}
|
||||
paths.push(
|
||||
path.join(root, relPack),
|
||||
path.join(root, relWindow),
|
||||
path.join(root, 'build', 'icon.png'),
|
||||
path.join(root, 'app', 'renderer', 'public', 'app-window-icon.png'),
|
||||
);
|
||||
return paths;
|
||||
}
|
||||
|
||||
function tryLoadImageFile(filePath: string): Electron.NativeImage | undefined {
|
||||
try {
|
||||
const buf = fs.readFileSync(filePath);
|
||||
const fromBuf = nativeImage.createFromBuffer(buf);
|
||||
if (!fromBuf.isEmpty()) return fromBuf;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
const fromPath = nativeImage.createFromPath(filePath);
|
||||
if (!fromPath.isEmpty()) return fromPath;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function tryLoadSvgFile(filePath: string): Electron.NativeImage | undefined {
|
||||
try {
|
||||
const fromPath = nativeImage.createFromPath(filePath);
|
||||
if (!fromPath.isEmpty()) return fromPath;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function tryDarwinSvgPaths(): Electron.NativeImage | undefined {
|
||||
if (process.platform !== 'darwin') return undefined;
|
||||
const root = app.getAppPath();
|
||||
for (const p of [
|
||||
path.join(root, 'dist', 'renderer', 'app-logo.svg'),
|
||||
path.join(root, 'app', 'renderer', 'public', 'app-logo.svg'),
|
||||
]) {
|
||||
if (!fs.existsSync(p)) continue;
|
||||
const img = tryLoadSvgFile(p);
|
||||
if (img) return img;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Иконка окна / дока. Сначала ICO из `extraResources` (реальный путь на диске), затем PNG
|
||||
* через буфер — `createFromPath` к файлам внутри `app.asar` на Windows часто даёт пустой `NativeImage`.
|
||||
*/
|
||||
export function loadBrandingWindowIcon(): Electron.NativeImage | undefined {
|
||||
if (resolved) return cached;
|
||||
resolved = true;
|
||||
|
||||
const ico = getPackagedBrandingIcoPath();
|
||||
if (ico) {
|
||||
const img = tryLoadImageFile(ico);
|
||||
if (img) {
|
||||
cached = img;
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
for (const p of brandingPngPaths()) {
|
||||
if (!fs.existsSync(p)) continue;
|
||||
const img = tryLoadImageFile(p);
|
||||
if (img) {
|
||||
cached = img;
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
const svgIcon = tryDarwinSvgPaths();
|
||||
if (svgIcon) {
|
||||
cached = svgIcon;
|
||||
return cached;
|
||||
}
|
||||
|
||||
cached = undefined;
|
||||
return undefined;
|
||||
}
|
||||
@@ -22,10 +22,11 @@ void test('createWindows: закрытие редактора завершает
|
||||
|
||||
void test('createWindows: иконка окна (pack PNG, затем window PNG; SVG только вне win32)', () => {
|
||||
const src = readCreateWindows();
|
||||
assert.ok(src.includes('resolveWindowIconPath'));
|
||||
assert.ok(src.includes('app-pack-icon.png'));
|
||||
assert.ok(src.includes('app-window-icon.png'));
|
||||
assert.ok(src.includes('app-logo.svg'));
|
||||
assert.ok(src.includes('loadBrandingWindowIcon'));
|
||||
const branding = fs.readFileSync(path.join(here, 'brandingIcon.ts'), 'utf8');
|
||||
assert.ok(branding.includes('app-pack-icon.png'));
|
||||
assert.ok(branding.includes('app-window-icon.png'));
|
||||
assert.ok(branding.includes('tryDarwinSvgPaths'));
|
||||
});
|
||||
|
||||
void test('createWindows: пульт поверх экрана просмотра (дочернее окно)', () => {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { app, BrowserWindow, nativeImage, screen } from 'electron';
|
||||
import { app, BrowserWindow, screen } from 'electron';
|
||||
|
||||
import { ipcChannels } from '../../shared/ipc/contracts';
|
||||
|
||||
import { getBootSplashWindow } from './bootWindow';
|
||||
import { loadBrandingWindowIcon } from './brandingIcon';
|
||||
|
||||
type WindowKind = 'editor' | 'presentation' | 'control';
|
||||
|
||||
@@ -69,82 +69,15 @@ function getPreloadPath(): string {
|
||||
return path.join(app.getAppPath(), 'dist', 'preload', 'index.cjs');
|
||||
}
|
||||
|
||||
/**
|
||||
* PNG для иконки окна / дока: тот же растр, что electron-builder берёт из `build/icon.png`
|
||||
* (копия в dist после сборки), затем окно 256px, затем dev-пути. SVG не используем для
|
||||
* nativeImage на Windows — иначе пустая картинка и дефолтная иконка Electron вместо exe.
|
||||
*/
|
||||
function resolveBrandingPngPaths(): string[] {
|
||||
const root = app.getAppPath();
|
||||
return [
|
||||
path.join(root, 'dist', 'renderer', 'app-pack-icon.png'),
|
||||
path.join(root, 'dist', 'renderer', 'app-window-icon.png'),
|
||||
path.join(root, 'build', 'icon.png'),
|
||||
path.join(root, 'app', 'renderer', 'public', 'app-window-icon.png'),
|
||||
];
|
||||
}
|
||||
|
||||
function resolveWindowIconPath(): string | undefined {
|
||||
for (const p of resolveBrandingPngPaths()) {
|
||||
try {
|
||||
if (fs.existsSync(p)) return p;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
const root = app.getAppPath();
|
||||
const svgFallback = [
|
||||
path.join(root, 'dist', 'renderer', 'app-logo.svg'),
|
||||
path.join(root, 'app', 'renderer', 'public', 'app-logo.svg'),
|
||||
];
|
||||
for (const p of svgFallback) {
|
||||
try {
|
||||
if (fs.existsSync(p)) return p;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveWindowIcon(): Electron.NativeImage | undefined {
|
||||
const tryPath = (filePath: string): Electron.NativeImage | undefined => {
|
||||
try {
|
||||
const img = nativeImage.createFromPath(filePath);
|
||||
if (!img.isEmpty()) return img;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
if (process.platform === 'win32' || process.platform === 'linux') {
|
||||
for (const p of resolveBrandingPngPaths()) {
|
||||
if (!fs.existsSync(p)) continue;
|
||||
const img = tryPath(p);
|
||||
if (img) return img;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const p = resolveWindowIconPath();
|
||||
if (!p) return undefined;
|
||||
return tryPath(p);
|
||||
}
|
||||
|
||||
/** macOS: в Dock показываем тот же PNG, что и у упакованного приложения на Windows (иконка exe). */
|
||||
/** macOS: в Dock — тот же растр, что и у окон (ICO/PNG из brandingIcon). */
|
||||
export function applyDockIconIfNeeded(): void {
|
||||
if (process.platform !== 'darwin' || !app.dock) return;
|
||||
for (const p of resolveBrandingPngPaths()) {
|
||||
if (!fs.existsSync(p)) continue;
|
||||
const icon = loadBrandingWindowIcon();
|
||||
if (!icon || icon.isEmpty()) return;
|
||||
try {
|
||||
const img = nativeImage.createFromPath(p);
|
||||
if (img.isEmpty()) continue;
|
||||
app.dock.setIcon(img);
|
||||
return;
|
||||
app.dock.setIcon(icon);
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,7 +113,7 @@ function ensureWindowBecomesVisible(win: BrowserWindow): void {
|
||||
|
||||
function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow {
|
||||
const deferEditor = kind === 'editor' && opts?.deferVisibility === true;
|
||||
const icon = resolveWindowIcon();
|
||||
const icon = loadBrandingWindowIcon();
|
||||
const win = new BrowserWindow({
|
||||
width: kind === 'editor' ? 1280 : kind === 'control' ? 1200 : 1280,
|
||||
height: 800,
|
||||
@@ -199,6 +132,13 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
|
||||
webSecurity: Boolean(process.env.VITE_DEV_SERVER_URL),
|
||||
},
|
||||
});
|
||||
if (icon) {
|
||||
try {
|
||||
win.setIcon(icon);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
win.webContents.on('preload-error', (_event, preloadPath, error) => {
|
||||
console.error(`[preload-error] ${preloadPath}:`, error);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { startTransition, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
import { ipcChannels } from '../../shared/ipc/contracts';
|
||||
import { ipcChannels, type UpdaterCheckResponse } from '../../shared/ipc/contracts';
|
||||
import { EULA_CURRENT_VERSION } from '../../shared/license/eulaVersion';
|
||||
import type { LicenseSnapshot } from '../../shared/license/licenseSnapshot';
|
||||
import type { AssetId, MediaAsset, Project, ProjectId, SceneAudioRef, SceneId } from '../../shared/types';
|
||||
@@ -76,6 +76,8 @@ export function EditorApp() {
|
||||
const [previewBusy, setPreviewBusy] = useState(false);
|
||||
const [presentationOpen, setPresentationOpen] = useState(false);
|
||||
const [licenseSnap, setLicenseSnap] = useState<LicenseSnapshot | null>(null);
|
||||
const [checkUpdatesOpen, setCheckUpdatesOpen] = useState(false);
|
||||
const [appPackaged, setAppPackaged] = useState(false);
|
||||
const [licenseKeyModalOpen, setLicenseKeyModalOpen] = useState(false);
|
||||
const [eulaModalOpen, setEulaModalOpen] = useState(false);
|
||||
const [aboutLicenseOpen, setAboutLicenseOpen] = useState(false);
|
||||
@@ -305,6 +307,7 @@ export function EditorApp() {
|
||||
const r = await getDndApi().invoke(ipcChannels.app.getVersion, {});
|
||||
const label = r.buildNumber ? `v${r.version} · ${r.buildNumber}` : `v${r.version}`;
|
||||
setAppVersionText(label);
|
||||
setAppPackaged(r.packaged);
|
||||
} catch {
|
||||
setAppVersionText(null);
|
||||
}
|
||||
@@ -647,6 +650,20 @@ export function EditorApp() {
|
||||
>
|
||||
{t('menu.aboutLicense')}
|
||||
</button>
|
||||
{licenseActive && appPackaged ? (
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={styles.fileMenuItem}
|
||||
onClick={() => {
|
||||
setSettingsMenuOpen(false);
|
||||
setSettingsLangSubOpen(false);
|
||||
setCheckUpdatesOpen(true);
|
||||
}}
|
||||
>
|
||||
{t('menu.checkUpdates')}
|
||||
</button>
|
||||
) : null}
|
||||
<div className={styles.fileMenuSubHost} role="presentation">
|
||||
<button
|
||||
type="button"
|
||||
@@ -819,6 +836,7 @@ export function EditorApp() {
|
||||
await actions.exportProject(projectId);
|
||||
}}
|
||||
/>
|
||||
<CheckUpdatesModal open={checkUpdatesOpen} onClose={() => setCheckUpdatesOpen(false)} />
|
||||
<SimpleMessageModal
|
||||
open={appNotice !== null}
|
||||
title={appNotice?.title ?? t('common.message')}
|
||||
@@ -941,6 +959,136 @@ function ExportProjectModal({
|
||||
);
|
||||
}
|
||||
|
||||
type CheckUpdatesModalProps = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
function CheckUpdatesModal({ open, onClose }: CheckUpdatesModalProps) {
|
||||
const { t } = useEditorI18n();
|
||||
const [phase, setPhase] = useState<'idle' | 'checking' | 'done'>('idle');
|
||||
const [res, setRes] = useState<UpdaterCheckResponse | null>(null);
|
||||
const [downloadBusy, setDownloadBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
startTransition(() => {
|
||||
setPhase('checking');
|
||||
setRes(null);
|
||||
});
|
||||
void getDndApi()
|
||||
.invoke(ipcChannels.updater.check, {})
|
||||
.then((r) => {
|
||||
setRes(r);
|
||||
setPhase('done');
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
setRes({ outcome: 'error', message });
|
||||
setPhase('done');
|
||||
});
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && !downloadBusy) onClose();
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [downloadBusy, onClose, open]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const body =
|
||||
phase === 'checking' || res === null ? (
|
||||
<div className={styles.muted}>{t('updates.checking')}</div>
|
||||
) : res.outcome === 'available' ? (
|
||||
<div className={styles.muted}>{t('updates.available', { version: res.version })}</div>
|
||||
) : res.outcome === 'current' ? (
|
||||
<div className={styles.muted}>{t('updates.current', { version: res.currentVersion })}</div>
|
||||
) : res.outcome === 'error' ? (
|
||||
<div className={styles.muted}>{t('updates.error', { message: res.message })}</div>
|
||||
) : res.outcome === 'not_packaged' ? (
|
||||
<div className={styles.muted}>{t('updates.notPackaged')}</div>
|
||||
) : (
|
||||
<div className={styles.muted}>{t('updates.noLicense')}</div>
|
||||
);
|
||||
|
||||
const showUpdateIdle = phase === 'done' && res !== null && res.outcome === 'available' && !downloadBusy;
|
||||
const showUpdateBusy = phase === 'done' && res !== null && res.outcome === 'available' && downloadBusy;
|
||||
|
||||
return createPortal(
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
onClick={() => {
|
||||
if (!downloadBusy) onClose();
|
||||
}}
|
||||
className={styles.modalBackdrop}
|
||||
/>
|
||||
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
||||
<div className={styles.modalHeader}>
|
||||
<div className={styles.modalTitle}>{t('updates.dialogTitle')}</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
disabled={downloadBusy}
|
||||
onClick={onClose}
|
||||
className={styles.modalClose}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div className={styles.fieldGrid}>{body}</div>
|
||||
<div className={styles.modalFooter}>
|
||||
{showUpdateIdle ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={downloadBusy} onClick={onClose}>
|
||||
{t('common.close')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={downloadBusy}
|
||||
onClick={() => {
|
||||
setDownloadBusy(true);
|
||||
void getDndApi()
|
||||
.invoke(ipcChannels.updater.downloadAndRestart, {})
|
||||
.then((r) => {
|
||||
if (!r.ok) {
|
||||
setDownloadBusy(false);
|
||||
setRes({ outcome: 'error', message: r.message });
|
||||
}
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
setDownloadBusy(false);
|
||||
setRes({
|
||||
outcome: 'error',
|
||||
message: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t('updates.download')}
|
||||
</Button>
|
||||
</>
|
||||
) : showUpdateBusy ? (
|
||||
<Button variant="primary" disabled>
|
||||
{t('updates.downloading')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="primary" disabled={downloadBusy} onClick={onClose}>
|
||||
{t('common.close')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
type SimpleMessageModalProps = {
|
||||
open: boolean;
|
||||
title?: string;
|
||||
|
||||
@@ -114,10 +114,21 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
|
||||
|
||||
'menu.enterKey': 'Указать ключ',
|
||||
'menu.aboutLicense': 'О лицензии',
|
||||
'menu.checkUpdates': 'Проверить обновления',
|
||||
'menu.language': 'Язык',
|
||||
'menu.langRu': 'Русский',
|
||||
'menu.langEn': 'English',
|
||||
|
||||
'updates.dialogTitle': 'Обновления',
|
||||
'updates.checking': 'Проверка наличия обновлений…',
|
||||
'updates.available': 'Доступна новая версия {version}.',
|
||||
'updates.current': 'У вас установлена актуальная версия ({version}).',
|
||||
'updates.error': 'Не удалось проверить обновления: {message}',
|
||||
'updates.notPackaged': 'Проверка доступна только в установленной версии приложения.',
|
||||
'updates.noLicense': 'Нужна активная лицензия.',
|
||||
'updates.download': 'Обновить',
|
||||
'updates.downloading': 'Загрузка…',
|
||||
|
||||
'projectMenu.home': 'Начальный экран',
|
||||
'projectMenu.import': 'Импорт',
|
||||
'projectMenu.export': 'Экспорт',
|
||||
@@ -330,10 +341,21 @@ export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
|
||||
|
||||
'menu.enterKey': 'Enter license key',
|
||||
'menu.aboutLicense': 'About license',
|
||||
'menu.checkUpdates': 'Check for updates',
|
||||
'menu.language': 'Language',
|
||||
'menu.langRu': 'Русский',
|
||||
'menu.langEn': 'English',
|
||||
|
||||
'updates.dialogTitle': 'Updates',
|
||||
'updates.checking': 'Checking for updates…',
|
||||
'updates.available': 'A new version is available: {version}.',
|
||||
'updates.current': 'You have the latest version ({version}).',
|
||||
'updates.error': 'Could not check for updates: {message}',
|
||||
'updates.notPackaged': 'Updates can only be checked in the installed application.',
|
||||
'updates.noLicense': 'An active license is required.',
|
||||
'updates.download': 'Update',
|
||||
'updates.downloading': 'Downloading…',
|
||||
|
||||
'projectMenu.home': 'Home',
|
||||
'projectMenu.import': 'Import',
|
||||
'projectMenu.export': 'Export',
|
||||
|
||||
@@ -18,6 +18,10 @@ export const ipcChannels = {
|
||||
quit: 'app.quit',
|
||||
getVersion: 'app.getVersion',
|
||||
},
|
||||
updater: {
|
||||
check: 'updater.check',
|
||||
downloadAndRestart: 'updater.downloadAndRestart',
|
||||
},
|
||||
project: {
|
||||
list: 'project.list',
|
||||
create: 'project.create',
|
||||
@@ -84,6 +88,15 @@ export type ZipProgressEvent = {
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
export type UpdaterCheckResponse =
|
||||
| { outcome: 'not_packaged' }
|
||||
| { outcome: 'no_license' }
|
||||
| { outcome: 'current'; currentVersion: string }
|
||||
| { outcome: 'available'; version: string }
|
||||
| { outcome: 'error'; message: string };
|
||||
|
||||
export type UpdaterDownloadResponse = { ok: true } | { ok: false; message: string };
|
||||
|
||||
export type IpcEventMap = {
|
||||
[ipcChannels.session.stateChanged]: { state: SessionState };
|
||||
[ipcChannels.effects.stateChanged]: { state: EffectsState };
|
||||
@@ -101,7 +114,15 @@ export type IpcInvokeMap = {
|
||||
};
|
||||
[ipcChannels.app.getVersion]: {
|
||||
req: Record<string, never>;
|
||||
res: { version: string; buildNumber: string | null };
|
||||
res: { version: string; buildNumber: string | null; packaged: boolean };
|
||||
};
|
||||
[ipcChannels.updater.check]: {
|
||||
req: Record<string, never>;
|
||||
res: UpdaterCheckResponse;
|
||||
};
|
||||
[ipcChannels.updater.downloadAndRestart]: {
|
||||
req: Record<string, never>;
|
||||
res: UpdaterDownloadResponse;
|
||||
};
|
||||
[ipcChannels.project.list]: {
|
||||
req: Record<string, never>;
|
||||
|
||||
@@ -6,13 +6,16 @@ import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
|
||||
void test('package.json: конфиг electron-builder (mac/win)', () => {
|
||||
void test('package.json: конфиг electron-builder (mac/win/linux)', () => {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as {
|
||||
build: {
|
||||
appId: string;
|
||||
asar: boolean;
|
||||
asarUnpack: string[];
|
||||
extraResources: { from: string; to: string }[];
|
||||
mac: { target: unknown };
|
||||
linux: { target: unknown };
|
||||
appImage?: { artifactName?: string };
|
||||
files: string[];
|
||||
};
|
||||
};
|
||||
@@ -21,6 +24,22 @@ void test('package.json: конфиг electron-builder (mac/win)', () => {
|
||||
assert.equal(pkg.build.asar, true, 'релизный артефакт: app.asar без «голого» дерева dist в .app/.exe');
|
||||
assert.ok(Array.isArray(pkg.build.asarUnpack));
|
||||
assert.ok(pkg.build.asarUnpack.some((p) => p.includes('preload')));
|
||||
assert.ok(Array.isArray(pkg.build.extraResources));
|
||||
assert.ok(
|
||||
pkg.build.extraResources.some(
|
||||
(e: unknown) =>
|
||||
typeof e === 'object' &&
|
||||
e !== null &&
|
||||
'to' in e &&
|
||||
typeof (e as { to: unknown }).to === 'string' &&
|
||||
(e as { to: string }).to.includes('branding'),
|
||||
),
|
||||
);
|
||||
assert.ok(Array.isArray(pkg.build.mac.target));
|
||||
assert.ok(Array.isArray(pkg.build.linux.target));
|
||||
const linuxTargets = pkg.build.linux.target as { target: string; arch: string[] }[];
|
||||
assert.ok(linuxTargets.some((t) => t.target === 'AppImage'));
|
||||
assert.ok(linuxTargets.some((t) => t.arch.includes('x64') && t.arch.includes('arm64')));
|
||||
assert.ok(pkg.build.appImage?.artifactName?.includes('${arch}'));
|
||||
assert.ok(pkg.build.files.includes('dist/**/*'));
|
||||
});
|
||||
|
||||
@@ -315,7 +315,16 @@ sudo journalctl -u gitea-act-runner -f
|
||||
- В **`.gitea/workflows/release.yml`** в `runs-on:` должна совпадать **именно метка `ubuntu-22.04`** (Gitea сопоставляет её и с **`ubuntu-22.04:host`**, и с **`ubuntu-22.04:docker://...`** — см. [Labels](https://docs.gitea.com/usage/actions/act-runner#labels) в документации act_runner).
|
||||
- Если при регистрации указал только **`self-hosted`** — добавь **`ubuntu-22.04:host`** (или поменяй `runs-on` в workflow на твои метки и закоммить).
|
||||
|
||||
Сборка **Windows (NSIS)** в CI идёт **на Linux**: нативный **`nsis`** (`makensis`) + **`wine64`** и обёртка **`wine`→`wine64`** (без **wine32**/i386 — см. `release.yml`). Отдельная **macOS**-сборка в workflow отключена, пока нет Mac-раннера (см. комментарии в `release.yml`).
|
||||
Сборка **Windows (NSIS)** и **Linux (AppImage x64 + arm64)** в CI идёт **на одном** `ubuntu-22.04`: NSIS + `wine64` для Win, `qemu-user-static` для кросс-сборки arm64 AppImage на amd64 (см. `release.yml`). **macOS** в этом job не собирается (ручная выкладка или отдельный раннер — см. `docs/MANUAL_MAC_UPDATE_UPLOAD.md`).
|
||||
|
||||
---
|
||||
|
||||
## Linux: AppImage и автообновление
|
||||
|
||||
- В ветке **`updates`** рядом с Windows лежат **`latest-linux.yml`** и файлы **`*.AppImage`** (x64 и arm64). Скрипт **`scripts/sync-update-feed.mjs`** делает **merge-копирование**: файлы других ОС в репозитории **не удаляются**, обновляются только имена, пришедшие из текущего CI-прогона.
|
||||
- **Базовый дистрибутив для бинарников:** сборка на **Ubuntu 22.04 (glibc 2.35)** — совместимость с «максимумом» настольных дистрибутивов с glibc не старее целевого; **Alpine/musl** без отдельной сборки не гарантируется.
|
||||
- **Запуск AppImage:** на части систем нужен **FUSE** (например `libfuse2` для старых форматов / документация дистрибутива). Подпись пакетов в первом варианте **не** используется (как договорённость по проекту).
|
||||
- Правила **electron-updater** в приложении те же: упакованная сборка и **активная лицензия** (`installAutoUpdater.ts`).
|
||||
|
||||
---
|
||||
|
||||
@@ -346,7 +355,7 @@ git push origin v1.0.1
|
||||
2. В **DndGamePlayerUpdates** есть хотя бы один коммит (не пустой репо).
|
||||
3. В приватном репо заданы **все четыре** секрета из таблицы шага 2 (имена **не** начинаются с `GITEA_`).
|
||||
4. В репо с кодом есть **`.gitea/workflows/release.yml`**.
|
||||
5. Релиз: пуш тега `v*` → в Actions job **`release`** (сборка Win + push feed в одном job, без GitHub `upload-artifact`); в публичном репо появляется ветка **`updates`** с `latest.yml` и установщиками (нужен online-раннер, см. раздел про act_runner).
|
||||
5. Релиз: пуш тега `v*` → в Actions job **`release`**: сборка **Windows** + **Linux AppImage** и push feed; в публичном репо ветка **`updates`** содержит `latest.yml`, `latest-linux.yml`, установщики Windows и **`.AppImage`** для Linux (нужен online-раннер `ubuntu-22.04`, см. раздел про act_runner). Скрипт sync **не затирает** артефакты других платформ при обновлении.
|
||||
6. В приложении: обновления только **`app.isPackaged`** и при **активной лицензии** (см. `app/main/update/installAutoUpdater.ts`).
|
||||
|
||||
---
|
||||
@@ -356,9 +365,9 @@ git push origin v1.0.1
|
||||
- Проверка только в **собранной** установке (`app.isPackaged`).
|
||||
- Только если **лицензия активна**.
|
||||
- Первый запрос примерно через **12 с** после старта; при смене лицензии — снова (не чаще **30 с**).
|
||||
- Для отладки можно задать переменную окружения **`DND_UPDATE_FEED_URL`** при запуске `.exe` — переопределит feed.
|
||||
- Для отладки можно задать переменную окружения **`DND_UPDATE_FEED_URL`** при запуске приложения (Windows / Linux / macOS) — переопределит feed.
|
||||
|
||||
Подпись кода в CI отключена: `CSC_IDENTITY_AUTO_DISCOVERY=false`.
|
||||
Подпись кода в CI отключена: `CSC_IDENTITY_AUTO_DISCOVERY=false` (в т.ч. Linux AppImage без репозитория подписи).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
# Ручная выкладка macOS-обновлений в публичный feed
|
||||
|
||||
Инструкция для случая, когда **сборка делается на вашем Mac вручную**, а файлы для `electron-updater` нужно **вручную** положить в публичный репозиторий обновлений.
|
||||
|
||||
Общая схема проекта: приватный репозиторий с кодом, публичный **`DndGamePlayerUpdates`**, ветка **`updates`**, URL feed как в `package.json`:
|
||||
|
||||
`https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/`
|
||||
|
||||
---
|
||||
|
||||
## 1. Что собрать на Mac
|
||||
|
||||
В каталоге проекта `dnd_player`:
|
||||
|
||||
```bash
|
||||
cd /путь/к/dnd_player
|
||||
npm ci
|
||||
npm run build
|
||||
```
|
||||
|
||||
Сборка установщиков только под macOS (без публикации в сеть, только файлы в `release/`):
|
||||
|
||||
```bash
|
||||
npx electron-builder --mac --publish never \
|
||||
--config.publish.provider=generic \
|
||||
--config.publish.url="https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/"
|
||||
```
|
||||
|
||||
**Важно:** значение `--config.publish.url=...` должно совпадать с `package.json` → `build.publish.url` (**со слэшем в конце**). Так внутри приложения и в `latest-mac.yml` будет корректный базовый URL для скачивания.
|
||||
|
||||
После сборки откройте папку **`release/`** в корне проекта. Там должны быть, среди прочего:
|
||||
|
||||
- **`latest-mac.yml`** — обязателен для `electron-updater` на Mac;
|
||||
- **`.dmg`** и/или **`.zip`** — то, на что ссылается `latest-mac.yml`;
|
||||
- при необходимости **`.blockmap`** (если electron-builder их создал) — заливайте с теми же именами, что указаны в `latest-mac.yml`.
|
||||
|
||||
Имена файлов зависят от версии и архитектур (в конфиге dmg и zip для **x64** и **arm64**). На Apple Silicon без дополнительных шагов часто получается только **arm64**; для отдельного Intel-сборщика нужна своя машина или параметры arch — ориентируйтесь на фактический список файлов в `release/`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Куда заливать
|
||||
|
||||
Файлы должны оказаться в **публичном** репозитории:
|
||||
|
||||
| Параметр | Значение |
|
||||
| ------------ | ------------------------------------------------------------------------- |
|
||||
| Репозиторий | `ifontosh/DndGamePlayerUpdates` (подставьте свой owner/repo, если другой) |
|
||||
| Ветка | `updates` |
|
||||
| Расположение | **корень ветки** (не подпапка) |
|
||||
|
||||
Проверка: в браузере должен открываться, например:
|
||||
|
||||
`https://git.mailib.ru/ifontosh/DndGamePlayerUpdates/raw/branch/updates/latest-mac.yml`
|
||||
|
||||
Файлы Windows (`latest.yml`, `.exe`, …), которые кладёт CI, должны **остаться** в том же корне. Вы **добавляете или обновляете** только macOS-артефакты и **`latest-mac.yml`**, не удаляя артефакты Windows (если не делаете осознанную зачистку старых версий).
|
||||
|
||||
---
|
||||
|
||||
## 3. Способ A — через `git` (удобно для больших dmg)
|
||||
|
||||
### 3.1. Клон и ветка `updates`
|
||||
|
||||
```bash
|
||||
cd ~/где-удобно
|
||||
git clone https://git.mailib.ru/ifontosh/DndGamePlayerUpdates.git
|
||||
cd DndGamePlayerUpdates
|
||||
git fetch origin
|
||||
git checkout updates
|
||||
```
|
||||
|
||||
Если ветки `updates` ещё нет:
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
git pull
|
||||
git checkout -b updates
|
||||
git push -u origin updates
|
||||
```
|
||||
|
||||
Дальше для каждой выкладки работайте в ветке **`updates`**.
|
||||
|
||||
### 3.2. Актуализировать локальную копию
|
||||
|
||||
```bash
|
||||
git checkout updates
|
||||
git pull origin updates
|
||||
```
|
||||
|
||||
### 3.3. Скопировать файлы из `release/` в корень клона
|
||||
|
||||
```bash
|
||||
cp /путь/к/dnd_player/release/latest-mac.yml .
|
||||
cp /путь/к/dnd_player/release/*.dmg .
|
||||
cp /путь/к/dnd_player/release/*.zip .
|
||||
# blockmap, если есть:
|
||||
cp /путь/к/dnd_player/release/*.blockmap . 2>/dev/null || true
|
||||
```
|
||||
|
||||
Проверка, что Windows-файлы на месте:
|
||||
|
||||
```bash
|
||||
ls -la
|
||||
```
|
||||
|
||||
### 3.4. Коммит и push
|
||||
|
||||
```bash
|
||||
git add latest-mac.yml *.dmg *.zip
|
||||
git add *.blockmap 2>/dev/null || true
|
||||
git status
|
||||
git commit -m "mac: DNDGamePlayer vX.Y.Z (ручная выкладка)"
|
||||
git push origin updates
|
||||
```
|
||||
|
||||
Для HTTPS обычно используют **персональный токен (PAT)** Gitea вместо пароля, либо настроенный **SSH** (`git@git.mailib.ru:ifontosh/DndGamePlayerUpdates.git`).
|
||||
|
||||
### 3.5. Проверка
|
||||
|
||||
- Откройте `latest-mac.yml` по raw-URL (см. выше).
|
||||
- Откройте в браузере прямую ссылку на один из `.dmg` из этого YAML — не должно быть 404.
|
||||
|
||||
---
|
||||
|
||||
## 4. Способ B — через веб-интерфейс Gitea
|
||||
|
||||
Подходит для редких правок; для больших **dmg** удобнее git.
|
||||
|
||||
1. Репозиторий `DndGamePlayerUpdates` → ветка **`updates`**.
|
||||
2. Загрузить или изменить **`latest-mac.yml`** и бинарники (**имена как в `release/`**).
|
||||
3. Не удалять при этом файлы Windows в корне, если они нужны для PC-обновлений.
|
||||
|
||||
---
|
||||
|
||||
## 5. Версии и Windows
|
||||
|
||||
- В **`latest-mac.yml`** и в именах файлов должна быть та **версия приложения**, которую вы отдаёте пользователям Mac (как в `package.json` на момент сборки).
|
||||
- **`latest.yml`** (Windows) и **`latest-mac.yml`** (Mac) — разные файлы; версии на платформах могут совпадать или нет. Каждая ОС читает свой YAML.
|
||||
|
||||
---
|
||||
|
||||
## 6. Подпись кода (кратко)
|
||||
|
||||
Без **Developer ID** и при необходимости **нотаризации** macOS может ограничивать запуск после скачивания. На процедуру «залить файлы в репо» это не влияет, но влияет на UX после автообновления. Для продакшена имеет смысл позже настроить `CSC_LINK`, `CSC_KEY_PASSWORD` и нотаризацию по [документации electron-builder](https://www.electron.build/).
|
||||
|
||||
---
|
||||
|
||||
## 7. Чеклист
|
||||
|
||||
1. Локально собрали Mac с `--publish never` и верным `publish.url`.
|
||||
2. В `release/` есть **`latest-mac.yml`** и все объекты, на которые он ссылается.
|
||||
3. В ветке **`updates`** в корне репозитория обновили/добавили эти файлы, не снеся Windows-артефакты без необходимости.
|
||||
4. Проверили raw-URL **`latest-mac.yml`** и ссылку на dmg.
|
||||
5. В **упакованном** приложении с **активной лицензией** сработает существующий `electron-updater` (задержка первой проверки и cooldown — см. `app/main/update/installAutoUpdater.ts`).
|
||||
|
||||
---
|
||||
|
||||
## Связанные документы
|
||||
|
||||
- Общая схема Gitea, секреты, раннер: [GITEA_AUTO_UPDATE.md](./GITEA_AUTO_UPDATE.md).
|
||||
Generated
+906
-7
File diff suppressed because it is too large
Load Diff
+30
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "DndGamePlayer",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.7",
|
||||
"description": "DNDGamePlayer — редактор и проигрыватель игр",
|
||||
"main": "dist/main/index.cjs",
|
||||
"scripts": {
|
||||
@@ -18,7 +18,8 @@
|
||||
"pack": "npm run build && node scripts/release-win-prep.mjs && electron-builder",
|
||||
"pack:dir": "npm run build && node scripts/release-win-prep.mjs && electron-builder --dir",
|
||||
"pack:mac": "npm run build && electron-builder --mac",
|
||||
"pack:win": "npm run build && node scripts/release-win-prep.mjs && electron-builder --win"
|
||||
"pack:win": "npm run build && node scripts/release-win-prep.mjs && electron-builder --win",
|
||||
"pack:linux": "npm run build && electron-builder --linux"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
@@ -60,6 +61,7 @@
|
||||
"javascript-obfuscator": "^4.2.2",
|
||||
"patch-package": "^8.0.1",
|
||||
"prettier": "^3.8.3",
|
||||
"to-ico": "^1.1.2",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.2",
|
||||
"typescript-eslint": "^8.58.2",
|
||||
@@ -75,6 +77,12 @@
|
||||
"output": "release",
|
||||
"buildResources": "build"
|
||||
},
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "build/icon.ico",
|
||||
"to": "branding/icon.ico"
|
||||
}
|
||||
],
|
||||
"files": [
|
||||
"dist/**/*",
|
||||
"package.json"
|
||||
@@ -82,6 +90,8 @@
|
||||
"asar": true,
|
||||
"asarUnpack": [
|
||||
"dist/preload/**",
|
||||
"dist/renderer/app-pack-icon.png",
|
||||
"dist/renderer/app-window-icon.png",
|
||||
"node_modules/sharp/**",
|
||||
"node_modules/@img/**",
|
||||
"node_modules/ffmpeg-static/**"
|
||||
@@ -121,8 +131,26 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"icon": "build/icon.ico"
|
||||
},
|
||||
"linux": {
|
||||
"target": [
|
||||
{
|
||||
"target": "AppImage",
|
||||
"arch": [
|
||||
"x64",
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
],
|
||||
"category": "Game",
|
||||
"maintainer": "DNDGamePlayer",
|
||||
"synopsis": "DNDGamePlayer — редактор и проигрыватель игр",
|
||||
"icon": "build/icon.png"
|
||||
},
|
||||
"appImage": {
|
||||
"artifactName": "${productName}-${version}-${arch}.${ext}"
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": false,
|
||||
"allowToChangeInstallationDirectory": true,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* Растеризует app-logo.svg в app-window-icon.png для nativeImage (Windows).
|
||||
* Пишет build/icon.png (macOS / fallback) и build/icon.ico — для exe/NSIS и «Программы и компоненты».
|
||||
* Запуск: node scripts/gen-window-icon.mjs
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
@@ -7,6 +8,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { Resvg } from '@resvg/resvg-js';
|
||||
import toIco from 'to-ico';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const root = path.join(__dirname, '..');
|
||||
@@ -29,4 +31,18 @@ const resvg512 = new Resvg(svg, {
|
||||
});
|
||||
const packOut = resvg512.render();
|
||||
fs.writeFileSync(packIconPath, packOut.asPng());
|
||||
console.log('wrote', packIconPath, packOut.width, 'x', packOut.height, '(electron-builder)');
|
||||
console.log('wrote', packIconPath, packOut.width, 'x', packOut.height, '(electron-builder mac / fallback)');
|
||||
|
||||
function renderPngForWidth(width) {
|
||||
const r = new Resvg(svg, {
|
||||
fitTo: { mode: 'width', value: width },
|
||||
});
|
||||
return Buffer.from(r.render().asPng());
|
||||
}
|
||||
|
||||
const icoSizes = [16, 24, 32, 48, 64, 128, 256];
|
||||
const icoPngs = icoSizes.map((w) => renderPngForWidth(w));
|
||||
const icoBuf = await toIco(icoPngs);
|
||||
const icoPath = path.join(buildDir, 'icon.ico');
|
||||
fs.writeFileSync(icoPath, icoBuf);
|
||||
console.log('wrote', icoPath, '(electron-builder win)');
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
/**
|
||||
* Складывает артефакты electron-builder (win + mac) в публичный репозиторий,
|
||||
* Складывает артефакты electron-builder (win + mac + linux) в публичный репозиторий,
|
||||
* ветка `updates`, чтобы generic URL …/raw/branch/updates/ указывал на актуальные latest*.yml и установщики.
|
||||
*
|
||||
* Переменные окружения (имена без префикса GITEA_ — в Gitea секреты GITEA_* зарезервированы):
|
||||
* Копирование **merge**: существующие файлы в ветке (другие ОС) не удаляются — обновляются только
|
||||
* те имена, которые пришли из переданных каталогов артефактов.
|
||||
*
|
||||
* Переменные окружения:
|
||||
* DND_UPDATES_SERVER — https://git.example.com (без слэша в конце)
|
||||
* UPDATES_REPO — owner/repo (публичный репозиторий «только релизы»)
|
||||
* UPDATES_REPO — owner/repo (публичный репозиторий)
|
||||
* DND_UPDATES_PUSH_TOKEN — PAT с правом push в UPDATES_REPO
|
||||
* ARTIFACT_WIN — каталог с файлами сборки Windows
|
||||
* ARTIFACT_MAC — каталог с файлами сборки macOS
|
||||
* ARTIFACT_WIN — каталог с файлами Windows (можно пустой / отсутствует — пропуск)
|
||||
* ARTIFACT_MAC — каталог с файлами macOS
|
||||
* ARTIFACT_LINUX — каталог с файлами Linux (AppImage и т.д.)
|
||||
* GIT_COMMIT_TAG — опционально, для сообщения коммита
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process';
|
||||
@@ -18,7 +22,7 @@ import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const ALLOWED_EXT = new Set(['.yml', '.yaml', '.exe', '.blockmap', '.zip', '.dmg', '.pkg']);
|
||||
const ALLOWED_EXT = new Set(['.yml', '.yaml', '.exe', '.blockmap', '.zip', '.dmg', '.pkg', '.appimage']);
|
||||
|
||||
function mustEnv(name) {
|
||||
const v = process.env[name]?.trim();
|
||||
@@ -26,9 +30,14 @@ function mustEnv(name) {
|
||||
return v;
|
||||
}
|
||||
|
||||
function optionalDir(name) {
|
||||
const v = process.env[name]?.trim();
|
||||
return v && v.length > 0 ? v : '';
|
||||
}
|
||||
|
||||
function copyFlatReleaseFiles(fromDir, toDir) {
|
||||
if (!fs.existsSync(fromDir)) {
|
||||
console.warn(`[sync-update-feed] skip missing dir: ${fromDir}`);
|
||||
if (!fromDir || !fs.existsSync(fromDir)) {
|
||||
console.warn(`[sync-update-feed] skip missing dir: ${fromDir || '(empty)'}`);
|
||||
return 0;
|
||||
}
|
||||
let n = 0;
|
||||
@@ -47,19 +56,13 @@ function runGit(args, cwd) {
|
||||
execFileSync('git', args, { cwd, stdio: 'inherit' });
|
||||
}
|
||||
|
||||
function emptyWorkingTreeExceptGit(cwd) {
|
||||
for (const ent of fs.readdirSync(cwd)) {
|
||||
if (ent === '.git') continue;
|
||||
fs.rmSync(path.join(cwd, ent), { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const server = mustEnv('DND_UPDATES_SERVER').replace(/\/+$/u, '');
|
||||
const updatesRepo = mustEnv('UPDATES_REPO');
|
||||
const token = mustEnv('DND_UPDATES_PUSH_TOKEN');
|
||||
const winDir = mustEnv('ARTIFACT_WIN');
|
||||
const macDir = mustEnv('ARTIFACT_MAC');
|
||||
const winDir = optionalDir('ARTIFACT_WIN');
|
||||
const macDir = optionalDir('ARTIFACT_MAC');
|
||||
const linuxDir = optionalDir('ARTIFACT_LINUX');
|
||||
|
||||
const u = new URL(server);
|
||||
const host = u.host;
|
||||
@@ -78,11 +81,14 @@ function main() {
|
||||
runGit(['config', 'user.email', 'ci@gitea-actions.local'], work);
|
||||
runGit(['config', 'user.name', 'gitea-actions'], work);
|
||||
|
||||
emptyWorkingTreeExceptGit(work);
|
||||
|
||||
const copied = copyFlatReleaseFiles(winDir, work) + copyFlatReleaseFiles(macDir, work);
|
||||
const copied =
|
||||
copyFlatReleaseFiles(winDir, work) +
|
||||
copyFlatReleaseFiles(macDir, work) +
|
||||
copyFlatReleaseFiles(linuxDir, work);
|
||||
if (copied === 0) {
|
||||
throw new Error('[sync-update-feed] no release files copied (check ARTIFACT_WIN / ARTIFACT_MAC)');
|
||||
throw new Error(
|
||||
'[sync-update-feed] no release files copied (check ARTIFACT_WIN / ARTIFACT_MAC / ARTIFACT_LINUX)',
|
||||
);
|
||||
}
|
||||
|
||||
const tag = process.env.GIT_COMMIT_TAG?.trim() || 'ci';
|
||||
@@ -96,7 +102,7 @@ function main() {
|
||||
}
|
||||
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
console.log(`[sync-update-feed] done (${String(copied)} file(s) staged)`);
|
||||
console.log(`[sync-update-feed] done (${String(copied)} file(s) copied)`);
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
Reference in New Issue
Block a user