Skip to content

Commit

Permalink
Cache segments
Browse files Browse the repository at this point in the history
  • Loading branch information
CommandString committed Sep 6, 2024
1 parent 4beb6b3 commit 38c72c3
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions server/utils/stations/sa/Station.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export abstract class Station {
abstract readonly songFolder: string|null;
protected readonly abstract songMetadata: SongMetaData[];
private songs: Song[]|null = null;
private segments: {
id: string[]|null,
dj: string[]|null,
caller: string[]|null,
} = {id: null, dj: null, caller: null};

public async getSongs(): Promise<Song[]> {
if (this.songs) {
Expand Down Expand Up @@ -61,21 +66,28 @@ export abstract class Station {
}

public async getRandomSegment(type: 'ID'|'DJ'|'Caller'): Promise<string> {
let segments = [];
let pathPrefix = [AUDIO_FOLDER, this.songFolder ?? this.name];
const files = await readdir(path.resolve(...pathPrefix));
let ids = [];

for (let file of files) {
if (file.includes(`(${type})`)) {
ids.push(file);
if (!this.segments[type.toLowerCase() as 'id'|'dj'|'caller']) {
const files = await readdir(path.resolve(...pathPrefix));

for (let file of files) {
if (file.includes(`(${type})`)) {
segments.push(file);
}
}

if (segments.length === 0) {
throw new Error(`No ${type} segments found`);
}
}

if (ids.length === 0) {
throw new Error(`No ${type} files found`);
this.segments[type.toLowerCase() as 'id'|'dj'|'caller'] = segments;
} else {
segments = this.segments[type.toLowerCase() as 'id'|'dj'|'caller']!;
}

let randomId = ids[Math.floor(Math.random() * ids.length)];
let randomId = segments[Math.floor(Math.random() * segments.length)];

return path.resolve(...pathPrefix, randomId);
}
Expand Down

0 comments on commit 38c72c3

Please sign in to comment.