Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/main/cms/transferCms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ async function flushToOldCms(deps: Pick<CmsTransferDeps, 'xmds' | 'db' | 'popSta
stats.forEach((stat) => { statsXmlString += submitStatXmlString(stat); });

const success = await xmds.submitStats(statsXmlString);
if (success) {
if (success === true) {
popStats.clearSubmitted(stats);
}
}
Expand Down
104 changes: 83 additions & 21 deletions src/main/common/fileManager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import axios from "axios";
import fs from 'fs';
import { join } from 'path';
import { createHash, randomUUID } from 'crypto';
import { Transform } from 'stream';
import { pipeline } from 'stream/promises';
import { app } from "electron";
import * as cheerio from 'cheerio';
import { DateTime } from 'luxon';
Expand Down Expand Up @@ -47,6 +50,35 @@ export function setIsPurging(value: boolean) {
isPurging = value;
}

/**
* Streams a download to tempPath, hashing it on the way.
*
* @return The number of bytes written and their MD5.
*/
async function downloadToFile(url: string, tempPath: string): Promise<{ size: number; md5: string }> {
const response = await axios.get(url, {
responseType: 'stream',
timeout: 15000, // 15s without data
});

const hash = createHash('md5');
let size = 0;

await pipeline(
response.data,
new Transform({
transform(chunk: Buffer, _encoding, callback) {
hash.update(chunk);
size += chunk.length;
callback(null, chunk);
},
}),
fs.createWriteStream(tempPath),
);

return { size, md5: hash.digest('hex') };
}

export async function downloadAndSaveFile(
file: FileManagerFileType,
options: {
Expand All @@ -56,30 +88,37 @@ export async function downloadAndSaveFile(
transaction: 'insert' | 'update' = 'insert'
) {
let status = options.status ?? 'success';
let size = 0;


// Download beside the real file and move it into place only once it is complete and
// checked, so a failed download never touches the copy that may be playing. The name is
// unique so two downloads of the same file cannot write into each other.
const tempPath = `${options.localPath}.${randomUUID()}.part`;

try {
console.log(`[FileManager] Downloading: ${file.path}`);
const response = await axios.get(file.path as string, {
responseType: 'arraybuffer',
timeout: 15000, // 15s timeout
});
const downloaded = await downloadToFile(file.path as string, tempPath);

let fileData = response.data;
// Anything other than the file the CMS listed (a cut-off transfer, or a proxy's error
// page sent with a 200) is a failure, and the next collection tries again.
if (file.md5 && downloaded.md5 !== file.md5) {
throw new Error(`MD5 mismatch, expected ${file.md5} but got ${downloaded.md5} (${downloaded.size} bytes)`);
}

// Rewrite local server URLs in CSS files
if (file.fileType === 'fontCss') {
fileData = Buffer.from(rewriteFontUrls(response.data.toString('utf-8'), (fileName) => {
const fileData = rewriteFontUrls(await fs.promises.readFile(tempPath, 'utf-8'), (fileName) => {
return localFileUrlFromFileName(fileName);
}));
});

console.debug('[FileManager::downloadFile] Rewrote font CSS URLs:', {
fileData: fileData.toString('utf-8'),
fileData,
});

await fs.promises.writeFile(tempPath, fileData);
}

fs.writeFileSync(options.localPath, fileData);
size = fs.statSync(options.localPath).size;
await fs.promises.rename(tempPath, options.localPath);
const size = (await fs.promises.stat(options.localPath)).size;

// An HTML Package is not playable as a downloaded archive — it has to be
// extracted before the renderer can point an iframe at it. Treat a
Expand Down Expand Up @@ -115,14 +154,17 @@ export async function downloadAndSaveFile(
console.error(`[FileManager] Error downloading ${file.saveAs}:`, err instanceof Error ? err.message : String(err));
status = 'failed';

// Remove partially downloaded file if exists
if (fs.existsSync(options.localPath)) {
try {
fs.unlinkSync(options.localPath);
console.log(`[FileManager] Removed incomplete file: ${file.saveAs}`);
} catch (unlinkErr) {
console.warn(`[FileManager] Failed to remove incomplete file: ${file.saveAs}`, unlinkErr);
}
try {
await fs.promises.rm(tempPath, { force: true });
} catch (unlinkErr) {
console.warn(`[FileManager] Failed to remove incomplete file: ${file.saveAs}`, unlinkErr);
}

// A failed update leaves the previous version on disk and recorded as downloaded,
// so it keeps playing. Its stored MD5 still differs from the CMS, so the next
// collection tries the update again.
if (transaction === 'update') {
return file;
}

store.db.prepare(`
Expand All @@ -143,7 +185,27 @@ export async function downloadAndSaveFile(
return file;
}

export async function downloadFile(file: FileManagerFileType) {
// Downloads in progress, by file name.
const downloadsInProgress = new Map<string, Promise<FileManagerFileType>>();

// Downloads a file unless it is already downloading, in which case it waits for that download
// instead of starting a second copy of the same file.
export function downloadFile(file: FileManagerFileType): Promise<FileManagerFileType> {
const name = file.saveAs as string;
const inProgress = downloadsInProgress.get(name);

if (inProgress) {
console.debug(`[FileManager] Already downloading ${name}, waiting for it`);
return inProgress;
}

const download = downloadFileIfNeeded(file).finally(() => downloadsInProgress.delete(name));
downloadsInProgress.set(name, download);

return download;
}

async function downloadFileIfNeeded(file: FileManagerFileType) {
const localPath = join(xiboLibDir, file.saveAs as string);

// Check if file already exists
Expand Down
76 changes: 58 additions & 18 deletions src/main/common/scheduleManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { geoLocationManager } from "./geoLocationManager";
import { scheduleCriteriaManager } from "../../shared/scheduleCriteria/scheduleCriteriaManager";
import { DataConnector } from "../xmds/response/schedule/events/dataConnector";
import { Action } from "../xmds/response/schedule/events/action";
import { loopDuration } from "./shareOfVoice";

export type ScheduleLayoutsType = Layout | DefaultLayout | SspLayout;

Expand Down Expand Up @@ -182,6 +183,24 @@ export default class ScheduleManager {

this.isAssessingLayouts = true;

// Always clear the flag: if it stayed set, every later assessment would be skipped and
// the screen would keep the current loop until the player restarts.
try {
await this.assessLayoutLoop();
} catch (error) {
console.error('[ScheduleManager::assessLayouts] > Assessment failed, keeping the current loop', {
error: error instanceof Error ? error.message : String(error),
method: 'Schedule: Manager: Assess',
});
} finally {
this.isAssessingLayouts = false;
}
}

/**
* Works out the layout loop from the current schedule and emits it if it changed.
*/
private async assessLayoutLoop() {
// If we don't have anything to assess, drop out straight away.
let hasChanged = false;
if (!this.schedule || (this.schedule.countLayouts() <= 0 && !this.schedule.defaultLayout)) {
Expand All @@ -192,7 +211,6 @@ export default class ScheduleManager {
this.config.state.scheduleLoop = 'Splash only';
this.layouts = [this.getSplash()];
this.emitter.emit('layouts', [this.getSplash()]);
this.isAssessingLayouts = false;
return;
}

Expand All @@ -201,8 +219,8 @@ export default class ScheduleManager {
let loop: ScheduleLayoutsType[] = [];
let interruptLayouts: ScheduleLayoutsType[] = [];

// Do we have SSP
if (this.sspShareOfVoice > 0) {
// Do we have SSP? Without an average ad duration there is nothing to divide the hour by.
if (this.sspShareOfVoice > 0 && this.sspAverageDuration > 0) {
const sspLayout = new SspLayout();
sspLayout.duration = this.sspAverageDuration;
sspLayout.shareOfVoice = this.sspShareOfVoice;
Expand Down Expand Up @@ -297,7 +315,7 @@ export default class ScheduleManager {
// Get the layout at this index
if (!interruptLayouts[index].isInterruptDurationSatisfied()) {
interruptLayouts[index].addCommittedInterruptDuration();
interruptSecondsInHour += interruptLayouts[index].duration;
interruptSecondsInHour += loopDuration(interruptLayouts[index].duration);

// Add this again
resolvedInterruptLayouts.push(interruptLayouts[index]);
Expand All @@ -306,7 +324,8 @@ export default class ScheduleManager {
index++;
}

if (interruptSecondsInHour >= 3600) {
if (interruptSecondsInHour >= 3600 || layouts.length === 0) {
// Interrupts fill the hour, or there is nothing else to play between them.
loop = resolvedInterruptLayouts;
} else {
// We should fill up the remaining time with normal layouts
Expand All @@ -317,8 +336,9 @@ export default class ScheduleManager {
index = 0;
}

normalSecondsInHour -= layouts[index].duration;
normalSecondsInHour -= loopDuration(layouts[index].duration);
resolvedNormalLayouts.push(layouts[index]);
index++;
}

// Now we combine them together.
Expand All @@ -343,7 +363,7 @@ export default class ScheduleManager {
normalIndex = 0;
}
loop.push(resolvedNormalLayouts[normalIndex]);
totalSecondsAllocated += resolvedNormalLayouts[normalIndex].duration;
totalSecondsAllocated += loopDuration(resolvedNormalLayouts[normalIndex].duration);
normalIndex++;
}

Expand All @@ -352,7 +372,7 @@ export default class ScheduleManager {
// them all.
if (i % interruptPick == 0 && interruptIndex < resolvedInterruptLayouts.length) {
loop.push(resolvedInterruptLayouts[interruptIndex]);
totalSecondsAllocated += resolvedInterruptLayouts[interruptIndex].duration;
totalSecondsAllocated += loopDuration(resolvedInterruptLayouts[interruptIndex].duration);
interruptIndex++;
}

Expand All @@ -367,7 +387,7 @@ export default class ScheduleManager {
normalIndex = 0;
}
loop.push(resolvedNormalLayouts[normalIndex]);
totalSecondsAllocated += resolvedNormalLayouts[normalIndex].duration;
totalSecondsAllocated += loopDuration(resolvedNormalLayouts[normalIndex].duration);
normalIndex++;
}
}
Expand Down Expand Up @@ -455,8 +475,6 @@ export default class ScheduleManager {
allLayouts.push(defaultId + ' (D)' + (loopIds.has(defaultId) ? '' : '*'));
}
this.config.state.allLayoutIds = allLayouts.join(', ');

this.isAssessingLayouts = false;
}

/**
Expand Down Expand Up @@ -487,11 +505,27 @@ export default class ScheduleManager {

this.isAssessingOverlays = true;

// Always clear the flag, for the same reason as in assessLayouts().
try {
await this.assessOverlayLoop();
} catch (error) {
console.error('[ScheduleManager::assessOverlays] > Assessment failed, keeping the current overlays', {
error: error instanceof Error ? error.message : String(error),
method: 'Schedule: Manager: Assess Overlays',
});
} finally {
this.isAssessingOverlays = false;
}
}

/**
* Works out the overlays from the current schedule and emits them if they changed.
*/
private async assessOverlayLoop() {
// If we don't have anything to assess, drop out straight away.
let hasChanged = false;
if (!this.schedule || (this.schedule && this.schedule.overlays.length === 0)) {
this.overlays = [];
this.isAssessingOverlays = false;
this.emitter.emit('overlays', this.overlays);
return;
}
Expand Down Expand Up @@ -523,7 +557,6 @@ export default class ScheduleManager {
method: 'Schedule: Manager: Assess Overlays',
});
this.overlays = [];
this.isAssessingOverlays = false;
this.emitter.emit('overlays', this.overlays);
return;
} else {
Expand All @@ -549,8 +582,6 @@ export default class ScheduleManager {
console.debug('[ScheduleManager::assessOverlays] > Assessment of overlays finished', {
method: 'Schedule: Manager: Assess Overlays',
});

this.isAssessingOverlays = false;
}

/**
Expand Down Expand Up @@ -815,9 +846,18 @@ export default class ScheduleManager {

// Handle geofence logic if applicable
if (layout.isGeoAware) {
// Extract the polygon from the layout's geoLocation
const geo = JSON.parse(layout.geoLocation);
const polygon = geo.geometry.coordinates[0];
// Extract the polygon from the layout's geoLocation. A fence that cannot be read
// cannot be checked, so the layout is left out rather than played everywhere.
let polygon;
try {
polygon = JSON.parse(layout.geoLocation).geometry.coordinates[0];
} catch {
console.warn('[ScheduleManager::evaluateLayout] > Unreadable geofence, skipping layout.', {
layoutId: layout.file,
method: 'Schedule: Manager: Assess'
});
return null;
}

// Check if the device's current location falls inside thsse polygon
const insidePolygon = geoLocationManager.isCurrentLocationInsidePolygon(polygon);
Expand Down
38 changes: 38 additions & 0 deletions src/main/common/shareOfVoice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2026 Xibo Signage Ltd
*
* Xibo - Digital Signage - https://xibosignage.com
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/

// Seconds a layout counts for when its duration is missing, zero or not a number.
export const DEFAULT_LOOP_DURATION = 60;

/**
* The duration a layout counts for when the schedule loop is built.
*
* The share of voice loops keep adding layouts until the hour is filled, so a
* duration of 0 or NaN would keep them running forever. Such a layout counts
* for DEFAULT_LOOP_DURATION instead. This only affects how the hour is divided;
* the layout still plays for its own length.
*
* @param duration The duration from the schedule, in seconds.
* @return {number} A positive number of seconds.
*/
export function loopDuration(duration: number): number {
return Number.isFinite(duration) && duration > 0 ? duration : DEFAULT_LOOP_DURATION;
}
6 changes: 4 additions & 2 deletions src/main/common/stats/PoPStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ export class PoPStats {
this.options = _options;
this.db = new StatsDB();

// Clear the stats DB on each start
this.clearDB();
// Finished stats not yet sent survive a restart and go to the CMS on the next submit.
// A stat still open (no end yet) was cut short by the restart and can never be
// closed, so it is dropped.
this.db.deleteOpen();

this.on('message', data => {
const eventData = data;
Expand Down
Loading
Loading