Merge branch 'j.lechner/ui-ux-improvements' into 'main'
feat: improve UI and UX, add schedule options and settings See merge request julian/blockwoche3.1-radiosender!14
This commit is contained in:
commit
ae3bb7960d
34 files changed
+2015
-466
No files matched your search
@@ -19,30 +19,39 @@ dotnet test Radiosender.slnx
|
|||||||
On first start the app creates its data under `%LOCALAPPDATA%\Radiosender`:
|
On first start the app creates its data under `%LOCALAPPDATA%\Radiosender`:
|
||||||
|
|
||||||
- `radiosender.db`: the SQLite music library
|
- `radiosender.db`: the SQLite music library
|
||||||
|
- `settings.json`: the values from the Settings page
|
||||||
- `Music\`: copies of uploaded files and downloaded Openverse tracks
|
- `Music\`: copies of uploaded files and downloaded Openverse tracks
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
1. **Import**: one page for both ways of adding music. Every result, added or failed, is listed under "Added in this session", with a link to the Library.
|
The interface is in German. This section names the controls as they appear on screen.
|
||||||
- **From computer**: drop MP3 or WAV files on the page or click **Choose files...**; several files at once are fine. The app copies each file into the music folder, reads title and artist from the file tags and measures the duration. A file that fails is reported and the others still get imported.
|
|
||||||
- **Openverse**: search the [Openverse](https://openverse.org) audio catalog, preview a result and import it with **Import to library** or a double-click. The app downloads the file and stores its license and attribution with the song. Results that are already in the library or have no duration are marked and cannot be imported.
|
|
||||||
2. **Library**: lists and searches all songs. Edit title, artist, license and attribution, or delete a song.
|
|
||||||
3. **Schedule**:
|
|
||||||
1. Enter the number of hours (1 to 24) and click **Create schedule**. The plan starts at the next full hour.
|
|
||||||
2. The timeline shows every item with start time, type (song, news, ad, moderator), title and duration.
|
|
||||||
3. **Start** puts the plan on air on the real clock. Before the planned start the now-playing card shows when the broadcast begins; if the plan has already begun, playback joins at the next item. **Stop** ends it. The now-playing card shows the current item, its progress and the volume.
|
|
||||||
4. **Song request**: choose a song, select an upcoming row in the timeline and click **Play instead of selected**. This also works while the broadcast is running.
|
|
||||||
|
|
||||||
News, ads and moderator talk are placeholders: the app shows them in the timeline and keeps silent for their duration.
|
1. **Import**: one page for both ways of adding music. Every result, added or failed, is listed under "Importiert" as soon as there is one, with a link to the library.
|
||||||
|
- **Vom Computer**: drop MP3 or WAV files on the page or click **Dateien auswählen...**; several files at once are fine. The app copies each file into the music folder, reads title and artist from the file tags and measures the duration. A file that fails is reported and the others still get imported.
|
||||||
|
- **Openverse**: search the [Openverse](https://openverse.org) audio catalog, preview a result and import it with **In Bibliothek importieren** or a double-click. Select several results with Ctrl or Shift to import them in one go; they are downloaded one after the other. The app downloads the file and stores its license and attribution with the song. Results that are already in the library or have no duration cannot be imported; the tooltip of the disabled button says why.
|
||||||
|
2. **Bibliothek**: lists and searches all songs. Edit title, artist, license and attribution, or delete a song.
|
||||||
|
3. **Sendeplan** (the start page):
|
||||||
|
1. Choose the start (one of the next 12 full hours) and the number of hours (1 to 24), then click **Plan erstellen**.
|
||||||
|
- **Unbegrenzt** plans without an end: the timeline shows the next 5 hours, and while the broadcast runs one more hour is added whenever less than 5 hours are left.
|
||||||
|
- **Jetzt starten** ignores the start time, plans from this moment and goes on air at once. Music leads up to the first news at the next :00 or :30; the chosen hours count from there.
|
||||||
|
2. The timeline shows every item with start time, type (song, news, ad, moderator), title and duration.
|
||||||
|
3. **Start** puts the plan on air on the real clock. Before the planned start the now-playing card shows when the broadcast begins; if the plan has already begun, playback joins at the next item. The same button then reads **Stopp** and ends it. The now-playing card shows the current item, its progress and the volume.
|
||||||
|
4. **Edit the timeline**: select an upcoming row and use the buttons above the list to move it up or down, edit it, or remove it (trash icon). News, ad and moderator items have no title until you give them one; news and moderator items can also change their length. A double-click opens the editor too. Every item after a change follows on without a gap. The item on air can be edited too, but not moved or removed; **Jetzt beenden** in the now-playing card ends it at once and starts the next item.
|
||||||
|
5. **Speaking reminder**: 30 seconds before a news or moderator item goes on air, a dialog in the middle of the screen reminds you on any page and stays until you click **OK**.
|
||||||
|
6. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running.
|
||||||
|
|
||||||
|
4. **Einstellungen** (bottom left): switch the speaking alert on or off for news and for moderator talk, set how many seconds before the start it appears and whether it plays a bing sound. Set the minutes per hour for news, moderator talk and ads (defaults 10, 10 and 20); together they can take at most 60 minutes. **ZurĂĽcksetzen** puts the default values into the form, **Speichern** stores them in `settings.json` next to the database. Alerts change at once; minutes per hour apply to the next schedule.
|
||||||
|
|
||||||
|
News, ads and moderator talk are placeholders: the app shows them in the timeline and keeps silent for their duration, so the speaker can talk live.
|
||||||
|
|
||||||
## How the schedule is built
|
## How the schedule is built
|
||||||
|
|
||||||
`ScheduleGenerator` plans in half-hour slots:
|
`ScheduleGenerator` plans in half-hour slots:
|
||||||
|
|
||||||
- Each slot starts with 5 minutes of news at :00 or :30.
|
- Each slot starts with news at :00 or :30; the news minutes per hour are split over the two.
|
||||||
- The rest of the slot is random songs plus 2 to 10 minutes of ads and moderator talk. Ten minutes per half hour keeps every hour at 20 minutes or less.
|
- The rest of the slot is random songs plus ads and moderator talk. The minutes per hour from the settings are targets: the last song has to end exactly when the next news starts and songs are never cut, so the ad and moderator time is what the songs leave. The generator tries several hundred random song picks per slot and keeps the one that leaves closest to the target. What the :00 slot misses, the :30 slot makes up for, so the hour comes out within a few seconds of the targets with a normal library.
|
||||||
- Ads and moderator items alternate, and one ad item lasts at most 5 minutes, so there is never a long block of ads.
|
- Ads are cut into items of at most 5 minutes. Each ad item follows a moderator item, and the breaks sit between the songs, so ads never run back to back as long as there is moderator time or a song to put between them.
|
||||||
- The filler sits between the songs and the slot always ends with a song, so that song ends exactly when the next news starts. Songs are never cut. When the filler does not add up, the last placeholder is shortened.
|
- The slot always ends with a song. If the targets take the whole hour, the slot has no songs.
|
||||||
|
|
||||||
During playback `PlaybackEngine` starts every item at its planned time. If the previous item ended early, it waits; if it ran late, the next item starts right after it and is never cut. The news therefore comes at the real :00 and :30.
|
During playback `PlaybackEngine` starts every item at its planned time. If the previous item ended early, it waits; if it ran late, the next item starts right after it and is never cut. The news therefore comes at the real :00 and :30.
|
||||||
|
|
||||||
@@ -76,21 +85,21 @@ Tests are in `tests/Radiosender.Tests` (xUnit). They cover the repository, impor
|
|||||||
|
|
||||||
Music search uses the [Openverse API](https://api.openverse.org/v1/) without an API key. Openverse lists openly licensed works (Creative Commons and public domain) from many sources. The rights stay with the creators.
|
Music search uses the [Openverse API](https://api.openverse.org/v1/) without an API key. Openverse lists openly licensed works (Creative Commons and public domain) from many sources. The rights stay with the creators.
|
||||||
|
|
||||||
For each downloaded track the app stores the license (for example `CC BY 4.0`) and the attribution text from Openverse. The Library page shows both. Anyone who plays or shares these tracks must keep this attribution, as the licenses require.
|
For each downloaded track the app stores the license (for example `CC BY 4.0`) and the attribution text from Openverse. Both are shown in the edit dialog of a song (**Bearbeiten** on the library page). Anyone who plays or shares these tracks must keep this attribution, as the licenses require.
|
||||||
|
|
||||||
## Assignment checklist
|
## Assignment checklist
|
||||||
|
|
||||||
| Requirement | Where | Status |
|
| Requirement | Where | Status |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Plays random music for X hours; only full hours, entered by the user | Schedule page, hours 1 to 24; `ScheduleGenerator.PickSongs` | Done |
|
| Plays random music for X hours; only full hours, entered by the user | Schedule page, hours 1 to 24 or unlimited; `ScheduleGenerator.PickSongs` | Done |
|
||||||
| 2 Ă— 5 minutes of news per hour, at :00 and :30 | `ScheduleGenerator.Generate`; `PlaybackEngine` waits for each planned start | Done |
|
| 2 Ă— 5 minutes of news per hour, at :00 and :30 | `ScheduleGenerator.Generate`; `PlaybackEngine` waits for each planned start | Done |
|
||||||
| News comes after a song, no song is cut | Slot ends with a song that ends at the news start; tests in `ScheduleGeneratorTests` | Done |
|
| News comes after a song, no song is cut | Slot ends with a song that ends at the news start; tests in `ScheduleGeneratorTests` | Done |
|
||||||
| Up to 20 minutes of ads and moderator talk per hour | At most 10 minutes per half hour | Done |
|
| Up to 20 minutes of ads and moderator talk per hour | Targets in the settings. The defaults are 20 minutes of ads plus 10 of moderator talk, which is 30; set them to 20 together to meet this rule | Configurable |
|
||||||
| Ads never 20 minutes in a row | Ads alternate with moderator items, one ad item lasts at most 5 minutes | Done |
|
| Ads never 20 minutes in a row | One ad item lasts at most 5 minutes and follows a moderator item | Done |
|
||||||
| Remaining time filled with music | Songs fill each slot | Done |
|
| Remaining time filled with music | Songs fill each slot | Done |
|
||||||
| Music comes from a SQLite database | `SongRepository`, `radiosender.db` | Done |
|
| Music comes from a SQLite database | `SongRepository`, `radiosender.db` | Done |
|
||||||
| Library can be extended at any time: add, edit, delete | Library page and `SongEditWindow` | Done |
|
| Library can be extended at any time: add, edit, delete | Library page and `SongEditWindow` | Done |
|
||||||
| Add by simple upload | Import page, "From computer" (MP3, WAV, several files, drag and drop) | Done |
|
| Add by simple upload | Import page, "Vom Computer" (MP3, WAV, several files, drag and drop) | Done |
|
||||||
| Add through the Openverse API | Import page, "Openverse" | Done |
|
| Add through the Openverse API | Import page, "Openverse" | Done |
|
||||||
| Music player is a singleton class | `MusicPlayer.Instance` | Done |
|
| Music player is a singleton class | `MusicPlayer.Instance` | Done |
|
||||||
| Hot swap: a requested song replaces an item during the planned run, everything after adapts | Song request on the Schedule page; `ScheduleGenerator.Replace`, `PlaybackEngine.ReplaceUpcoming` | Done |
|
| Hot swap: a requested song replaces an item during the planned run, everything after adapts | Song request on the Schedule page; `ScheduleGenerator.Replace`, `PlaybackEngine.ReplaceUpcoming` | Done |
|
||||||
@@ -100,8 +109,11 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
|
|||||||
|
|
||||||
## Known limitations
|
## Known limitations
|
||||||
|
|
||||||
- **Waiting for the start**: a new plan starts at the next full hour, so after **Start** the app can stay silent for up to an hour.
|
- **Waiting for the start**: a plan made with **Plan erstellen** starts at a full hour, so after **Start** the app stays silent until then. **Jetzt starten** avoids the wait.
|
||||||
|
- **Unlimited plans** keep every played item in the timeline, so the list grows by about 20 rows per hour.
|
||||||
|
- **Manual edits** shift every later item, so after moving, removing or resizing an item the news can leave :00 and :30 and the plan can end earlier or later.
|
||||||
- **Late items**: if a song plays longer than its stored duration, the following items start late by the same amount. Nothing is cut to catch up; the delay only disappears when a later item ends early.
|
- **Late items**: if a song plays longer than its stored duration, the following items start late by the same amount. Nothing is cut to catch up; the delay only disappears when a later item ends early.
|
||||||
- **Skipped songs**: a song that cannot be played (missing file, unsupported format) is skipped with a warning, and the station stays silent until the next planned item.
|
- **Skipped songs**: a song that cannot be played (missing file, unsupported format) is skipped with a warning, and the station stays silent until the next planned item.
|
||||||
- **Deleting a song** removes it from the library but keeps its file in the `Music` folder.
|
- **Deleting a song** removes it from the library but keeps its file in the `Music` folder.
|
||||||
- **Placeholders** have no audio. The last filler of a half hour can be very short (for example 2 seconds) because it is cut to fit.
|
- **Placeholders** have no audio.
|
||||||
|
- **Targets** for ads and moderator talk are missed by the time the songs cannot fill, usually a few seconds per hour; a small library or only long songs make that more.
|
||||||
@@ -11,11 +11,29 @@ public partial class App : Application
|
|||||||
/// <summary>App-wide, so a running broadcast keeps going while the user switches pages.</summary>
|
/// <summary>App-wide, so a running broadcast keeps going while the user switches pages.</summary>
|
||||||
public static ScheduleController Schedule { get; private set; } = null!;
|
public static ScheduleController Schedule { get; private set; } = null!;
|
||||||
|
|
||||||
|
public static AppSettings Settings { get; private set; } = new();
|
||||||
|
|
||||||
|
private static readonly ScheduleGenerator Generator = new();
|
||||||
|
|
||||||
|
/// <summary>Stores the settings and applies them: alerts at once, minutes per hour from the next plan on.</summary>
|
||||||
|
/// <exception cref="System.IO.IOException">The settings file cannot be written.</exception>
|
||||||
|
/// <exception cref="UnauthorizedAccessException">The settings file cannot be written.</exception>
|
||||||
|
public static void SaveSettings(AppSettings settings)
|
||||||
|
{
|
||||||
|
settings.Save(AppSettings.DefaultPath);
|
||||||
|
Settings = settings;
|
||||||
|
Generator.Options = settings.ToScheduleOptions();
|
||||||
|
}
|
||||||
|
|
||||||
protected override void OnStartup(StartupEventArgs e)
|
protected override void OnStartup(StartupEventArgs e)
|
||||||
{
|
{
|
||||||
|
Settings = AppSettings.Load(AppSettings.DefaultPath);
|
||||||
|
Generator.Options = Settings.ToScheduleOptions();
|
||||||
// Creates the database file and table on first start.
|
// Creates the database file and table on first start.
|
||||||
Songs = new SongRepository(SongRepository.DefaultDatabasePath);
|
Songs = new SongRepository(SongRepository.DefaultDatabasePath);
|
||||||
Schedule = new ScheduleController(Songs, new ScheduleGenerator(), new PlaybackEngine(), () => DateTime.Now);
|
Schedule = new ScheduleController(Songs, Generator, new PlaybackEngine(), () => DateTime.Now);
|
||||||
|
// Follow the Windows setting: light, dark or a high-contrast theme.
|
||||||
|
Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme();
|
||||||
base.OnStartup(e);
|
base.OnStartup(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ public class OpenverseController(OpenverseClient client, SongRepository songs)
|
|||||||
public async Task<Song> ImportAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
|
public async Task<Song> ImportAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
if (track.Duration is not { } duration)
|
if (track.Duration is not { } duration)
|
||||||
throw new OpenverseException("This result has no duration and cannot be imported.");
|
throw new OpenverseException("Dieses Ergebnis hat keine Dauer und kann nicht importiert werden.");
|
||||||
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
|
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
|
||||||
throw new OpenverseException($"\"{track.Title}\" is already in the library.");
|
throw new OpenverseException($"\"{track.Title}\" ist bereits in der Bibliothek.");
|
||||||
|
|
||||||
var path = await client.DownloadAsync(track, cancellationToken);
|
var path = await client.DownloadAsync(track, cancellationToken);
|
||||||
var song = new Song
|
var song = new Song
|
||||||
|
|||||||
@@ -12,10 +12,15 @@ public class ScheduleController
|
|||||||
{
|
{
|
||||||
public const int MaxHours = 24;
|
public const int MaxHours = 24;
|
||||||
|
|
||||||
|
/// <summary>How far ahead an unlimited plan always reaches.</summary>
|
||||||
|
public const int UnlimitedLookaheadHours = 5;
|
||||||
|
|
||||||
private readonly SongRepository _songs;
|
private readonly SongRepository _songs;
|
||||||
private readonly ScheduleGenerator _generator;
|
private readonly ScheduleGenerator _generator;
|
||||||
private readonly PlaybackEngine _engine;
|
private readonly PlaybackEngine _engine;
|
||||||
private readonly Func<DateTime> _now;
|
private readonly Func<DateTime> _now;
|
||||||
|
// Guards Plan against a song request (UI thread) racing the hourly extension (engine thread).
|
||||||
|
private readonly Lock _planLock = new();
|
||||||
private DateTime _itemStartedAt;
|
private DateTime _itemStartedAt;
|
||||||
|
|
||||||
public ScheduleController(SongRepository songs, ScheduleGenerator generator, PlaybackEngine engine, Func<DateTime> now)
|
public ScheduleController(SongRepository songs, ScheduleGenerator generator, PlaybackEngine engine, Func<DateTime> now)
|
||||||
@@ -27,9 +32,10 @@ public class ScheduleController
|
|||||||
_engine.ItemStarted += (_, e) =>
|
_engine.ItemStarted += (_, e) =>
|
||||||
{
|
{
|
||||||
_itemStartedAt = _now();
|
_itemStartedAt = _now();
|
||||||
|
ExtendIfUnlimited();
|
||||||
ItemStarted?.Invoke(this, e.Index);
|
ItemStarted?.Invoke(this, e.Index);
|
||||||
};
|
};
|
||||||
_engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, $"Skipped \"{e.Item.Title}\": {e.Error.Message}");
|
_engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, $"\"{e.Item.Title}\" ĂĽbersprungen: {e.Error.Message}");
|
||||||
_engine.Finished += (_, _) => Finished?.Invoke(this, EventArgs.Empty);
|
_engine.Finished += (_, _) => Finished?.Invoke(this, EventArgs.Empty);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,6 +45,10 @@ public class ScheduleController
|
|||||||
|
|
||||||
public IReadOnlyList<ScheduleItem> Plan { get; private set; } = [];
|
public IReadOnlyList<ScheduleItem> Plan { get; private set; } = [];
|
||||||
|
|
||||||
|
/// <summary><c>true</c> for a plan without an end: it grows by an hour whenever less than
|
||||||
|
/// <see cref="UnlimitedLookaheadHours"/> hours are left.</summary>
|
||||||
|
public bool IsUnlimited { get; private set; }
|
||||||
|
|
||||||
public bool IsPlaying => _engine.IsRunning;
|
public bool IsPlaying => _engine.IsRunning;
|
||||||
|
|
||||||
public int CurrentIndex => _engine.CurrentIndex;
|
public int CurrentIndex => _engine.CurrentIndex;
|
||||||
@@ -58,18 +68,66 @@ public class ScheduleController
|
|||||||
set => MusicPlayer.Instance.Volume = value;
|
set => MusicPlayer.Instance.Volume = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Plans <paramref name="hours"/> full hours from the next full hour with the songs in the library.</summary>
|
/// <summary>
|
||||||
|
/// Plans <paramref name="hours"/> full hours with the songs in the library; <c>null</c> plans without an end.
|
||||||
|
/// The plan begins at <paramref name="start"/>, or at the next full hour when that is <c>null</c>.
|
||||||
|
/// </summary>
|
||||||
/// <exception cref="ScheduleException">The library cannot fill the plan.</exception>
|
/// <exception cref="ScheduleException">The library cannot fill the plan.</exception>
|
||||||
public IReadOnlyList<ScheduleItem> CreatePlan(int hours)
|
public IReadOnlyList<ScheduleItem> CreatePlan(int? hours, DateTime? start = null)
|
||||||
{
|
{
|
||||||
ArgumentOutOfRangeException.ThrowIfLessThan(hours, 1);
|
if (hours is { } h)
|
||||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(hours, MaxHours);
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(h, 1, nameof(hours));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(h, MaxHours, nameof(hours));
|
||||||
|
}
|
||||||
|
|
||||||
var now = _now();
|
var now = _now();
|
||||||
var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1);
|
var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1);
|
||||||
|
// Whole seconds, so the timeline and the item ends stay on the second.
|
||||||
|
var from = start is { } s ? new DateTime(s.Ticks - s.Ticks % TimeSpan.TicksPerSecond, s.Kind) : nextHour;
|
||||||
Stop();
|
Stop();
|
||||||
Plan = _generator.Generate(nextHour, hours, _songs.GetAll());
|
var plan = _generator.Generate(from, hours ?? UnlimitedLookaheadHours, _songs.GetAll());
|
||||||
return Plan;
|
lock (_planLock)
|
||||||
|
{
|
||||||
|
Plan = plan;
|
||||||
|
IsUnlimited = hours is null;
|
||||||
|
}
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Plans from this moment and goes on air at once; music leads up to the first news at :00 or :30.</summary>
|
||||||
|
/// <exception cref="ScheduleException">The library cannot fill the plan.</exception>
|
||||||
|
public void StartNow(int? hours)
|
||||||
|
{
|
||||||
|
CreatePlan(hours, _now());
|
||||||
|
_engine.Start(Plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Runs on the engine thread whenever an item starts.
|
||||||
|
// shortcut: played items stay in the plan (about 20 per hour); trim them if broadcasts run for weeks.
|
||||||
|
private void ExtendIfUnlimited()
|
||||||
|
{
|
||||||
|
if (!IsUnlimited)
|
||||||
|
return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
lock (_planLock)
|
||||||
|
{
|
||||||
|
var plan = Plan;
|
||||||
|
if (plan.Count == 0) // the user removed every item
|
||||||
|
return;
|
||||||
|
var until = _now().AddHours(UnlimitedLookaheadHours);
|
||||||
|
while (plan[^1].End < until)
|
||||||
|
plan = [.. plan, .. _generator.Generate(plan[^1].End, 1, _songs.GetAll())];
|
||||||
|
// Only appends, so the engine keeps everything up to the old end.
|
||||||
|
if (!ReferenceEquals(plan, Plan) && _engine.ReplaceUpcoming(plan, Plan.Count))
|
||||||
|
Plan = plan;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (ScheduleException ex)
|
||||||
|
{
|
||||||
|
ItemFailed?.Invoke(this, $"Der Plan konnte nicht verlängert werden: {ex.Message}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Planned start of the next item while the broadcast waits for it, otherwise <c>null</c>.</summary>
|
/// <summary>Planned start of the next item while the broadcast waits for it, otherwise <c>null</c>.</summary>
|
||||||
@@ -82,14 +140,127 @@ public class ScheduleController
|
|||||||
public void Start()
|
public void Start()
|
||||||
{
|
{
|
||||||
if (Plan.Count == 0)
|
if (Plan.Count == 0)
|
||||||
throw new InvalidOperationException("Create a schedule first.");
|
throw new InvalidOperationException("Zuerst einen Plan erstellen.");
|
||||||
if (Plan[^1].Start <= _now())
|
if (Plan[^1].Start <= _now())
|
||||||
throw new InvalidOperationException("This schedule is already over. Create a new one.");
|
throw new InvalidOperationException("Dieser Plan ist bereits vorbei. Einen neuen erstellen.");
|
||||||
_engine.Start(Plan);
|
_engine.Start(Plan);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Stop() => _engine.Stop();
|
public void Stop() => _engine.Stop();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The next news or moderator item that is due for a reminder while the broadcast runs: it starts within
|
||||||
|
/// the lead time of its kind. <c>null</c> as lead time switches that kind off. Returns <c>null</c> when
|
||||||
|
/// nothing is due.
|
||||||
|
/// </summary>
|
||||||
|
public ScheduleItem? UpcomingSpeech(TimeSpan? newsLead, TimeSpan? moderatorLead)
|
||||||
|
{
|
||||||
|
if (!IsPlaying)
|
||||||
|
return null;
|
||||||
|
var now = _now();
|
||||||
|
var plan = Plan;
|
||||||
|
var longest = TimeSpan.FromTicks(Math.Max((newsLead ?? TimeSpan.Zero).Ticks, (moderatorLead ?? TimeSpan.Zero).Ticks));
|
||||||
|
for (var i = Math.Max(CurrentIndex + 1, 0); i < plan.Count; i++)
|
||||||
|
{
|
||||||
|
var wait = plan[i].Start - now;
|
||||||
|
if (wait > longest)
|
||||||
|
return null;
|
||||||
|
var lead = plan[i].Kind switch
|
||||||
|
{
|
||||||
|
ScheduleItemKind.News => newsLead,
|
||||||
|
ScheduleItemKind.Moderator => moderatorLead,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
if (wait > TimeSpan.Zero && wait <= lead)
|
||||||
|
return plan[i];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Moves the item at <paramref name="index"/> by <paramref name="offset"/> positions; later items shift in time.</summary>
|
||||||
|
/// <exception cref="ScheduleException">An affected item is already on air or over, or the target is outside the plan.</exception>
|
||||||
|
public IReadOnlyList<ScheduleItem> Move(int index, int offset)
|
||||||
|
{
|
||||||
|
var target = index + offset;
|
||||||
|
if (target < 0 || target >= Plan.Count)
|
||||||
|
throw new ScheduleException("Das Element ist bereits am Rand des Plans.");
|
||||||
|
return Change(Math.Min(index, target), change: items =>
|
||||||
|
{
|
||||||
|
var item = items[index];
|
||||||
|
items.RemoveAt(index);
|
||||||
|
items.Insert(target, item);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Removes the item at <paramref name="index"/>; later items move up in time.</summary>
|
||||||
|
/// <exception cref="ScheduleException">The item is already on air or over.</exception>
|
||||||
|
public IReadOnlyList<ScheduleItem> Remove(int index) => Change(index, change: items => items.RemoveAt(index));
|
||||||
|
|
||||||
|
/// <summary>Ends the item on air now: its length becomes the time it has run, and the next item starts.</summary>
|
||||||
|
/// <exception cref="ScheduleException">Nothing is on air.</exception>
|
||||||
|
public IReadOnlyList<ScheduleItem> EndCurrentNow()
|
||||||
|
{
|
||||||
|
var index = CurrentIndex;
|
||||||
|
if (CurrentItem is null)
|
||||||
|
throw new ScheduleException("Es ist nichts auf Sendung.");
|
||||||
|
var now = _now();
|
||||||
|
// Whole seconds, like every other time in the plan; the next start is then not in the future.
|
||||||
|
var end = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, now.Kind);
|
||||||
|
return Change(index, currentAllowed: true, change: items =>
|
||||||
|
{
|
||||||
|
var item = items[index];
|
||||||
|
items[index] = item with { Duration = end > item.Start ? end - item.Start : TimeSpan.Zero };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sets the title of a news, ad or moderator item, and the length of a news or moderator item;
|
||||||
|
/// later items shift in time. Also works for the item on air: its new length counts from its start.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ScheduleException">The item cannot be edited that way, or is already over.</exception>
|
||||||
|
public IReadOnlyList<ScheduleItem> EditItem(int index, string title, TimeSpan duration) => Change(index, currentAllowed: true, change: items =>
|
||||||
|
{
|
||||||
|
var item = items[index];
|
||||||
|
if (item.Kind == ScheduleItemKind.Song)
|
||||||
|
throw new ScheduleException("Songs werden in der Bibliothek bearbeitet.");
|
||||||
|
if (duration != item.Duration && item.Kind == ScheduleItemKind.Ad)
|
||||||
|
throw new ScheduleException("Nur Nachrichten und Moderation können ihre Länge ändern.");
|
||||||
|
if (duration <= TimeSpan.Zero)
|
||||||
|
throw new ScheduleException("Die Länge muss größer als null sein.");
|
||||||
|
items[index] = item with { Title = title.Trim(), Duration = duration };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Manual edits ripple: from the first changed position on, every item starts when the one before ends.
|
||||||
|
// News can therefore leave :00 and :30; that is the user's call.
|
||||||
|
// currentAllowed: the item on air may change too; the engine is then told to re-time it.
|
||||||
|
private IReadOnlyList<ScheduleItem> Change(int firstChanged, Action<List<ScheduleItem>> change, bool currentAllowed = false)
|
||||||
|
{
|
||||||
|
lock (_planLock)
|
||||||
|
{
|
||||||
|
if (firstChanged < 0 || firstChanged >= Plan.Count)
|
||||||
|
throw new ScheduleException("Ein Element im Plan auswählen.");
|
||||||
|
var onAir = IsPlaying && firstChanged == CurrentIndex;
|
||||||
|
if (IsPlaying && (firstChanged < CurrentIndex || (onAir && !currentAllowed)))
|
||||||
|
throw new ScheduleException(onAir
|
||||||
|
? "Dieses Element ist auf Sendung. Es kann bearbeitet oder beendet, aber nicht verschoben oder entfernt werden."
|
||||||
|
: "Dieses Element ist bereits vorbei. Ein späteres wählen.");
|
||||||
|
|
||||||
|
var items = Plan.ToList();
|
||||||
|
var start = items[firstChanged].Start;
|
||||||
|
change(items);
|
||||||
|
for (var i = firstChanged; i < items.Count; i++)
|
||||||
|
{
|
||||||
|
items[i] = items[i] with { Start = start };
|
||||||
|
start = items[i].End;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsPlaying && !(onAir ? _engine.ReplaceCurrent(items, firstChanged) : _engine.ReplaceUpcoming(items, firstChanged)))
|
||||||
|
throw new ScheduleException("Die Sendung ist inzwischen weitergelaufen. Erneut versuchen.");
|
||||||
|
Plan = items;
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>All songs in the library, for the song request picker.</summary>
|
/// <summary>All songs in the library, for the song request picker.</summary>
|
||||||
public IReadOnlyList<Song> LibrarySongs() => _songs.GetAll();
|
public IReadOnlyList<Song> LibrarySongs() => _songs.GetAll();
|
||||||
|
|
||||||
@@ -100,19 +271,22 @@ public class ScheduleController
|
|||||||
/// <exception cref="ScheduleException">The item cannot be replaced or the song does not fit.</exception>
|
/// <exception cref="ScheduleException">The item cannot be replaced or the song does not fit.</exception>
|
||||||
public IReadOnlyList<ScheduleItem> Swap(int index, long songId)
|
public IReadOnlyList<ScheduleItem> Swap(int index, long songId)
|
||||||
{
|
{
|
||||||
if (Plan.Count == 0)
|
lock (_planLock)
|
||||||
throw new ScheduleException("Create a schedule first.");
|
{
|
||||||
if (index < 0 || index >= Plan.Count)
|
if (Plan.Count == 0)
|
||||||
throw new ScheduleException("Select an item in the schedule.");
|
throw new ScheduleException("Zuerst einen Plan erstellen.");
|
||||||
if (IsPlaying && index <= CurrentIndex)
|
if (index < 0 || index >= Plan.Count)
|
||||||
throw new ScheduleException("This item is already on air or over. Choose a later item.");
|
throw new ScheduleException("Ein Element im Plan auswählen.");
|
||||||
var song = _songs.GetById(songId) ?? throw new ScheduleException("The song is no longer in the library.");
|
if (IsPlaying && index <= CurrentIndex)
|
||||||
|
throw new ScheduleException("Dieses Element ist bereits auf Sendung oder vorbei. Ein späteres wählen.");
|
||||||
|
var song = _songs.GetById(songId) ?? throw new ScheduleException("Der Song ist nicht mehr in der Bibliothek.");
|
||||||
|
|
||||||
var plan = _generator.Replace(Plan, index, song, _songs.GetAll());
|
var plan = _generator.Replace(Plan, index, song, _songs.GetAll());
|
||||||
// The engine may have moved on while the plan was rebuilt.
|
// The engine may have moved on while the plan was rebuilt.
|
||||||
if (IsPlaying && !_engine.ReplaceUpcoming(plan, index))
|
if (IsPlaying && !_engine.ReplaceUpcoming(plan, index))
|
||||||
throw new ScheduleException("This item went on air in the meantime. Choose a later item.");
|
throw new ScheduleException("Dieses Element ist inzwischen auf Sendung gegangen. Ein späteres wählen.");
|
||||||
Plan = plan;
|
Plan = plan;
|
||||||
return plan;
|
return plan;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,7 @@ public record UploadResult(bool Success, string Message, Song? Song = null);
|
|||||||
|
|
||||||
public class UploadController(SongImportService importService)
|
public class UploadController(SongImportService importService)
|
||||||
{
|
{
|
||||||
public static string FileDialogFilter { get; } = "Audio files (*.mp3;*.wav)|*.mp3;*.wav";
|
public static string FileDialogFilter { get; } = "Audiodateien (*.mp3;*.wav)|*.mp3;*.wav";
|
||||||
|
|
||||||
/// <summary>Imports one file; failures come back as a result, so a batch can go on with the next file.</summary>
|
/// <summary>Imports one file; failures come back as a result, so a batch can go on with the next file.</summary>
|
||||||
public UploadResult Upload(string filePath)
|
public UploadResult Upload(string filePath)
|
||||||
@@ -16,7 +16,7 @@ public class UploadController(SongImportService importService)
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var song = importService.Import(filePath);
|
var song = importService.Import(filePath);
|
||||||
return new UploadResult(true, $"\"{song.Title}\" ({(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}) was added to the library.", song);
|
return new UploadResult(true, $"\"{song.Title}\" ({(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}) wurde zur Bibliothek hinzugefĂĽgt.", song);
|
||||||
}
|
}
|
||||||
catch (SongImportException e)
|
catch (SongImportException e)
|
||||||
{
|
{
|
||||||
@@ -24,7 +24,7 @@ public class UploadController(SongImportService importService)
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
return new UploadResult(false, $"The song could not be saved: {e.Message}");
|
return new UploadResult(false, $"Der Song konnte nicht gespeichert werden: {e.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,17 +3,18 @@ using System.Text.Json.Serialization;
|
|||||||
namespace Radiosender.Models;
|
namespace Radiosender.Models;
|
||||||
|
|
||||||
/// <summary>One audio result of the Openverse search API (fields as documented at api.openverse.org/v1).</summary>
|
/// <summary>One audio result of the Openverse search API (fields as documented at api.openverse.org/v1).</summary>
|
||||||
|
/// <remarks>Openverse sends some texts HTML-encoded (&amp;), so the text fields decode on assignment.</remarks>
|
||||||
public class OpenverseTrack
|
public class OpenverseTrack
|
||||||
{
|
{
|
||||||
public string Id { get; init; } = "";
|
public string Id { get; init; } = "";
|
||||||
public string Title { get; init; } = "";
|
public string Title { get; init => field = System.Net.WebUtility.HtmlDecode(value); } = "";
|
||||||
public string? Creator { get; init; }
|
public string? Creator { get; init => field = System.Net.WebUtility.HtmlDecode(value); }
|
||||||
public string Url { get; init; } = "";
|
public string Url { get; init; } = "";
|
||||||
[JsonPropertyName("filetype")]
|
[JsonPropertyName("filetype")]
|
||||||
public string? FileType { get; init; }
|
public string? FileType { get; init; }
|
||||||
public string License { get; init; } = "";
|
public string License { get; init; } = "";
|
||||||
public string? LicenseVersion { get; init; }
|
public string? LicenseVersion { get; init; }
|
||||||
public string? Attribution { get; init; }
|
public string? Attribution { get; init => field = System.Net.WebUtility.HtmlDecode(value); }
|
||||||
|
|
||||||
/// <summary>Length in milliseconds; Openverse leaves it empty for some results.</summary>
|
/// <summary>Length in milliseconds; Openverse leaves it empty for some results.</summary>
|
||||||
[JsonPropertyName("duration")]
|
[JsonPropertyName("duration")]
|
||||||
@@ -25,7 +26,7 @@ public class OpenverseTrack
|
|||||||
/// <summary>Songs need a duration for scheduling, so results without one cannot be imported.</summary>
|
/// <summary>Songs need a duration for scheduling, so results without one cannot be imported.</summary>
|
||||||
public bool CanImport => Duration is not null;
|
public bool CanImport => Duration is not null;
|
||||||
|
|
||||||
public string DurationText => Duration?.ToString(@"m\:ss") ?? "unknown";
|
public string DurationText => Duration?.ToString(@"m\:ss") ?? "unbekannt";
|
||||||
|
|
||||||
/// <summary>Readable license name, for example "CC BY 4.0", "CC0 1.0" or "Public Domain Mark 1.0".</summary>
|
/// <summary>Readable license name, for example "CC BY 4.0", "CC0 1.0" or "Public Domain Mark 1.0".</summary>
|
||||||
public string LicenseName => License.ToLowerInvariant() switch
|
public string LicenseName => License.ToLowerInvariant() switch
|
||||||
|
|||||||
@@ -12,4 +12,13 @@ public enum ScheduleItemKind
|
|||||||
public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null)
|
public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null)
|
||||||
{
|
{
|
||||||
public DateTime End => Start + Duration;
|
public DateTime End => Start + Duration;
|
||||||
|
|
||||||
|
/// <summary>The kind as the user reads it.</summary>
|
||||||
|
public string KindName => Kind switch
|
||||||
|
{
|
||||||
|
ScheduleItemKind.News => "Nachrichten",
|
||||||
|
ScheduleItemKind.Ad => "Werbung",
|
||||||
|
ScheduleItemKind.Moderator => "Moderation",
|
||||||
|
_ => "Song",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
using System.IO;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
/// <summary>What the user can change on the Settings page. The defaults are the values the app shipped with.</summary>
|
||||||
|
public record AppSettings
|
||||||
|
{
|
||||||
|
public const int MinAlertSeconds = 5;
|
||||||
|
public const int MaxAlertSeconds = 300;
|
||||||
|
|
||||||
|
public bool NewsAlert { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>How long before a news item the reminder appears.</summary>
|
||||||
|
public int NewsAlertSeconds { get; init; } = 30;
|
||||||
|
|
||||||
|
public bool NewsAlertSound { get; init; } = true;
|
||||||
|
|
||||||
|
public bool ModeratorAlert { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>How long before a moderator item the reminder appears.</summary>
|
||||||
|
public int ModeratorAlertSeconds { get; init; } = 30;
|
||||||
|
|
||||||
|
public bool ModeratorAlertSound { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>News time per hour, split over the two news at :00 and :30.</summary>
|
||||||
|
public int NewsMinutesPerHour { get; init; } = 10;
|
||||||
|
|
||||||
|
/// <summary>Target; the plan gets as close as the song lengths allow.</summary>
|
||||||
|
public int ModeratorMinutesPerHour { get; init; } = 10;
|
||||||
|
|
||||||
|
/// <summary>Target; the plan gets as close as the song lengths allow.</summary>
|
||||||
|
public int AdMinutesPerHour { get; init; } = 20;
|
||||||
|
|
||||||
|
public static string DefaultPath { get; } = Path.Combine(
|
||||||
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
|
||||||
|
|
||||||
|
/// <summary>The first problem with these values as a message for the user, or <c>null</c> when they are fine.</summary>
|
||||||
|
public string? Validate()
|
||||||
|
{
|
||||||
|
if (NewsAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds || ModeratorAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds)
|
||||||
|
return $"Die Hinweiszeit muss zwischen {MinAlertSeconds} und {MaxAlertSeconds} Sekunden liegen.";
|
||||||
|
if (NewsMinutesPerHour < 2)
|
||||||
|
return "Nachrichten brauchen mindestens 2 Minuten pro Stunde.";
|
||||||
|
if (ModeratorMinutesPerHour < 0 || AdMinutesPerHour < 0)
|
||||||
|
return "Minuten pro Stunde dĂĽrfen nicht negativ sein.";
|
||||||
|
if (NewsMinutesPerHour + ModeratorMinutesPerHour + AdMinutesPerHour > 60)
|
||||||
|
return "Nachrichten, Moderation und Werbung dürfen zusammen höchstens 60 Minuten pro Stunde dauern.";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ScheduleOptions ToScheduleOptions() => new()
|
||||||
|
{
|
||||||
|
NewsDuration = TimeSpan.FromMinutes(NewsMinutesPerHour / 2.0),
|
||||||
|
AdsPerHour = TimeSpan.FromMinutes(AdMinutesPerHour),
|
||||||
|
ModeratorPerHour = TimeSpan.FromMinutes(ModeratorMinutesPerHour),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Reads the settings; a missing, unreadable or invalid file gives the defaults.</summary>
|
||||||
|
public static AppSettings Load(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var settings = JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(path));
|
||||||
|
return settings is not null && settings.Validate() is null ? settings : new AppSettings();
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||||||
|
{
|
||||||
|
return new AppSettings();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <exception cref="IOException">The file cannot be written.</exception>
|
||||||
|
/// <exception cref="UnauthorizedAccessException">The file cannot be written.</exception>
|
||||||
|
public void Save(string path)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||||
|
File.WriteAllText(path, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -80,7 +80,7 @@ public sealed class MusicPlayer : IAudioPlayer
|
|||||||
Release();
|
Release();
|
||||||
|
|
||||||
if (!File.Exists(filePath))
|
if (!File.Exists(filePath))
|
||||||
throw new FileNotFoundException($"Audio file not found: {filePath}", filePath);
|
throw new FileNotFoundException($"Audiodatei nicht gefunden: {filePath}", filePath);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -88,7 +88,7 @@ public sealed class MusicPlayer : IAudioPlayer
|
|||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||||
{
|
{
|
||||||
throw new InvalidDataException($"Cannot read audio file: {filePath}", ex);
|
throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public class OpenverseClient(HttpClient http, string musicFolder)
|
|||||||
}
|
}
|
||||||
catch (Exception e) when (e is not OpenverseException && !cancellationToken.IsCancellationRequested)
|
catch (Exception e) when (e is not OpenverseException && !cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
throw Wrap(e, "Openverse search failed");
|
throw Wrap(e, "Openverse-Suche fehlgeschlagen");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ public class OpenverseClient(HttpClient http, string musicFolder)
|
|||||||
public async Task<string> DownloadAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
|
public async Task<string> DownloadAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
|
if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
|
||||||
throw new OpenverseException("Only https downloads are allowed.");
|
throw new OpenverseException("Nur https-Downloads sind erlaubt.");
|
||||||
|
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
timeout.CancelAfter(DownloadTimeout);
|
timeout.CancelAfter(DownloadTimeout);
|
||||||
@@ -68,7 +68,7 @@ public class OpenverseClient(HttpClient http, string musicFolder)
|
|||||||
using var response = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
|
using var response = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
|
||||||
EnsureSuccess(response);
|
EnsureSuccess(response);
|
||||||
if (response.Content.Headers.ContentLength > MaxDownloadBytes)
|
if (response.Content.Headers.ContentLength > MaxDownloadBytes)
|
||||||
throw new OpenverseException("The file is larger than 50 MB.");
|
throw new OpenverseException("Die Datei ist größer als 50 MB.");
|
||||||
|
|
||||||
Directory.CreateDirectory(musicFolder);
|
Directory.CreateDirectory(musicFolder);
|
||||||
await using var file = CreateUniqueFile(track, out path);
|
await using var file = CreateUniqueFile(track, out path);
|
||||||
@@ -80,11 +80,11 @@ public class OpenverseClient(HttpClient http, string musicFolder)
|
|||||||
{
|
{
|
||||||
total += read;
|
total += read;
|
||||||
if (total > MaxDownloadBytes)
|
if (total > MaxDownloadBytes)
|
||||||
throw new OpenverseException("The file is larger than 50 MB.");
|
throw new OpenverseException("Die Datei ist größer als 50 MB.");
|
||||||
await file.WriteAsync(buffer.AsMemory(0, read), timeout.Token);
|
await file.WriteAsync(buffer.AsMemory(0, read), timeout.Token);
|
||||||
}
|
}
|
||||||
if (total == 0)
|
if (total == 0)
|
||||||
throw new OpenverseException("The download was empty.");
|
throw new OpenverseException("Der Download war leer.");
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
@@ -94,7 +94,7 @@ public class OpenverseClient(HttpClient http, string musicFolder)
|
|||||||
File.Delete(path);
|
File.Delete(path);
|
||||||
if (e is OpenverseException || cancellationToken.IsCancellationRequested)
|
if (e is OpenverseException || cancellationToken.IsCancellationRequested)
|
||||||
throw;
|
throw;
|
||||||
throw Wrap(e, "Download failed");
|
throw Wrap(e, "Download fehlgeschlagen");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,15 +120,15 @@ public class OpenverseClient(HttpClient http, string musicFolder)
|
|||||||
private static void EnsureSuccess(HttpResponseMessage response)
|
private static void EnsureSuccess(HttpResponseMessage response)
|
||||||
{
|
{
|
||||||
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
||||||
throw new OpenverseException("Openverse rate limit reached (anonymous: 20 requests per minute, 200 per day). Please try again later.");
|
throw new OpenverseException("Openverse-Limit erreicht (anonym: 20 Anfragen pro Minute, 200 pro Tag). Bitte später erneut versuchen.");
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
throw new OpenverseException($"Openverse returned HTTP {(int)response.StatusCode}.");
|
throw new OpenverseException($"Openverse hat HTTP {(int)response.StatusCode} geliefert.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static OpenverseException Wrap(Exception e, string action) => e switch
|
private static OpenverseException Wrap(Exception e, string action) => e switch
|
||||||
{
|
{
|
||||||
OperationCanceledException => new OpenverseException($"{action}: the request timed out.", e),
|
OperationCanceledException => new OpenverseException($"{action}: ZeitĂĽberschreitung der Anfrage.", e),
|
||||||
JsonException => new OpenverseException($"{action}: unexpected response.", e),
|
JsonException => new OpenverseException($"{action}: unerwartete Antwort.", e),
|
||||||
_ => new OpenverseException($"{action}: {e.Message}", e),
|
_ => new OpenverseException($"{action}: {e.Message}", e),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ public sealed class PlaybackEngine
|
|||||||
private CancellationTokenSource? _cts;
|
private CancellationTokenSource? _cts;
|
||||||
private Task _run = Task.CompletedTask;
|
private Task _run = Task.CompletedTask;
|
||||||
|
|
||||||
|
// Completed by ReplaceCurrent to wake the wait of the item on air; a new one per wait.
|
||||||
|
private TaskCompletionSource? _currentChanged;
|
||||||
|
|
||||||
public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay, () => DateTime.Now)
|
public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay, () => DateTime.Now)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -88,6 +91,24 @@ public sealed class PlaybackEngine
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Switches to <paramref name="items"/> while the item at <paramref name="index"/> is on air and that item
|
||||||
|
/// itself changed: a news, ad or moderator item then runs for its new length, counted from when it started,
|
||||||
|
/// and a song ends at once. Items before <paramref name="index"/> must be unchanged. Returns <c>false</c>
|
||||||
|
/// if that item is not the one on air.
|
||||||
|
/// </summary>
|
||||||
|
public bool ReplaceCurrent(IReadOnlyList<ScheduleItem> items, int index)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (!IsRunning || CurrentIndex != index || index >= items.Count)
|
||||||
|
return false;
|
||||||
|
Items = items;
|
||||||
|
_currentChanged?.TrySetResult();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Stops playback. Waits until the running schedule has ended.</summary>
|
/// <summary>Stops playback. Waits until the running schedule has ended.</summary>
|
||||||
public void Stop()
|
public void Stop()
|
||||||
{
|
{
|
||||||
@@ -151,7 +172,7 @@ public sealed class PlaybackEngine
|
|||||||
if (item.Kind == ScheduleItemKind.Song && item.Song is not null)
|
if (item.Kind == ScheduleItemKind.Song && item.Song is not null)
|
||||||
await PlaySongAsync(item, token);
|
await PlaySongAsync(item, token);
|
||||||
else
|
else
|
||||||
await _delay(item.Duration, token);
|
await HoldAsync(i, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
CurrentIndex = -1;
|
CurrentIndex = -1;
|
||||||
@@ -163,6 +184,33 @@ public sealed class PlaybackEngine
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Keeps a news, ad or moderator item on air for its length. ReplaceCurrent can change that length
|
||||||
|
// meanwhile; the wait then starts over with what is left.
|
||||||
|
private async Task HoldAsync(int index, CancellationToken token)
|
||||||
|
{
|
||||||
|
var startedAt = _now();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
TaskCompletionSource changed;
|
||||||
|
TimeSpan remaining;
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
changed = _currentChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
remaining = Items[index].Duration - (_now() - startedAt);
|
||||||
|
}
|
||||||
|
if (remaining <= TimeSpan.Zero)
|
||||||
|
return;
|
||||||
|
|
||||||
|
using var wait = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||||
|
var delay = _delay(remaining, wait.Token);
|
||||||
|
var done = await Task.WhenAny(delay, changed.Task);
|
||||||
|
wait.Cancel();
|
||||||
|
token.ThrowIfCancellationRequested();
|
||||||
|
if (done == delay)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task PlaySongAsync(ScheduleItem item, CancellationToken token)
|
private async Task PlaySongAsync(ScheduleItem item, CancellationToken token)
|
||||||
{
|
{
|
||||||
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
@@ -181,13 +229,17 @@ public sealed class PlaybackEngine
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TaskCompletionSource changed;
|
||||||
|
lock (_lock)
|
||||||
|
changed = _currentChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||||
var stuck = _delay(item.Duration + SongGrace, timeout.Token);
|
var stuck = _delay(item.Duration + SongGrace, timeout.Token);
|
||||||
var done = await Task.WhenAny(finished.Task, stuck);
|
// changed: the user ended the song early; the finally block stops the player.
|
||||||
|
var done = await Task.WhenAny(finished.Task, stuck, changed.Task);
|
||||||
timeout.Cancel();
|
timeout.Cancel();
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
if (done == stuck)
|
if (done == stuck)
|
||||||
ItemFailed?.Invoke(this, (item, new TimeoutException($"Song did not finish in time: {item.Title}")));
|
ItemFailed?.Invoke(this, (item, new TimeoutException($"Der Song wurde nicht rechtzeitig fertig: {item.Title}")));
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,71 +6,115 @@ public record ScheduleOptions
|
|||||||
{
|
{
|
||||||
public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
|
public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
|
||||||
|
|
||||||
/// <summary>Upper limit for ads and moderator talk together, per hour.</summary>
|
/// <summary>Target for ads per hour. Met as closely as the song lengths allow.</summary>
|
||||||
public TimeSpan MaxFillerPerHour { get; init; } = TimeSpan.FromMinutes(20);
|
public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20);
|
||||||
|
|
||||||
/// <summary>Ads and moderator talk planned at least per half hour, so the music is broken up.</summary>
|
/// <summary>Target for moderator talk per hour. Met as closely as the song lengths allow.</summary>
|
||||||
public TimeSpan MinFillerPerHalfHour { get; init; } = TimeSpan.FromMinutes(2);
|
public TimeSpan ModeratorPerHour { get; init; } = TimeSpan.FromMinutes(10);
|
||||||
|
|
||||||
/// <summary>Longest run of consecutive ad items. Must be below 20 minutes.</summary>
|
/// <summary>Longest single ad item; longer ad time is split and separated by moderator talk or songs.</summary>
|
||||||
public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5);
|
public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5);
|
||||||
|
|
||||||
/// <summary>Random song picks tried per half hour before giving up.</summary>
|
/// <summary>Random song picks tried per half hour; the one closest to the targets wins.</summary>
|
||||||
public int Attempts { get; init; } = 1000;
|
public int Attempts { get; init; } = 400;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ScheduleException(string message) : Exception(message);
|
public class ScheduleException(string message) : Exception(message);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds the plan in half-hour slots: news at :00 and :30, then random songs, with ads and
|
/// Builds the plan in half-hour slots: news at :00 and :30, then random songs with ads and moderator talk
|
||||||
/// moderator talk sized so that the last song of each slot ends exactly when the next news starts.
|
/// in between. The last song of each slot ends exactly when the next news starts, so the ad and moderator
|
||||||
|
/// time is whatever the songs leave; the generator picks songs that leave as close to the targets as it can
|
||||||
|
/// and evens out the difference in the second half of the hour.
|
||||||
|
/// A start between two news times gets a lead-in without news up to the next :00 or :30.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class ScheduleGenerator(ScheduleOptions options, Random random)
|
public class ScheduleGenerator(ScheduleOptions options, Random random)
|
||||||
{
|
{
|
||||||
|
/// <summary>Can be replaced at any time, e.g. from the settings page; the next plan uses the new values.</summary>
|
||||||
|
public ScheduleOptions Options { get; set; } = options;
|
||||||
|
|
||||||
private static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30);
|
private static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30);
|
||||||
|
|
||||||
|
// A pick that misses the target by this little is taken at once.
|
||||||
|
private static readonly TimeSpan CloseEnough = TimeSpan.FromSeconds(1);
|
||||||
|
|
||||||
public ScheduleGenerator() : this(new ScheduleOptions(), Random.Shared)
|
public ScheduleGenerator() : this(new ScheduleOptions(), Random.Shared)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Plans <paramref name="hours"/> full hours. They begin at <paramref name="start"/> if that is :00 or :30,
|
||||||
|
/// otherwise at the next :00 or :30 after a lead-in of music.
|
||||||
|
/// </summary>
|
||||||
public IReadOnlyList<ScheduleItem> Generate(DateTime start, int hours, IReadOnlyList<Song> songs)
|
public IReadOnlyList<ScheduleItem> Generate(DateTime start, int hours, IReadOnlyList<Song> songs)
|
||||||
{
|
{
|
||||||
|
var options = Options; // one consistent set of values for the whole plan
|
||||||
if (hours < 1)
|
if (hours < 1)
|
||||||
throw new ArgumentOutOfRangeException(nameof(hours), "At least one full hour is required.");
|
throw new ArgumentOutOfRangeException(nameof(hours), "At least one full hour is required.");
|
||||||
if (start.Minute != 0 || start.Second != 0 || start.Millisecond != 0 || start.Microsecond != 0)
|
|
||||||
throw new ArgumentException("The schedule must start at a full hour.", nameof(start));
|
|
||||||
if (options.MaxAdBlock <= TimeSpan.Zero || options.MaxAdBlock >= TimeSpan.FromMinutes(20))
|
if (options.MaxAdBlock <= TimeSpan.Zero || options.MaxAdBlock >= TimeSpan.FromMinutes(20))
|
||||||
throw new ArgumentException("MaxAdBlock must be between 0 and 20 minutes.", nameof(options));
|
throw new ArgumentException("MaxAdBlock must be between 0 and 20 minutes.", nameof(options));
|
||||||
|
|
||||||
var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList();
|
var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList();
|
||||||
if (playable.Count == 0)
|
if (playable.Count == 0)
|
||||||
throw new ScheduleException("The music library has no songs to plan with.");
|
throw new ScheduleException("Die Bibliothek enthält keine Songs zum Planen.");
|
||||||
|
|
||||||
var items = new List<ScheduleItem>();
|
var items = new List<ScheduleItem>();
|
||||||
for (var slotStart = start; slotStart < start.AddHours(hours); slotStart += HalfHour)
|
var firstNews = new DateTime((start.Ticks + HalfHour.Ticks - 1) / HalfHour.Ticks * HalfHour.Ticks, start.Kind);
|
||||||
|
if (firstNews > start)
|
||||||
|
items.AddRange(BuildLeadIn(options, start, firstNews - start, playable));
|
||||||
|
|
||||||
|
var adHalf = options.AdsPerHour / 2;
|
||||||
|
var moderatorHalf = options.ModeratorPerHour / 2;
|
||||||
|
// How far the :00 slot ended up over (or under) its half of the hour; the :30 slot makes up for it.
|
||||||
|
var adOver = TimeSpan.Zero;
|
||||||
|
var moderatorOver = TimeSpan.Zero;
|
||||||
|
for (var slotStart = firstNews; slotStart < firstNews.AddHours(hours); slotStart += HalfHour)
|
||||||
{
|
{
|
||||||
items.Add(new ScheduleItem(ScheduleItemKind.News, "News", slotStart, options.NewsDuration));
|
if (slotStart.Minute == 0)
|
||||||
items.AddRange(BuildSlot(slotStart + options.NewsDuration, HalfHour - options.NewsDuration, playable));
|
adOver = moderatorOver = TimeSpan.Zero;
|
||||||
|
|
||||||
|
var news = Min(options.NewsDuration, HalfHour);
|
||||||
|
if (news > TimeSpan.Zero)
|
||||||
|
items.Add(new ScheduleItem(ScheduleItemKind.News, "", slotStart, news));
|
||||||
|
var slot = BuildSlot(options, slotStart + news, HalfHour - news,
|
||||||
|
Max(adHalf - adOver, TimeSpan.Zero), Max(moderatorHalf - moderatorOver, TimeSpan.Zero), playable);
|
||||||
|
items.AddRange(slot);
|
||||||
|
|
||||||
|
adOver = Sum(slot.Where(i => i.Kind == ScheduleItemKind.Ad)) - adHalf;
|
||||||
|
moderatorOver = Sum(slot.Where(i => i.Kind == ScheduleItemKind.Moderator)) - moderatorHalf;
|
||||||
}
|
}
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<ScheduleItem> BuildSlot(DateTime slotStart, TimeSpan length, List<Song> songs)
|
private List<ScheduleItem> BuildLeadIn(ScheduleOptions options, DateTime start, TimeSpan length, List<Song> songs)
|
||||||
{
|
{
|
||||||
// Half of the hourly limit per slot keeps every hour within MaxFillerPerHour.
|
// The targets shrink with the lead-in: half of a half hour gets half of the ads.
|
||||||
var maxFiller = options.MaxFillerPerHour / 2;
|
var share = length / HalfHour;
|
||||||
var minFiller = options.MinFillerPerHalfHour < maxFiller ? options.MinFillerPerHalfHour : maxFiller;
|
try
|
||||||
|
|
||||||
for (var attempt = 0; attempt < options.Attempts; attempt++)
|
|
||||||
{
|
{
|
||||||
var picked = PickSongs(length - minFiller, songs);
|
return BuildSlot(options, start, length, options.AdsPerHour / 2 * share, options.ModeratorPerHour / 2 * share, songs);
|
||||||
var gap = length - Sum(picked);
|
|
||||||
if (picked.Count > 0 && gap <= maxFiller)
|
|
||||||
return Arrange(slotStart, picked, BuildFiller(gap));
|
|
||||||
}
|
}
|
||||||
|
catch (ScheduleException) when (length <= (options.AdsPerHour + options.ModeratorPerHour) / 2)
|
||||||
|
{
|
||||||
|
// Too short for any song: the moderator talks until the news.
|
||||||
|
return [new ScheduleItem(ScheduleItemKind.Moderator, "", start, length)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
throw new ScheduleException(
|
private List<ScheduleItem> BuildSlot(
|
||||||
$"No combination of songs fills the slot at {slotStart:HH:mm} so that the last song ends on time. Add more songs, especially shorter ones.");
|
ScheduleOptions options, DateTime slotStart, TimeSpan length, TimeSpan adTarget, TimeSpan moderatorTarget, List<Song> songs)
|
||||||
|
{
|
||||||
|
if (length <= TimeSpan.Zero)
|
||||||
|
return [];
|
||||||
|
var target = Min(adTarget + moderatorTarget, length);
|
||||||
|
var (picked, gap) = PickBest(options, length, target, songs);
|
||||||
|
// No song at all is only right when the targets leave no room for music.
|
||||||
|
if (picked.Count == 0 && target < length)
|
||||||
|
throw new ScheduleException(
|
||||||
|
$"Keine Song-Kombination fĂĽllt den Abschnitt ab {slotStart:HH:mm} so, dass der letzte Song pĂĽnktlich endet. Mehr Songs hinzufĂĽgen, vor allem kĂĽrzere.");
|
||||||
|
|
||||||
|
var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget);
|
||||||
|
return Arrange(options, slotStart, picked, ads, moderator, keepFirstSongFirst: false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -78,15 +122,15 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
|
|||||||
/// rebuilds the rest of its half-hour slot, so the last song still ends exactly when the next news starts.
|
/// rebuilds the rest of its half-hour slot, so the last song still ends exactly when the next news starts.
|
||||||
/// Items before <paramref name="index"/> and all later slots stay as they are.
|
/// Items before <paramref name="index"/> and all later slots stay as they are.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <exception cref="ScheduleException">The song does not fit before the next news, or the rest cannot be filled.</exception>
|
/// <exception cref="ScheduleException">The song does not fit before the next news.</exception>
|
||||||
public IReadOnlyList<ScheduleItem> Replace(IReadOnlyList<ScheduleItem> plan, int index, Song requested, IReadOnlyList<Song> songs)
|
public IReadOnlyList<ScheduleItem> Replace(IReadOnlyList<ScheduleItem> plan, int index, Song requested, IReadOnlyList<Song> songs)
|
||||||
{
|
{
|
||||||
ArgumentOutOfRangeException.ThrowIfNegative(index);
|
ArgumentOutOfRangeException.ThrowIfNegative(index);
|
||||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, plan.Count);
|
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, plan.Count);
|
||||||
if (plan[index].Kind == ScheduleItemKind.News)
|
if (plan[index].Kind == ScheduleItemKind.News)
|
||||||
throw new ScheduleException("News cannot be replaced.");
|
throw new ScheduleException("Nachrichten können nicht ersetzt werden.");
|
||||||
if (requested.Duration <= TimeSpan.Zero)
|
if (requested.Duration <= TimeSpan.Zero)
|
||||||
throw new ScheduleException("The requested song has no duration.");
|
throw new ScheduleException("Der gewĂĽnschte Song hat keine Dauer.");
|
||||||
|
|
||||||
var slotStartIndex = LastIndexOf(plan, index, ScheduleItemKind.News); // -1 if the plan does not start with news
|
var slotStartIndex = LastIndexOf(plan, index, ScheduleItemKind.News); // -1 if the plan does not start with news
|
||||||
var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News);
|
var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News);
|
||||||
@@ -96,27 +140,20 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
|
|||||||
|
|
||||||
if (requested.Duration > length)
|
if (requested.Duration > length)
|
||||||
throw new ScheduleException(
|
throw new ScheduleException(
|
||||||
$"\"{requested.Title}\" ({requested.Duration:m\\:ss}) does not fit before the news at {slotEnd:HH:mm}; only {length:m\\:ss} are left. Choose an earlier item.");
|
$"\"{requested.Title}\" ({requested.Duration:m\\:ss}) passt nicht vor die Nachrichten um {slotEnd:HH:mm}; es sind nur noch {length:m\\:ss} übrig. Ein früheres Element wählen.");
|
||||||
|
|
||||||
|
// What the slot has already spent on ads and moderator talk before the request counts against its targets.
|
||||||
|
var options = Options;
|
||||||
var prefix = plan.Take(index).ToList();
|
var prefix = plan.Take(index).ToList();
|
||||||
var prefixFiller = Sum(prefix.Skip(slotStartIndex + 1).Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator));
|
var slotPrefix = prefix.Skip(slotStartIndex + 1).ToList();
|
||||||
var maxGap = options.MaxFillerPerHour / 2 - prefixFiller;
|
var adTarget = Max(options.AdsPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Ad)), TimeSpan.Zero);
|
||||||
|
var moderatorTarget = Max(options.ModeratorPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Moderator)), TimeSpan.Zero);
|
||||||
var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList();
|
var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList();
|
||||||
var startWithAd = prefix.Count == 0 || prefix[^1].Kind != ScheduleItemKind.Ad;
|
|
||||||
|
|
||||||
for (var attempt = 0; attempt < options.Attempts; attempt++)
|
var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested);
|
||||||
{
|
var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget);
|
||||||
List<Song> picked = [requested, .. PickSongs(length - requested.Duration, playable, requested)];
|
IEnumerable<ScheduleItem> rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex);
|
||||||
var gap = length - Sum(picked);
|
return [.. prefix, .. Arrange(options, start, picked, ads, moderator, keepFirstSongFirst: true), .. rest];
|
||||||
if (gap <= maxGap)
|
|
||||||
{
|
|
||||||
IEnumerable<ScheduleItem> rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex);
|
|
||||||
return [.. prefix, .. Arrange(start, picked, BuildFiller(gap, startWithAd)), .. rest];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new ScheduleException(
|
|
||||||
$"After \"{requested.Title}\" the slot up to {slotEnd:HH:mm} cannot be filled without exceeding the ad limit. Choose another item or song.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int IndexOf(IReadOnlyList<ScheduleItem> plan, int from, ScheduleItemKind kind)
|
private static int IndexOf(IReadOnlyList<ScheduleItem> plan, int from, ScheduleItemKind kind)
|
||||||
@@ -133,6 +170,27 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tries random song picks and keeps the one whose leftover time is closest to the target for ads and
|
||||||
|
// moderator talk. Picks never go over the music time, so the leftover is the target or more.
|
||||||
|
private (List<Song> Songs, TimeSpan Gap) PickBest(
|
||||||
|
ScheduleOptions options, TimeSpan length, TimeSpan target, List<Song> songs, Song? first = null)
|
||||||
|
{
|
||||||
|
var fixedTime = first?.Duration ?? TimeSpan.Zero;
|
||||||
|
var budget = Max(length - fixedTime - target, TimeSpan.Zero);
|
||||||
|
(List<Song> Songs, TimeSpan Gap)? best = null;
|
||||||
|
for (var attempt = 0; attempt < options.Attempts; attempt++)
|
||||||
|
{
|
||||||
|
var more = PickSongs(budget, songs, first);
|
||||||
|
List<Song> picked = first is null ? more : [first, .. more];
|
||||||
|
var gap = length - Sum(picked);
|
||||||
|
if (best is null || gap < best.Value.Gap)
|
||||||
|
best = (picked, gap);
|
||||||
|
if (gap - target <= CloseEnough || budget == TimeSpan.Zero)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return best ?? ([], length);
|
||||||
|
}
|
||||||
|
|
||||||
private List<Song> PickSongs(TimeSpan budget, List<Song> songs, Song? previous = null)
|
private List<Song> PickSongs(TimeSpan budget, List<Song> songs, Song? previous = null)
|
||||||
{
|
{
|
||||||
var picked = new List<Song>();
|
var picked = new List<Song>();
|
||||||
@@ -149,52 +207,95 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Alternates ad and moderator items, so ads never run back to back.
|
// Shares the leftover time between ads and moderator talk in the ratio of their targets.
|
||||||
private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap, bool startWithAd = true)
|
private static (TimeSpan Ads, TimeSpan Moderator) Split(ScheduleOptions options, TimeSpan gap, TimeSpan adTarget, TimeSpan moderatorTarget)
|
||||||
{
|
{
|
||||||
var filler = new List<(ScheduleItemKind, string, TimeSpan)>();
|
if (adTarget + moderatorTarget <= TimeSpan.Zero)
|
||||||
var nextIsAd = startWithAd;
|
|
||||||
while (gap > TimeSpan.Zero)
|
|
||||||
{
|
{
|
||||||
(ScheduleItemKind kind, string title, TimeSpan duration) = nextIsAd
|
// This slot has nothing left to aim for; fall back to the hourly ratio, or to talk alone.
|
||||||
? Pick(PlaceholderContent.AdSpots, a => (ScheduleItemKind.Ad, a.Title, Min(a.Duration, options.MaxAdBlock)))
|
adTarget = options.AdsPerHour;
|
||||||
: Pick(PlaceholderContent.ModeratorSegments, m => (ScheduleItemKind.Moderator, m.Title, m.Duration));
|
moderatorTarget = options.ModeratorPerHour;
|
||||||
duration = Min(duration, gap); // shortcut: the last placeholder is cut to fit; fine while they have no audio
|
if (adTarget + moderatorTarget <= TimeSpan.Zero)
|
||||||
filler.Add((kind, title, duration));
|
return (TimeSpan.Zero, gap);
|
||||||
gap -= duration;
|
|
||||||
nextIsAd = !nextIsAd;
|
|
||||||
}
|
}
|
||||||
return filler;
|
var ads = TimeSpan.FromSeconds(Math.Round(gap.TotalSeconds * (adTarget / (adTarget + moderatorTarget))));
|
||||||
|
ads = Min(ads, gap);
|
||||||
|
return (ads, gap - ads);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Spreads the filler between songs; the slot always ends with a song.
|
// Lays out the slot: songs with breaks in between, each break "moderator, ad, moderator, ad ...".
|
||||||
private static List<ScheduleItem> Arrange(DateTime start, List<Song> songs, List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> filler)
|
// Ads are cut into pieces of at most MaxAdBlock and never follow each other directly as long as there
|
||||||
|
// is moderator talk or a song to put between them. The slot always ends with a song.
|
||||||
|
private static List<ScheduleItem> Arrange(
|
||||||
|
ScheduleOptions options, DateTime start, List<Song> songs, TimeSpan ads, TimeSpan moderator, bool keepFirstSongFirst)
|
||||||
{
|
{
|
||||||
|
var adPieces = Pieces(ads, (int)Math.Ceiling(ads / options.MaxAdBlock));
|
||||||
|
// One moderator piece in front of every ad piece; without ads, one piece per five minutes of talk.
|
||||||
|
var moderatorPieces = Pieces(moderator, adPieces.Count > 0 ? adPieces.Count : (int)Math.Ceiling(moderator / TimeSpan.FromMinutes(5)));
|
||||||
|
var pairs = Math.Max(adPieces.Count, moderatorPieces.Count);
|
||||||
|
|
||||||
|
// A hot swap keeps the requested song at its position, so breaks start after it when another song follows.
|
||||||
|
var firstBreakSong = keepFirstSongFirst && songs.Count > 1 ? 1 : 0;
|
||||||
|
var breakSlots = Math.Max(songs.Count - firstBreakSong, 1);
|
||||||
|
var breaks = Math.Min(pairs, breakSlots);
|
||||||
|
|
||||||
var items = new List<ScheduleItem>();
|
var items = new List<ScheduleItem>();
|
||||||
var time = start;
|
var time = start;
|
||||||
var fillerIndex = 0;
|
void Add(ScheduleItemKind kind, TimeSpan duration, Song? song = null)
|
||||||
|
{
|
||||||
|
if (duration <= TimeSpan.Zero)
|
||||||
|
return;
|
||||||
|
// News, ads and moderator items start without a title; the user can name them in the timeline.
|
||||||
|
var title = song is null ? "" : string.IsNullOrWhiteSpace(song.Artist) ? song.Title : $"{song.Artist} - {song.Title}";
|
||||||
|
items.Add(new ScheduleItem(kind, title, time, duration, song));
|
||||||
|
time += duration;
|
||||||
|
}
|
||||||
|
|
||||||
|
var pair = 0;
|
||||||
|
void AddBreak(int number)
|
||||||
|
{
|
||||||
|
// Pairs are dealt out evenly; the last break takes what is left.
|
||||||
|
var until = number == breaks - 1 ? pairs : pairs * (number + 1) / breaks;
|
||||||
|
for (; pair < until; pair++)
|
||||||
|
{
|
||||||
|
if (pair < moderatorPieces.Count) Add(ScheduleItemKind.Moderator, moderatorPieces[pair]);
|
||||||
|
if (pair < adPieces.Count) Add(ScheduleItemKind.Ad, adPieces[pair]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var nextBreak = 0;
|
||||||
for (var i = 0; i < songs.Count; i++)
|
for (var i = 0; i < songs.Count; i++)
|
||||||
{
|
{
|
||||||
// Filler goes before song i; the share grows with i so it ends up spread over the slot.
|
// Break n sits before the song at its share of the way through the slot.
|
||||||
var until = filler.Count * (i + 1) / songs.Count;
|
while (nextBreak < breaks && i == firstBreakSong + nextBreak * breakSlots / breaks)
|
||||||
for (; fillerIndex < until; fillerIndex++)
|
AddBreak(nextBreak++);
|
||||||
{
|
Add(ScheduleItemKind.Song, songs[i].Duration, songs[i]);
|
||||||
var f = filler[fillerIndex];
|
|
||||||
items.Add(new ScheduleItem(f.Kind, f.Title, time, f.Duration));
|
|
||||||
time += f.Duration;
|
|
||||||
}
|
|
||||||
var title = string.IsNullOrWhiteSpace(songs[i].Artist) ? songs[i].Title : $"{songs[i].Artist} - {songs[i].Title}";
|
|
||||||
items.Add(new ScheduleItem(ScheduleItemKind.Song, title, time, songs[i].Duration, songs[i]));
|
|
||||||
time += songs[i].Duration;
|
|
||||||
}
|
}
|
||||||
|
// No songs at all: the slot is ads and talk only.
|
||||||
|
while (nextBreak < breaks)
|
||||||
|
AddBreak(nextBreak++);
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
private T Pick<TSource, T>(IReadOnlyList<TSource> source, Func<TSource, T> map) => map(source[random.Next(source.Count)]);
|
// Cuts a time into pieces of whole seconds that differ by at most one second, so no piece grows past
|
||||||
|
// the limit the count was chosen for. A fraction of a second goes to the last piece.
|
||||||
|
private static List<TimeSpan> Pieces(TimeSpan total, int count)
|
||||||
|
{
|
||||||
|
var pieces = new List<TimeSpan>();
|
||||||
|
if (total <= TimeSpan.Zero || count < 1)
|
||||||
|
return pieces;
|
||||||
|
var seconds = (long)Math.Floor(total.TotalSeconds);
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
pieces.Add(TimeSpan.FromSeconds(seconds / count + (i < seconds % count ? 1 : 0)));
|
||||||
|
pieces[^1] += total - TimeSpan.FromSeconds(seconds);
|
||||||
|
return pieces;
|
||||||
|
}
|
||||||
|
|
||||||
private static TimeSpan Sum(IEnumerable<Song> songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration);
|
private static TimeSpan Sum(IEnumerable<Song> songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration);
|
||||||
|
|
||||||
private static TimeSpan Sum(IEnumerable<ScheduleItem> items) => items.Aggregate(TimeSpan.Zero, (total, i) => total + i.Duration);
|
private static TimeSpan Sum(IEnumerable<ScheduleItem> items) => items.Aggregate(TimeSpan.Zero, (total, i) => total + i.Duration);
|
||||||
|
|
||||||
private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
|
private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
|
||||||
|
|
||||||
|
private static TimeSpan Max(TimeSpan a, TimeSpan b) => a > b ? a : b;
|
||||||
}
|
}
|
||||||
@@ -19,7 +19,7 @@ public class SongImportService(SongRepository songs, string musicDirectory)
|
|||||||
public Song Import(string sourcePath)
|
public Song Import(string sourcePath)
|
||||||
{
|
{
|
||||||
if (!SupportedExtensions.Contains(Path.GetExtension(sourcePath).ToLowerInvariant()))
|
if (!SupportedExtensions.Contains(Path.GetExtension(sourcePath).ToLowerInvariant()))
|
||||||
throw new SongImportException("Only MP3 and WAV files are supported.");
|
throw new SongImportException("Nur MP3- und WAV-Dateien werden unterstĂĽtzt.");
|
||||||
|
|
||||||
Directory.CreateDirectory(musicDirectory);
|
Directory.CreateDirectory(musicDirectory);
|
||||||
var targetPath = GetUniqueTargetPath(Path.GetFileName(sourcePath));
|
var targetPath = GetUniqueTargetPath(Path.GetFileName(sourcePath));
|
||||||
@@ -29,7 +29,7 @@ public class SongImportService(SongRepository songs, string musicDirectory)
|
|||||||
}
|
}
|
||||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||||
{
|
{
|
||||||
throw new SongImportException($"The file could not be read: {e.Message}", e);
|
throw new SongImportException($"Die Datei konnte nicht gelesen werden: {e.Message}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -75,11 +75,11 @@ public class SongImportService(SongRepository songs, string musicDirectory)
|
|||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// NAudio and Media Foundation throw many unrelated exception types for corrupt files.
|
// NAudio and Media Foundation throw many unrelated exception types for corrupt files.
|
||||||
throw new SongImportException("The file is not a readable MP3 or WAV file.", e);
|
throw new SongImportException("Die Datei ist keine lesbare MP3- oder WAV-Datei.", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (duration <= TimeSpan.Zero)
|
if (duration <= TimeSpan.Zero)
|
||||||
throw new SongImportException("The file contains no audio.");
|
throw new SongImportException("Die Datei enthält kein Audio.");
|
||||||
return duration;
|
return duration;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Data;
|
||||||
|
using System.Windows.Media;
|
||||||
|
|
||||||
|
namespace Radiosender.Views;
|
||||||
|
|
||||||
|
/// <summary>Sizes the text columns of a list so that every row can be read in full.</summary>
|
||||||
|
public static class GridColumns
|
||||||
|
{
|
||||||
|
// Cell padding on both sides plus a little air, so the text never touches the next column.
|
||||||
|
private const double Slack = 28;
|
||||||
|
|
||||||
|
// Rows use this size when no row exists yet to ask.
|
||||||
|
private const double DefaultFontSize = 14;
|
||||||
|
|
||||||
|
// The width from the XAML stays the minimum, so an empty or short list keeps its designed look.
|
||||||
|
private static readonly ConditionalWeakTable<GridViewColumn, object> MinWidths = [];
|
||||||
|
|
||||||
|
// Laying out text is the slow part and the same titles come up on every refresh, so widths are remembered.
|
||||||
|
// All lists share one font. shortcut: never trimmed; clear it if libraries reach hundreds of thousands of songs.
|
||||||
|
private static readonly Dictionary<string, double> TextWidths = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Widens each column with a <see cref="GridViewColumn.DisplayMemberBinding"/> to its longest text over
|
||||||
|
/// all rows, not only the visible ones: the lists are virtualized, so the built-in auto width would miss
|
||||||
|
/// rows that are scrolled out of view. Columns with a cell template keep their width, and so do columns
|
||||||
|
/// with a string format: those show times, which always have the same length.
|
||||||
|
/// </summary>
|
||||||
|
public static void Fit(ListView list)
|
||||||
|
{
|
||||||
|
if (list.View is not GridView view)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// The rows have their own font size, so a realized row is asked rather than the list.
|
||||||
|
var row = list.ItemContainerGenerator.ContainerFromIndex(0) as Control;
|
||||||
|
var typeface = new Typeface(row?.FontFamily ?? list.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
|
||||||
|
var fontSize = row?.FontSize ?? DefaultFontSize;
|
||||||
|
var pixelsPerDip = VisualTreeHelper.GetDpi(list).PixelsPerDip;
|
||||||
|
|
||||||
|
foreach (var column in view.Columns)
|
||||||
|
{
|
||||||
|
if (column.DisplayMemberBinding is not Binding { StringFormat: null, Path.Path: { } path })
|
||||||
|
continue;
|
||||||
|
var min = (double)MinWidths.GetValue(column, c => double.IsNaN(c.Width) ? 0d : c.Width);
|
||||||
|
var properties = path.Split('.');
|
||||||
|
|
||||||
|
var widest = 0d;
|
||||||
|
foreach (var item in list.Items)
|
||||||
|
{
|
||||||
|
var text = Text(item, properties);
|
||||||
|
if (text.Length == 0)
|
||||||
|
continue;
|
||||||
|
if (!TextWidths.TryGetValue(text, out var width))
|
||||||
|
{
|
||||||
|
width = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,
|
||||||
|
typeface, fontSize, Brushes.Black, pixelsPerDip).WidthIncludingTrailingWhitespace;
|
||||||
|
TextWidths[text] = width;
|
||||||
|
}
|
||||||
|
widest = Math.Max(widest, width);
|
||||||
|
}
|
||||||
|
|
||||||
|
var fitted = Math.Max(min, Math.Ceiling(widest + Slack));
|
||||||
|
if (column.Width != fitted) // setting it triggers a layout pass
|
||||||
|
column.Width = fitted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Follows a simple property path such as "Item.Title". A binding on a probe element would not do:
|
||||||
|
// it only resolves once the element is part of the window.
|
||||||
|
private static string Text(object? value, string[] properties)
|
||||||
|
{
|
||||||
|
foreach (var property in properties)
|
||||||
|
{
|
||||||
|
value = value?.GetType().GetProperty(property)?.GetValue(value);
|
||||||
|
if (value is null)
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return value?.ToString() ?? "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,21 +17,26 @@
|
|||||||
|
|
||||||
<ui:TitleBar Grid.Row="0" Title="Radiosender" />
|
<ui:TitleBar Grid.Row="0" Title="Radiosender" />
|
||||||
|
|
||||||
|
<!-- The navigation view wraps pages in its own scroll viewer, which gives a list unlimited height:
|
||||||
|
it then creates every row at once and each update takes seconds. The pages therefore set
|
||||||
|
ScrollViewer.CanContentScroll="False" and let their lists scroll themselves. -->
|
||||||
<ui:NavigationView x:Name="RootNavigation" Grid.Row="1" IsBackButtonVisible="Collapsed">
|
<ui:NavigationView x:Name="RootNavigation" Grid.Row="1" IsBackButtonVisible="Collapsed">
|
||||||
<ui:NavigationView.MenuItems>
|
<ui:NavigationView.MenuItems>
|
||||||
<ui:NavigationViewItem Content="Home"
|
<ui:NavigationViewItem Content="Sendeplan"
|
||||||
Icon="{ui:SymbolIcon Home24}"
|
|
||||||
TargetPageType="{x:Type pages:HomePage}" />
|
|
||||||
<ui:NavigationViewItem Content="Schedule"
|
|
||||||
Icon="{ui:SymbolIcon CalendarLtr24}"
|
Icon="{ui:SymbolIcon CalendarLtr24}"
|
||||||
TargetPageType="{x:Type pages:SchedulePage}" />
|
TargetPageType="{x:Type pages:SchedulePage}" />
|
||||||
<ui:NavigationViewItem Content="Library"
|
<ui:NavigationViewItem Content="Bibliothek"
|
||||||
Icon="{ui:SymbolIcon MusicNote224}"
|
Icon="{ui:SymbolIcon MusicNote224}"
|
||||||
TargetPageType="{x:Type pages:LibraryPage}" />
|
TargetPageType="{x:Type pages:LibraryPage}" />
|
||||||
<ui:NavigationViewItem Content="Import"
|
<ui:NavigationViewItem Content="Import"
|
||||||
Icon="{ui:SymbolIcon ArrowDownload24}"
|
Icon="{ui:SymbolIcon ArrowDownload24}"
|
||||||
TargetPageType="{x:Type pages:ImportPage}" />
|
TargetPageType="{x:Type pages:ImportPage}" />
|
||||||
</ui:NavigationView.MenuItems>
|
</ui:NavigationView.MenuItems>
|
||||||
|
<ui:NavigationView.FooterMenuItems>
|
||||||
|
<ui:NavigationViewItem Content="Einstellungen"
|
||||||
|
Icon="{ui:SymbolIcon Settings24}"
|
||||||
|
TargetPageType="{x:Type pages:SettingsPage}" />
|
||||||
|
</ui:NavigationView.FooterMenuItems>
|
||||||
</ui:NavigationView>
|
</ui:NavigationView>
|
||||||
</Grid>
|
</Grid>
|
||||||
</ui:FluentWindow>
|
</ui:FluentWindow>
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
using System.Windows.Threading;
|
||||||
|
using NAudio.Wave;
|
||||||
|
using NAudio.Wave.SampleProviders;
|
||||||
|
using Radiosender.Models;
|
||||||
using Radiosender.Views.Pages;
|
using Radiosender.Views.Pages;
|
||||||
using Wpf.Ui.Controls;
|
using Wpf.Ui.Controls;
|
||||||
|
|
||||||
@@ -5,9 +9,58 @@ namespace Radiosender.Views;
|
|||||||
|
|
||||||
public partial class MainWindow : FluentWindow
|
public partial class MainWindow : FluentWindow
|
||||||
{
|
{
|
||||||
|
private readonly DispatcherTimer _reminderTimer = new() { Interval = TimeSpan.FromSeconds(1) };
|
||||||
|
private DateTime _remindedFor;
|
||||||
|
|
||||||
public MainWindow()
|
public MainWindow()
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
Loaded += (_, _) => RootNavigation.Navigate(typeof(HomePage));
|
// Re-themes the app when the user switches the Windows theme while it runs.
|
||||||
|
Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this);
|
||||||
|
Loaded += (_, _) => RootNavigation.Navigate(typeof(SchedulePage));
|
||||||
|
_reminderTimer.Tick += (_, _) => RemindSpeaker();
|
||||||
|
_reminderTimer.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shortly before news or moderator talk goes on air, the person at the microphone gets a heads-up.
|
||||||
|
private void RemindSpeaker()
|
||||||
|
{
|
||||||
|
var settings = App.Settings;
|
||||||
|
TimeSpan? newsLead = settings.NewsAlert ? TimeSpan.FromSeconds(settings.NewsAlertSeconds) : null;
|
||||||
|
TimeSpan? moderatorLead = settings.ModeratorAlert ? TimeSpan.FromSeconds(settings.ModeratorAlertSeconds) : null;
|
||||||
|
if (App.Schedule.UpcomingSpeech(newsLead, moderatorLead) is not { } item || item.Start == _remindedFor)
|
||||||
|
return;
|
||||||
|
_remindedFor = item.Start; // once per item
|
||||||
|
var isNews = item.Kind == ScheduleItemKind.News;
|
||||||
|
var what = item.KindName;
|
||||||
|
if (isNews ? settings.NewsAlertSound : settings.ModeratorAlertSound)
|
||||||
|
PlayBing();
|
||||||
|
// A dialog in the middle of the screen that stays until OK is clicked; the broadcast keeps running behind it.
|
||||||
|
_ = new Wpf.Ui.Controls.MessageBox
|
||||||
|
{
|
||||||
|
Title = "Gleich bist du dran.",
|
||||||
|
Content = item.Title.Length > 0 ? $"{what} um {item.Start:HH:mm:ss}: {item.Title}" : $"{what} um {item.Start:HH:mm:ss}",
|
||||||
|
CloseButtonText = "OK",
|
||||||
|
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen,
|
||||||
|
Topmost = true,
|
||||||
|
}.ShowDialogAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
// A short generated tone on its own output, so it sounds over the running broadcast.
|
||||||
|
private static void PlayBing()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var tone = new SignalGenerator(44100, 1) { Type = SignalGeneratorType.Sin, Frequency = 880, Gain = 0.25 }
|
||||||
|
.Take(TimeSpan.FromMilliseconds(350));
|
||||||
|
var output = new WaveOut();
|
||||||
|
output.PlaybackStopped += (_, _) => output.Dispose();
|
||||||
|
output.Init(tone);
|
||||||
|
output.Play();
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is NAudio.MmException or InvalidOperationException)
|
||||||
|
{
|
||||||
|
// No audio device: the dialog still reminds the speaker.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<Page x:Class="Radiosender.Views.Pages.HomePage"
|
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
||||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
|
||||||
Title="Home">
|
|
||||||
<StackPanel Margin="24">
|
|
||||||
<ui:TextBlock FontTypography="Title" Text="Radiosender" />
|
|
||||||
<ui:TextBlock Margin="0,8,0,0" TextWrapping="Wrap"
|
|
||||||
Text="Add music on the Import page, then plan and start a broadcast on the Schedule page." />
|
|
||||||
</StackPanel>
|
|
||||||
</Page>
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
using System.Windows.Controls;
|
|
||||||
|
|
||||||
namespace Radiosender.Views.Pages;
|
|
||||||
|
|
||||||
public partial class HomePage : Page
|
|
||||||
{
|
|
||||||
public HomePage()
|
|
||||||
{
|
|
||||||
InitializeComponent();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,20 +3,19 @@
|
|||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||||
Title="Import"
|
Title="Import"
|
||||||
|
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||||
|
ScrollViewer.CanContentScroll="False"
|
||||||
Unloaded="OnUnloaded">
|
Unloaded="OnUnloaded">
|
||||||
<Grid Margin="24">
|
<Grid Margin="24">
|
||||||
<Grid.RowDefinitions>
|
<Grid.RowDefinitions>
|
||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
<RowDefinition Height="3*" MinHeight="260" />
|
<RowDefinition Height="*" MinHeight="260" />
|
||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
<RowDefinition Height="2*" MinHeight="120" />
|
|
||||||
</Grid.RowDefinitions>
|
</Grid.RowDefinitions>
|
||||||
|
|
||||||
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Import" />
|
<TabControl x:Name="Sources" Grid.Row="1">
|
||||||
|
|
||||||
<TabControl x:Name="Sources" Grid.Row="1" Margin="0,12,0,0">
|
|
||||||
<!-- From computer -->
|
<!-- From computer -->
|
||||||
<TabItem Header="From computer">
|
<TabItem Header="Vom Computer">
|
||||||
<Grid Margin="0,12,0,0">
|
<Grid Margin="0,12,0,0">
|
||||||
<Grid.RowDefinitions>
|
<Grid.RowDefinitions>
|
||||||
<RowDefinition Height="*" />
|
<RowDefinition Height="*" />
|
||||||
@@ -26,7 +25,7 @@
|
|||||||
<Grid x:Name="DropZone"
|
<Grid x:Name="DropZone"
|
||||||
Background="Transparent"
|
Background="Transparent"
|
||||||
AllowDrop="True"
|
AllowDrop="True"
|
||||||
AutomationProperties.Name="Drop zone for MP3 and WAV files"
|
AutomationProperties.Name="Ablagebereich fĂĽr MP3- und WAV-Dateien"
|
||||||
DragEnter="OnDragOver"
|
DragEnter="OnDragOver"
|
||||||
DragOver="OnDragOver"
|
DragOver="OnDragOver"
|
||||||
DragLeave="OnDragLeave"
|
DragLeave="OnDragLeave"
|
||||||
@@ -36,21 +35,17 @@
|
|||||||
RadiusY="8"
|
RadiusY="8"
|
||||||
StrokeThickness="2"
|
StrokeThickness="2"
|
||||||
StrokeDashArray="4 3"
|
StrokeDashArray="4 3"
|
||||||
Stroke="{DynamicResource TextFillColorTertiaryBrush}" />
|
Stroke="{DynamicResource ControlStrongStrokeColorDefaultBrush}" />
|
||||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
|
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||||
<ui:SymbolIcon HorizontalAlignment="Center" FontSize="40" Symbol="ArrowUpload24" />
|
<ui:SymbolIcon HorizontalAlignment="Center" FontSize="40" Symbol="ArrowUpload24" />
|
||||||
<ui:TextBlock Margin="0,8,0,0"
|
<ui:TextBlock Margin="0,8,0,12"
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
FontTypography="BodyStrong"
|
FontTypography="BodyStrong"
|
||||||
Text="Drop MP3 or WAV files here" />
|
Text="MP3- oder WAV-Dateien hier ablegen" />
|
||||||
<ui:TextBlock Margin="0,4,0,12"
|
|
||||||
HorizontalAlignment="Center"
|
|
||||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
|
||||||
Text="You can add several files at once." />
|
|
||||||
<ui:Button x:Name="ChooseFilesButton"
|
<ui:Button x:Name="ChooseFilesButton"
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
Appearance="Primary"
|
Appearance="Primary"
|
||||||
Content="Choose files..."
|
Content="Dateien auswählen..."
|
||||||
Icon="{ui:SymbolIcon FolderOpen24}"
|
Icon="{ui:SymbolIcon FolderOpen24}"
|
||||||
Click="OnChooseFiles" />
|
Click="OnChooseFiles" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
@@ -60,7 +55,7 @@
|
|||||||
<ui:TextBlock x:Name="UploadProgressText" />
|
<ui:TextBlock x:Name="UploadProgressText" />
|
||||||
<ProgressBar x:Name="UploadProgress"
|
<ProgressBar x:Name="UploadProgress"
|
||||||
Margin="0,6,0,0"
|
Margin="0,6,0,0"
|
||||||
AutomationProperties.Name="Upload progress" />
|
AutomationProperties.Name="Import-Fortschritt" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
</TabItem>
|
</TabItem>
|
||||||
@@ -81,14 +76,14 @@
|
|||||||
<ColumnDefinition Width="Auto" />
|
<ColumnDefinition Width="Auto" />
|
||||||
</Grid.ColumnDefinitions>
|
</Grid.ColumnDefinitions>
|
||||||
<ui:TextBox x:Name="QueryBox"
|
<ui:TextBox x:Name="QueryBox"
|
||||||
PlaceholderText="Search free audio, for example "jazz piano""
|
PlaceholderText="Freie Musik suchen, zum Beispiel "jazz piano""
|
||||||
AutomationProperties.Name="Search term"
|
AutomationProperties.Name="Suchbegriff"
|
||||||
KeyDown="OnQueryKeyDown" />
|
KeyDown="OnQueryKeyDown" />
|
||||||
<ui:Button x:Name="SearchButton"
|
<ui:Button x:Name="SearchButton"
|
||||||
Grid.Column="1"
|
Grid.Column="1"
|
||||||
Margin="8,0,0,0"
|
Margin="8,0,0,0"
|
||||||
Appearance="Primary"
|
Appearance="Primary"
|
||||||
Content="Search"
|
Content="Suchen"
|
||||||
Icon="{ui:SymbolIcon Search24}"
|
Icon="{ui:SymbolIcon Search24}"
|
||||||
Click="OnSearch" />
|
Click="OnSearch" />
|
||||||
</Grid>
|
</Grid>
|
||||||
@@ -98,34 +93,25 @@
|
|||||||
<ui:ListView x:Name="Results"
|
<ui:ListView x:Name="Results"
|
||||||
Grid.Row="2"
|
Grid.Row="2"
|
||||||
Margin="0,12,0,0"
|
Margin="0,12,0,0"
|
||||||
SelectionMode="Single"
|
SelectionMode="Extended"
|
||||||
AutomationProperties.Name="Search results"
|
AutomationProperties.Name="Suchergebnisse"
|
||||||
SelectionChanged="OnSelectionChanged"
|
SelectionChanged="OnSelectionChanged"
|
||||||
MouseDoubleClick="OnResultDoubleClick">
|
MouseDoubleClick="OnResultDoubleClick">
|
||||||
<ui:ListView.View>
|
<ui:ListView.View>
|
||||||
<ui:GridView>
|
<ui:GridView>
|
||||||
<ui:GridViewColumn Width="300" Header="Title" DisplayMemberBinding="{Binding Track.Title}" />
|
<ui:GridViewColumn Width="300" Header="Titel" DisplayMemberBinding="{Binding Track.Title}" />
|
||||||
<ui:GridViewColumn Width="180" Header="Creator" DisplayMemberBinding="{Binding Track.Creator}" />
|
<ui:GridViewColumn Width="180" Header="Urheber" DisplayMemberBinding="{Binding Track.Creator}" />
|
||||||
<ui:GridViewColumn Width="80" Header="Duration" DisplayMemberBinding="{Binding Track.DurationText}" />
|
<ui:GridViewColumn Width="80" Header="Dauer" DisplayMemberBinding="{Binding Track.DurationText}" />
|
||||||
<ui:GridViewColumn Width="130" Header="License" DisplayMemberBinding="{Binding Track.LicenseName}" />
|
<ui:GridViewColumn Width="130" Header="Lizenz" DisplayMemberBinding="{Binding Track.LicenseName}" />
|
||||||
<ui:GridViewColumn Width="150" Header="Status">
|
|
||||||
<ui:GridViewColumn.CellTemplate>
|
|
||||||
<DataTemplate>
|
|
||||||
<ui:TextBlock Text="{Binding Status}" Foreground="{DynamicResource TextFillColorSecondaryBrush}" />
|
|
||||||
</DataTemplate>
|
|
||||||
</ui:GridViewColumn.CellTemplate>
|
|
||||||
</ui:GridViewColumn>
|
|
||||||
</ui:GridView>
|
</ui:GridView>
|
||||||
</ui:ListView.View>
|
</ui:ListView.View>
|
||||||
</ui:ListView>
|
</ui:ListView>
|
||||||
|
|
||||||
<StackPanel Grid.Row="3" Margin="0,12,0,0" Orientation="Horizontal">
|
<StackPanel Grid.Row="3" Margin="0,12,0,0" Orientation="Horizontal">
|
||||||
<ui:Button x:Name="PreviewButton" Content="Preview" Icon="{ui:SymbolIcon Play24}"
|
<ui:Button x:Name="PreviewButton" MinWidth="110" Content="Vorhören" Icon="{ui:SymbolIcon Play24}"
|
||||||
IsEnabled="False" Click="OnPreview" />
|
IsEnabled="False" Click="OnPreview" />
|
||||||
<ui:Button x:Name="StopButton" Margin="8,0,0,0" Content="Stop" Icon="{ui:SymbolIcon Stop24}"
|
<ui:Button x:Name="ImportButton" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0" Appearance="Primary"
|
||||||
IsEnabled="False" Click="OnStop" />
|
Content="In Bibliothek importieren" Icon="{ui:SymbolIcon ArrowDownload24}"
|
||||||
<ui:Button x:Name="ImportButton" Margin="8,0,0,0" Appearance="Primary"
|
|
||||||
Content="Import to library" Icon="{ui:SymbolIcon ArrowDownload24}"
|
|
||||||
IsEnabled="False" Click="OnImport" />
|
IsEnabled="False" Click="OnImport" />
|
||||||
<ui:ProgressRing x:Name="Busy"
|
<ui:ProgressRing x:Name="Busy"
|
||||||
Width="20"
|
Width="20"
|
||||||
@@ -142,57 +128,51 @@
|
|||||||
</TabItem>
|
</TabItem>
|
||||||
</TabControl>
|
</TabControl>
|
||||||
|
|
||||||
<!-- Added in this session, from both sources -->
|
<!-- Results of this session from both sources; hidden until something was imported. -->
|
||||||
<Grid Grid.Row="2" Margin="0,16,0,0">
|
<Grid x:Name="SessionPanel" Grid.Row="2" Margin="0,16,0,0" Visibility="Collapsed">
|
||||||
<ui:TextBlock VerticalAlignment="Center" FontTypography="Subtitle" Text="Added in this session" />
|
<Grid.RowDefinitions>
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
<ui:TextBlock VerticalAlignment="Center" FontTypography="BodyStrong" Text="Importiert" />
|
||||||
<ui:Button HorizontalAlignment="Right"
|
<ui:Button HorizontalAlignment="Right"
|
||||||
Appearance="Transparent"
|
Appearance="Transparent"
|
||||||
Content="Open library"
|
Content="Bibliothek öffnen"
|
||||||
Icon="{ui:SymbolIcon MusicNote224}"
|
Icon="{ui:SymbolIcon MusicNote224}"
|
||||||
Click="OnOpenLibrary" />
|
Click="OnOpenLibrary" />
|
||||||
|
<ui:ListView x:Name="Session"
|
||||||
|
Grid.Row="1"
|
||||||
|
MaxHeight="200"
|
||||||
|
Margin="0,8,0,0"
|
||||||
|
AutomationProperties.Name="In dieser Sitzung importierte Songs">
|
||||||
|
<ui:ListView.View>
|
||||||
|
<ui:GridView>
|
||||||
|
<ui:GridViewColumn Width="160" Header="Status">
|
||||||
|
<ui:GridViewColumn.CellTemplate>
|
||||||
|
<DataTemplate>
|
||||||
|
<StackPanel Orientation="Horizontal">
|
||||||
|
<ui:SymbolIcon x:Name="Icon"
|
||||||
|
Symbol="CheckmarkCircle24"
|
||||||
|
Filled="True"
|
||||||
|
Foreground="{DynamicResource SystemFillColorSuccessBrush}" />
|
||||||
|
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="HinzugefĂĽgt" />
|
||||||
|
</StackPanel>
|
||||||
|
<DataTemplate.Triggers>
|
||||||
|
<DataTrigger Binding="{Binding Success}" Value="False">
|
||||||
|
<Setter TargetName="Icon" Property="Symbol" Value="ErrorCircle24" />
|
||||||
|
<Setter TargetName="Icon" Property="Foreground" Value="{DynamicResource SystemFillColorCriticalBrush}" />
|
||||||
|
<Setter TargetName="Label" Property="Text" Value="Fehlgeschlagen" />
|
||||||
|
</DataTrigger>
|
||||||
|
</DataTemplate.Triggers>
|
||||||
|
</DataTemplate>
|
||||||
|
</ui:GridViewColumn.CellTemplate>
|
||||||
|
</ui:GridViewColumn>
|
||||||
|
<ui:GridViewColumn Width="240" Header="Titel" DisplayMemberBinding="{Binding Title}" />
|
||||||
|
<ui:GridViewColumn Width="160" Header="Interpret" DisplayMemberBinding="{Binding Artist}" />
|
||||||
|
<ui:GridViewColumn Width="320" Header="Details" DisplayMemberBinding="{Binding Details}" />
|
||||||
|
</ui:GridView>
|
||||||
|
</ui:ListView.View>
|
||||||
|
</ui:ListView>
|
||||||
</Grid>
|
</Grid>
|
||||||
|
|
||||||
<ui:ListView x:Name="Session"
|
|
||||||
Grid.Row="3"
|
|
||||||
Margin="0,8,0,0"
|
|
||||||
AutomationProperties.Name="Songs added in this session">
|
|
||||||
<ui:ListView.View>
|
|
||||||
<ui:GridView>
|
|
||||||
<ui:GridViewColumn Width="110" Header="Status">
|
|
||||||
<ui:GridViewColumn.CellTemplate>
|
|
||||||
<DataTemplate>
|
|
||||||
<StackPanel Orientation="Horizontal">
|
|
||||||
<ui:SymbolIcon x:Name="Icon"
|
|
||||||
Symbol="CheckmarkCircle24"
|
|
||||||
Filled="True"
|
|
||||||
Foreground="{DynamicResource SystemFillColorSuccessBrush}" />
|
|
||||||
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="Added" />
|
|
||||||
</StackPanel>
|
|
||||||
<DataTemplate.Triggers>
|
|
||||||
<DataTrigger Binding="{Binding Success}" Value="False">
|
|
||||||
<Setter TargetName="Icon" Property="Symbol" Value="ErrorCircle24" />
|
|
||||||
<Setter TargetName="Icon" Property="Foreground" Value="{DynamicResource SystemFillColorCriticalBrush}" />
|
|
||||||
<Setter TargetName="Label" Property="Text" Value="Failed" />
|
|
||||||
</DataTrigger>
|
|
||||||
</DataTemplate.Triggers>
|
|
||||||
</DataTemplate>
|
|
||||||
</ui:GridViewColumn.CellTemplate>
|
|
||||||
</ui:GridViewColumn>
|
|
||||||
<ui:GridViewColumn Width="240" Header="Title" DisplayMemberBinding="{Binding Title}" />
|
|
||||||
<ui:GridViewColumn Width="160" Header="Artist" DisplayMemberBinding="{Binding Artist}" />
|
|
||||||
<ui:GridViewColumn Width="80" Header="Duration" DisplayMemberBinding="{Binding Duration}" />
|
|
||||||
<ui:GridViewColumn Width="100" Header="Source" DisplayMemberBinding="{Binding Source}" />
|
|
||||||
<ui:GridViewColumn Width="320" Header="Details" DisplayMemberBinding="{Binding Details}" />
|
|
||||||
</ui:GridView>
|
|
||||||
</ui:ListView.View>
|
|
||||||
</ui:ListView>
|
|
||||||
|
|
||||||
<ui:TextBlock x:Name="SessionEmpty"
|
|
||||||
Grid.Row="3"
|
|
||||||
Margin="0,32,0,0"
|
|
||||||
HorizontalAlignment="Center"
|
|
||||||
VerticalAlignment="Top"
|
|
||||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
|
||||||
Text="Songs you import appear here." />
|
|
||||||
</Grid>
|
</Grid>
|
||||||
</Page>
|
</Page>
|
||||||
@@ -3,8 +3,8 @@ using System.IO;
|
|||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Controls;
|
using System.Windows.Controls;
|
||||||
using System.Windows.Input;
|
using System.Windows.Input;
|
||||||
using System.Windows.Media;
|
|
||||||
using Microsoft.Win32;
|
using Microsoft.Win32;
|
||||||
|
using NAudio.Wave;
|
||||||
using Radiosender.Controllers;
|
using Radiosender.Controllers;
|
||||||
using Radiosender.Models;
|
using Radiosender.Models;
|
||||||
using Radiosender.Services;
|
using Radiosender.Services;
|
||||||
@@ -23,21 +23,22 @@ public partial class ImportPage : Page
|
|||||||
new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory));
|
new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory));
|
||||||
|
|
||||||
private readonly ObservableCollection<SessionRow> _session = [];
|
private readonly ObservableCollection<SessionRow> _session = [];
|
||||||
private readonly MediaPlayer _preview = new();
|
// Preview has its own output, so it never interrupts a running broadcast.
|
||||||
|
private WaveOut? _previewOutput;
|
||||||
|
private MediaFoundationReader? _previewReader;
|
||||||
|
private int _previewId; // changes on every start and stop; a late callback with an old id is ignored
|
||||||
private bool _uploading;
|
private bool _uploading;
|
||||||
private bool _busy;
|
private bool _busy;
|
||||||
|
private bool _previewing;
|
||||||
|
|
||||||
public ImportPage()
|
public ImportPage()
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
Session.ItemsSource = _session;
|
Session.ItemsSource = _session;
|
||||||
_session.CollectionChanged += (_, _) =>
|
_session.CollectionChanged += (_, _) =>
|
||||||
SessionEmpty.Visibility = _session.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
|
|
||||||
_preview.MediaEnded += (_, _) => OnStop(this, new RoutedEventArgs());
|
|
||||||
_preview.MediaFailed += (_, e) =>
|
|
||||||
{
|
{
|
||||||
OnStop(this, new RoutedEventArgs());
|
SessionPanel.Visibility = _session.Count == 0 ? Visibility.Collapsed : Visibility.Visible;
|
||||||
Show(InfoBarSeverity.Error, "Preview failed", e.ErrorException.Message);
|
GridColumns.Fit(Session);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,12 +55,12 @@ public partial class ImportPage : Page
|
|||||||
{
|
{
|
||||||
var ok = !_uploading && e.Data.GetDataPresent(DataFormats.FileDrop);
|
var ok = !_uploading && e.Data.GetDataPresent(DataFormats.FileDrop);
|
||||||
e.Effects = ok ? DragDropEffects.Copy : DragDropEffects.None;
|
e.Effects = ok ? DragDropEffects.Copy : DragDropEffects.None;
|
||||||
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, ok ? "AccentTextFillColorPrimaryBrush" : "TextFillColorTertiaryBrush");
|
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, ok ? "AccentTextFillColorPrimaryBrush" : "ControlStrongStrokeColorDefaultBrush");
|
||||||
e.Handled = true;
|
e.Handled = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDragLeave(object sender, DragEventArgs e) =>
|
private void OnDragLeave(object sender, DragEventArgs e) =>
|
||||||
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextFillColorTertiaryBrush");
|
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "ControlStrongStrokeColorDefaultBrush");
|
||||||
|
|
||||||
private async void OnDrop(object sender, DragEventArgs e)
|
private async void OnDrop(object sender, DragEventArgs e)
|
||||||
{
|
{
|
||||||
@@ -82,11 +83,11 @@ public partial class ImportPage : Page
|
|||||||
{
|
{
|
||||||
var path = paths[i];
|
var path = paths[i];
|
||||||
UploadProgress.Value = i;
|
UploadProgress.Value = i;
|
||||||
UploadProgressText.Text = $"Importing {i + 1} of {paths.Count}: {Path.GetFileName(path)}";
|
UploadProgressText.Text = $"Importiere {i + 1} von {paths.Count}: {Path.GetFileName(path)}";
|
||||||
var result = await Task.Run(() => _upload.Upload(path));
|
var result = await Task.Run(() => _upload.Upload(path));
|
||||||
_session.Insert(0, result.Song is { } song
|
_session.Insert(0, result.Song is { } song
|
||||||
? SessionRow.Added(song, "Upload", Path.GetFileName(path))
|
? SessionRow.Added(song, Path.GetFileName(path))
|
||||||
: SessionRow.Failed(Path.GetFileName(path), "Upload", result.Message));
|
: SessionRow.Failed(Path.GetFileName(path), result.Message));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@@ -113,19 +114,20 @@ public partial class ImportPage : Page
|
|||||||
if (query.Length == 0 || _busy)
|
if (query.Length == 0 || _busy)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
SetBusy($"Searching Openverse for \"{query}\"...");
|
SetBusy($"Suche auf Openverse nach \"{query}\"...");
|
||||||
Message.IsOpen = false;
|
Message.IsOpen = false;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var tracks = await Openverse.SearchAsync(query);
|
var tracks = await Openverse.SearchAsync(query);
|
||||||
var imported = Openverse.ImportedIds();
|
var imported = Openverse.ImportedIds();
|
||||||
Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList();
|
Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList();
|
||||||
|
GridColumns.Fit(Results);
|
||||||
if (tracks.Count == 0)
|
if (tracks.Count == 0)
|
||||||
Show(InfoBarSeverity.Informational, "No results", $"Openverse found no audio for \"{query}\".");
|
Show(InfoBarSeverity.Informational, "Keine Ergebnisse", $"Openverse hat nichts zu \"{query}\" gefunden.");
|
||||||
}
|
}
|
||||||
catch (OpenverseException ex)
|
catch (OpenverseException ex)
|
||||||
{
|
{
|
||||||
Show(InfoBarSeverity.Error, "Search failed", ex.Message);
|
Show(InfoBarSeverity.Error, "Suche fehlgeschlagen", ex.Message);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -133,46 +135,120 @@ public partial class ImportPage : Page
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnPreview(object sender, RoutedEventArgs e)
|
// One button: starts the preview, or stops the running one.
|
||||||
|
// NAudio, not WPF's MediaPlayer: that one cannot open https URLs.
|
||||||
|
private async void OnPreview(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
|
if (_previewing)
|
||||||
|
{
|
||||||
|
OnStop(sender, e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (Selected is not { } row || !Uri.TryCreate(row.Track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
|
if (Selected is not { } row || !Uri.TryCreate(row.Track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
|
||||||
return;
|
return;
|
||||||
_preview.Open(uri); // streams the file, nothing is saved
|
SetPreviewing(true);
|
||||||
_preview.Play();
|
Message.IsOpen = false;
|
||||||
StopButton.IsEnabled = true;
|
var id = ++_previewId;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Connects to the server, so it runs off the UI thread. The file is streamed, nothing is saved.
|
||||||
|
var reader = await Task.Run(() => new MediaFoundationReader(uri.AbsoluteUri));
|
||||||
|
if (id != _previewId) // stopped or page left in the meantime
|
||||||
|
{
|
||||||
|
reader.Dispose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_previewReader = reader;
|
||||||
|
_previewOutput = new WaveOut();
|
||||||
|
_previewOutput.PlaybackStopped += (_, stopped) => Dispatcher.BeginInvoke(() =>
|
||||||
|
{
|
||||||
|
if (id != _previewId) return;
|
||||||
|
OnStop(this, new RoutedEventArgs());
|
||||||
|
if (stopped.Exception is { } error)
|
||||||
|
Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", error.Message);
|
||||||
|
});
|
||||||
|
_previewOutput.Init(reader);
|
||||||
|
_previewOutput.Play();
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||||
|
{
|
||||||
|
if (id != _previewId) return;
|
||||||
|
OnStop(this, new RoutedEventArgs());
|
||||||
|
Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetPreviewing(bool on)
|
||||||
|
{
|
||||||
|
_previewing = on;
|
||||||
|
PreviewButton.Content = on ? "Stopp" : "Vorhören";
|
||||||
|
PreviewButton.Icon = new SymbolIcon(on ? SymbolRegular.Stop24 : SymbolRegular.Play24);
|
||||||
|
UpdateButtons();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnStop(object sender, RoutedEventArgs e)
|
private void OnStop(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
_preview.Stop();
|
_previewId++;
|
||||||
_preview.Close();
|
var output = _previewOutput;
|
||||||
StopButton.IsEnabled = false;
|
var reader = _previewReader;
|
||||||
|
_previewOutput = null;
|
||||||
|
_previewReader = null;
|
||||||
|
SetPreviewing(false);
|
||||||
|
// Disposing waits for the audio thread, which can sit in a network read; not on the UI thread.
|
||||||
|
if (output is not null || reader is not null)
|
||||||
|
Task.Run(() =>
|
||||||
|
{
|
||||||
|
output?.Dispose();
|
||||||
|
reader?.Dispose();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
|
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
|
||||||
|
|
||||||
|
// Everything selected that can still be imported.
|
||||||
|
private List<ResultRow> Importable => Results.SelectedItems.OfType<ResultRow>().Where(r => r.CanImport).ToList();
|
||||||
|
|
||||||
|
// One after the other: Openverse limits anonymous requests, and each result shows up as soon as it is done.
|
||||||
private async void OnImport(object sender, RoutedEventArgs e)
|
private async void OnImport(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
if (Selected is not { CanImport: true } row || _busy)
|
var rows = Importable;
|
||||||
|
if (rows.Count == 0 || _busy)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
SetBusy($"Downloading \"{row.Track.Title}\"...");
|
|
||||||
Message.IsOpen = false;
|
Message.IsOpen = false;
|
||||||
|
var failed = 0;
|
||||||
|
var lastError = "";
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var song = await Openverse.ImportAsync(row.Track);
|
for (var i = 0; i < rows.Count; i++)
|
||||||
_session.Insert(0, SessionRow.Added(song, "Openverse", song.License ?? ""));
|
{
|
||||||
ReplaceRow(row, row with { Status = "In library", CanImport = false });
|
var row = rows[i];
|
||||||
}
|
SetBusy(rows.Count == 1
|
||||||
catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException)
|
? $"Lade \"{row.Track.Title}\" herunter..."
|
||||||
{
|
: $"Lade {i + 1} von {rows.Count} herunter: \"{row.Track.Title}\"...");
|
||||||
_session.Insert(0, SessionRow.Failed(row.Track.Title, "Openverse", ex.Message));
|
try
|
||||||
Show(InfoBarSeverity.Error, "Import failed", ex.Message);
|
{
|
||||||
|
var song = await Openverse.ImportAsync(row.Track);
|
||||||
|
_session.Insert(0, SessionRow.Added(song, song.License ?? ""));
|
||||||
|
ReplaceRow(row, row with { Status = "In Bibliothek", CanImport = false });
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException)
|
||||||
|
{
|
||||||
|
_session.Insert(0, SessionRow.Failed(row.Track.Title, ex.Message));
|
||||||
|
failed++;
|
||||||
|
lastError = ex.Message;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
SetBusy(null);
|
SetBusy(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (failed > 0)
|
||||||
|
Show(InfoBarSeverity.Error, "Import fehlgeschlagen", rows.Count == 1
|
||||||
|
? lastError
|
||||||
|
: $"{failed} von {rows.Count} Songs konnten nicht importiert werden. Die GrĂĽnde stehen in der Liste \"Importiert\".");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ReplaceRow(ResultRow old, ResultRow updated)
|
private void ReplaceRow(ResultRow old, ResultRow updated)
|
||||||
@@ -180,7 +256,6 @@ public partial class ImportPage : Page
|
|||||||
if (Results.ItemsSource is not List<ResultRow> rows || rows.IndexOf(old) is var i && i < 0) return;
|
if (Results.ItemsSource is not List<ResultRow> rows || rows.IndexOf(old) is var i && i < 0) return;
|
||||||
rows[i] = updated;
|
rows[i] = updated;
|
||||||
Results.Items.Refresh();
|
Results.Items.Refresh();
|
||||||
Results.SelectedIndex = i;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
||||||
@@ -196,8 +271,12 @@ public partial class ImportPage : Page
|
|||||||
|
|
||||||
private void UpdateButtons()
|
private void UpdateButtons()
|
||||||
{
|
{
|
||||||
PreviewButton.IsEnabled = Selected is not null;
|
PreviewButton.IsEnabled = _previewing || Selected is not null;
|
||||||
ImportButton.IsEnabled = !_busy && Selected is { CanImport: true };
|
var importable = Importable.Count;
|
||||||
|
ImportButton.IsEnabled = !_busy && importable > 0;
|
||||||
|
ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren";
|
||||||
|
// Why the selection cannot be imported ("In Bibliothek", "Keine Dauer"); shown on the disabled button.
|
||||||
|
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Show(InfoBarSeverity severity, string title, string message)
|
private void Show(InfoBarSeverity severity, string title, string message)
|
||||||
@@ -218,16 +297,15 @@ public partial class ImportPage : Page
|
|||||||
private sealed record ResultRow(OpenverseTrack Track, string Status, bool CanImport)
|
private sealed record ResultRow(OpenverseTrack Track, string Status, bool CanImport)
|
||||||
{
|
{
|
||||||
public static ResultRow For(OpenverseTrack track, IReadOnlySet<string> imported) =>
|
public static ResultRow For(OpenverseTrack track, IReadOnlySet<string> imported) =>
|
||||||
imported.Contains(track.Id) ? new(track, "In library", false)
|
imported.Contains(track.Id) ? new(track, "In Bibliothek", false)
|
||||||
: !track.CanImport ? new(track, "No duration", false)
|
: !track.CanImport ? new(track, "Keine Dauer", false)
|
||||||
: new(track, "", true);
|
: new(track, "", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record SessionRow(bool Success, string Title, string Artist, string Duration, string Source, string Details)
|
private sealed record SessionRow(bool Success, string Title, string Artist, string Details)
|
||||||
{
|
{
|
||||||
public static SessionRow Added(Song song, string source, string details) =>
|
public static SessionRow Added(Song song, string details) => new(true, song.Title, song.Artist, details);
|
||||||
new(true, song.Title, song.Artist, $"{(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}", source, details);
|
|
||||||
|
|
||||||
public static SessionRow Failed(string name, string source, string error) => new(false, name, "", "", source, error);
|
public static SessionRow Failed(string name, string error) => new(false, name, "", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,9 @@
|
|||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||||
Title="Library"
|
Title="Bibliothek"
|
||||||
|
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||||
|
ScrollViewer.CanContentScroll="False"
|
||||||
Loaded="OnLoaded">
|
Loaded="OnLoaded">
|
||||||
<Grid Margin="24">
|
<Grid Margin="24">
|
||||||
<Grid.RowDefinitions>
|
<Grid.RowDefinitions>
|
||||||
@@ -11,26 +13,24 @@
|
|||||||
<RowDefinition Height="*" />
|
<RowDefinition Height="*" />
|
||||||
</Grid.RowDefinitions>
|
</Grid.RowDefinitions>
|
||||||
|
|
||||||
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Library" />
|
<DockPanel Grid.Row="1" Margin="0,0,0,12" LastChildFill="True">
|
||||||
|
|
||||||
<DockPanel Grid.Row="1" Margin="0,16,0,12" LastChildFill="True">
|
|
||||||
<ui:Button x:Name="DeleteButton"
|
<ui:Button x:Name="DeleteButton"
|
||||||
DockPanel.Dock="Right"
|
DockPanel.Dock="Right"
|
||||||
Margin="8,0,0,0"
|
Margin="8,0,0,0"
|
||||||
Content="Delete"
|
Content="Löschen"
|
||||||
Icon="{ui:SymbolIcon Delete24}"
|
Icon="{ui:SymbolIcon Delete24}"
|
||||||
IsEnabled="False"
|
IsEnabled="False"
|
||||||
Click="OnDelete" />
|
Click="OnDelete" />
|
||||||
<ui:Button x:Name="EditButton"
|
<ui:Button x:Name="EditButton"
|
||||||
DockPanel.Dock="Right"
|
DockPanel.Dock="Right"
|
||||||
Margin="8,0,0,0"
|
Margin="8,0,0,0"
|
||||||
Content="Edit"
|
Content="Bearbeiten"
|
||||||
Icon="{ui:SymbolIcon Edit24}"
|
Icon="{ui:SymbolIcon Edit24}"
|
||||||
IsEnabled="False"
|
IsEnabled="False"
|
||||||
Click="OnEdit" />
|
Click="OnEdit" />
|
||||||
<ui:TextBox x:Name="SearchBox"
|
<ui:TextBox x:Name="SearchBox"
|
||||||
AutomationProperties.Name="Search songs"
|
AutomationProperties.Name="Songs suchen"
|
||||||
PlaceholderText="Search title or artist"
|
PlaceholderText="Titel oder Interpret suchen"
|
||||||
Icon="{ui:SymbolIcon Search24}"
|
Icon="{ui:SymbolIcon Search24}"
|
||||||
TextChanged="OnSearchChanged" />
|
TextChanged="OnSearchChanged" />
|
||||||
</DockPanel>
|
</DockPanel>
|
||||||
@@ -40,18 +40,17 @@
|
|||||||
SelectionMode="Single"
|
SelectionMode="Single"
|
||||||
AutomationProperties.Name="Songs"
|
AutomationProperties.Name="Songs"
|
||||||
SelectionChanged="OnSelectionChanged"
|
SelectionChanged="OnSelectionChanged"
|
||||||
MouseDoubleClick="OnEdit">
|
MouseDoubleClick="OnEdit"
|
||||||
|
KeyDown="OnListKeyDown">
|
||||||
<ui:ListView.View>
|
<ui:ListView.View>
|
||||||
<ui:GridView>
|
<ui:GridView>
|
||||||
<ui:GridViewColumn Width="260" Header="Title" DisplayMemberBinding="{Binding Title}" />
|
<ui:GridViewColumn Width="220" Header="Titel" DisplayMemberBinding="{Binding Title}" />
|
||||||
<ui:GridViewColumn Width="200" Header="Artist" DisplayMemberBinding="{Binding Artist}" />
|
<ui:GridViewColumn Width="160" Header="Interpret" DisplayMemberBinding="{Binding Artist}" />
|
||||||
<ui:GridViewColumn Width="80" Header="Duration">
|
<ui:GridViewColumn Width="80" Header="Dauer">
|
||||||
<ui:GridViewColumn.DisplayMemberBinding>
|
<ui:GridViewColumn.DisplayMemberBinding>
|
||||||
<Binding Path="Duration" StringFormat="m\:ss" />
|
<Binding Path="Duration" StringFormat="m\:ss" />
|
||||||
</ui:GridViewColumn.DisplayMemberBinding>
|
</ui:GridViewColumn.DisplayMemberBinding>
|
||||||
</ui:GridViewColumn>
|
</ui:GridViewColumn>
|
||||||
<ui:GridViewColumn Width="140" Header="License" DisplayMemberBinding="{Binding License}" />
|
|
||||||
<ui:GridViewColumn Width="220" Header="Attribution" DisplayMemberBinding="{Binding Attribution}" />
|
|
||||||
</ui:GridView>
|
</ui:GridView>
|
||||||
</ui:ListView.View>
|
</ui:ListView.View>
|
||||||
</ui:ListView>
|
</ui:ListView>
|
||||||
@@ -61,7 +60,7 @@
|
|||||||
Margin="0,48,0,0"
|
Margin="0,48,0,0"
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
VerticalAlignment="Top"
|
VerticalAlignment="Top"
|
||||||
Text="No songs found."
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
Visibility="Collapsed" />
|
Visibility="Collapsed" />
|
||||||
</Grid>
|
</Grid>
|
||||||
</Page>
|
</Page>
|
||||||
@@ -27,9 +27,19 @@ public partial class LibraryPage : Page
|
|||||||
{
|
{
|
||||||
var songs = _controller.Search(SearchBox.Text);
|
var songs = _controller.Search(SearchBox.Text);
|
||||||
SongList.ItemsSource = songs;
|
SongList.ItemsSource = songs;
|
||||||
|
GridColumns.Fit(SongList);
|
||||||
|
EmptyText.Text = string.IsNullOrWhiteSpace(SearchBox.Text)
|
||||||
|
? "Noch keine Songs. Musik auf der Seite Import hinzufĂĽgen."
|
||||||
|
: "Kein Song passt zur Suche.";
|
||||||
EmptyText.Visibility = songs.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
|
EmptyText.Visibility = songs.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void OnListKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
|
||||||
|
{
|
||||||
|
if (e.Key == System.Windows.Input.Key.Enter) OnEdit(sender, e);
|
||||||
|
else if (e.Key == System.Windows.Input.Key.Delete) OnDelete(sender, e);
|
||||||
|
}
|
||||||
|
|
||||||
private void OnEdit(object sender, RoutedEventArgs e)
|
private void OnEdit(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
if (Selected is not { } song)
|
if (Selected is not { } song)
|
||||||
@@ -48,10 +58,10 @@ public partial class LibraryPage : Page
|
|||||||
|
|
||||||
var result = await new MessageBox
|
var result = await new MessageBox
|
||||||
{
|
{
|
||||||
Title = "Delete song",
|
Title = "Song löschen",
|
||||||
Content = $"Delete \"{song.Title}\" by {song.Artist} from the library?",
|
Content = $"\"{song.Title}\" von {song.Artist} aus der Bibliothek löschen?",
|
||||||
PrimaryButtonText = "Delete",
|
PrimaryButtonText = "Löschen",
|
||||||
CloseButtonText = "Cancel",
|
CloseButtonText = "Abbrechen",
|
||||||
}.ShowDialogAsync();
|
}.ShowDialogAsync();
|
||||||
|
|
||||||
if (result != Wpf.Ui.Controls.MessageBoxResult.Primary)
|
if (result != Wpf.Ui.Controls.MessageBoxResult.Primary)
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||||
Title="Schedule"
|
Title="Sendeplan"
|
||||||
|
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||||
|
ScrollViewer.CanContentScroll="False"
|
||||||
Loaded="OnLoaded"
|
Loaded="OnLoaded"
|
||||||
Unloaded="OnUnloaded">
|
Unloaded="OnUnloaded">
|
||||||
<Page.Resources>
|
<Page.Resources>
|
||||||
@@ -14,8 +16,8 @@
|
|||||||
HorizontalAlignment="Left"
|
HorizontalAlignment="Left"
|
||||||
BorderThickness="1"
|
BorderThickness="1"
|
||||||
CornerRadius="4"
|
CornerRadius="4"
|
||||||
BorderBrush="{DynamicResource TextFillColorTertiaryBrush}">
|
BorderBrush="{DynamicResource ControlStrongStrokeColorDefaultBrush}">
|
||||||
<TextBlock x:Name="ChipText" Text="{Binding Kind}" FontSize="12" />
|
<TextBlock x:Name="ChipText" Text="{Binding KindName}" FontSize="12" />
|
||||||
</Border>
|
</Border>
|
||||||
<DataTemplate.Triggers>
|
<DataTemplate.Triggers>
|
||||||
<DataTrigger Binding="{Binding Kind}" Value="News">
|
<DataTrigger Binding="{Binding Kind}" Value="News">
|
||||||
@@ -41,26 +43,50 @@
|
|||||||
<RowDefinition Height="*" />
|
<RowDefinition Height="*" />
|
||||||
</Grid.RowDefinitions>
|
</Grid.RowDefinitions>
|
||||||
|
|
||||||
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Schedule" />
|
<!-- Wraps on narrow windows instead of cutting off the buttons. -->
|
||||||
|
<WrapPanel Grid.Row="1" Margin="0,-8,0,0">
|
||||||
<StackPanel Grid.Row="1" Margin="0,16,0,0" Orientation="Horizontal">
|
<ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="Start" />
|
||||||
<ui:TextBlock VerticalAlignment="Center" Text="Hours" />
|
<ComboBox x:Name="StartBox"
|
||||||
|
Width="112"
|
||||||
|
Margin="0,8,12,0"
|
||||||
|
VerticalAlignment="Center"
|
||||||
|
AutomationProperties.Name="Startzeit"
|
||||||
|
DisplayMemberPath="Label"
|
||||||
|
DropDownOpened="OnStartDropDownOpened" />
|
||||||
|
<ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="Stunden" />
|
||||||
<ui:NumberBox x:Name="HoursBox"
|
<ui:NumberBox x:Name="HoursBox"
|
||||||
Width="140"
|
Width="112"
|
||||||
Margin="12,0,0,0"
|
Margin="0,8,12,0"
|
||||||
AutomationProperties.Name="Hours to plan"
|
VerticalAlignment="Center"
|
||||||
|
AutomationProperties.Name="Zu planende Stunden"
|
||||||
Minimum="1"
|
Minimum="1"
|
||||||
Maximum="24"
|
Maximum="24"
|
||||||
Value="1"
|
Value="1"
|
||||||
SmallChange="1"
|
SmallChange="1"
|
||||||
MaxDecimalPlaces="0"
|
MaxDecimalPlaces="0"
|
||||||
ClearButtonEnabled="False" />
|
ClearButtonEnabled="False" />
|
||||||
<ui:Button Margin="12,0,0,0"
|
<CheckBox x:Name="UnlimitedBox"
|
||||||
|
MinWidth="0"
|
||||||
|
Margin="0,8,0,0"
|
||||||
|
VerticalAlignment="Center"
|
||||||
|
Content="Unbegrenzt"
|
||||||
|
ToolTip="Ohne Ende: Die nächsten 5 Stunden sind geplant, jede Stunde kommt eine weitere dazu."
|
||||||
|
Checked="OnUnlimitedChanged"
|
||||||
|
Unchecked="OnUnlimitedChanged" />
|
||||||
|
<ui:Button x:Name="CreateButton"
|
||||||
|
Margin="0,8,8,0"
|
||||||
|
VerticalAlignment="Center"
|
||||||
Appearance="Primary"
|
Appearance="Primary"
|
||||||
Content="Create schedule"
|
Content="Plan erstellen"
|
||||||
Icon="{ui:SymbolIcon CalendarLtr24}"
|
|
||||||
Click="OnCreate" />
|
Click="OnCreate" />
|
||||||
</StackPanel>
|
<ui:Button x:Name="StartNowButton"
|
||||||
|
Margin="0,8,0,0"
|
||||||
|
VerticalAlignment="Center"
|
||||||
|
Content="Jetzt starten"
|
||||||
|
Icon="{ui:SymbolIcon Play24}"
|
||||||
|
ToolTip="Plant ab diesem Moment und geht sofort auf Sendung. Die Startzeit wird ignoriert."
|
||||||
|
Click="OnStartNow" />
|
||||||
|
</WrapPanel>
|
||||||
|
|
||||||
<ui:InfoBar x:Name="Message"
|
<ui:InfoBar x:Name="Message"
|
||||||
Grid.Row="2"
|
Grid.Row="2"
|
||||||
@@ -73,6 +99,8 @@
|
|||||||
Margin="0,16,0,16"
|
Margin="0,16,0,16"
|
||||||
Padding="16"
|
Padding="16"
|
||||||
CornerRadius="8"
|
CornerRadius="8"
|
||||||
|
BorderThickness="1"
|
||||||
|
BorderBrush="{DynamicResource CardStrokeColorDefaultBrush}"
|
||||||
Background="{DynamicResource CardBackgroundFillColorDefaultBrush}">
|
Background="{DynamicResource CardBackgroundFillColorDefaultBrush}">
|
||||||
<Grid>
|
<Grid>
|
||||||
<Grid.ColumnDefinitions>
|
<Grid.ColumnDefinitions>
|
||||||
@@ -83,7 +111,7 @@
|
|||||||
<StackPanel Grid.Column="0">
|
<StackPanel Grid.Column="0">
|
||||||
<ui:TextBlock FontTypography="Caption"
|
<ui:TextBlock FontTypography="Caption"
|
||||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
Text="Now playing" />
|
Text="Läuft gerade" />
|
||||||
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
|
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
|
||||||
<ContentPresenter x:Name="NowKind"
|
<ContentPresenter x:Name="NowKind"
|
||||||
VerticalAlignment="Center"
|
VerticalAlignment="Center"
|
||||||
@@ -93,11 +121,11 @@
|
|||||||
Margin="8,0,0,0"
|
Margin="8,0,0,0"
|
||||||
FontTypography="Subtitle"
|
FontTypography="Subtitle"
|
||||||
TextTrimming="CharacterEllipsis"
|
TextTrimming="CharacterEllipsis"
|
||||||
Text="Nothing on air" />
|
Text="Nichts auf Sendung" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
<ProgressBar x:Name="NowProgress"
|
<ProgressBar x:Name="NowProgress"
|
||||||
Margin="0,12,0,0"
|
Margin="0,12,0,0"
|
||||||
AutomationProperties.Name="Progress of the current item"
|
AutomationProperties.Name="Fortschritt des aktuellen Elements"
|
||||||
Maximum="1" />
|
Maximum="1" />
|
||||||
<ui:TextBlock x:Name="NowTime"
|
<ui:TextBlock x:Name="NowTime"
|
||||||
Margin="0,6,0,0"
|
Margin="0,6,0,0"
|
||||||
@@ -106,18 +134,21 @@
|
|||||||
</StackPanel>
|
</StackPanel>
|
||||||
|
|
||||||
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center">
|
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center">
|
||||||
<StackPanel Orientation="Horizontal">
|
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
|
||||||
<ui:Button x:Name="StartButton"
|
<ui:Button x:Name="EndNowButton"
|
||||||
|
Content="Jetzt beenden"
|
||||||
|
Icon="{ui:SymbolIcon Next24}"
|
||||||
|
ToolTip="Beendet das laufende Element sofort; das nächste startet."
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnEndNow" />
|
||||||
|
<!-- One button: Start while idle, Stop while on air. -->
|
||||||
|
<ui:Button x:Name="PlayButton"
|
||||||
|
MinWidth="110"
|
||||||
|
Margin="8,0,0,0"
|
||||||
Content="Start"
|
Content="Start"
|
||||||
Icon="{ui:SymbolIcon Play24}"
|
Icon="{ui:SymbolIcon Play24}"
|
||||||
IsEnabled="False"
|
IsEnabled="False"
|
||||||
Click="OnStart" />
|
Click="OnPlayToggle" />
|
||||||
<ui:Button x:Name="StopButton"
|
|
||||||
Margin="8,0,0,0"
|
|
||||||
Content="Stop"
|
|
||||||
Icon="{ui:SymbolIcon Stop24}"
|
|
||||||
IsEnabled="False"
|
|
||||||
Click="OnStop" />
|
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
<StackPanel Margin="0,12,0,0" Orientation="Horizontal">
|
<StackPanel Margin="0,12,0,0" Orientation="Horizontal">
|
||||||
<ui:SymbolIcon VerticalAlignment="Center" Symbol="Speaker224" />
|
<ui:SymbolIcon VerticalAlignment="Center" Symbol="Speaker224" />
|
||||||
@@ -125,7 +156,7 @@
|
|||||||
Width="140"
|
Width="140"
|
||||||
Margin="8,0,0,0"
|
Margin="8,0,0,0"
|
||||||
VerticalAlignment="Center"
|
VerticalAlignment="Center"
|
||||||
AutomationProperties.Name="Volume"
|
AutomationProperties.Name="Lautstärke"
|
||||||
Minimum="0"
|
Minimum="0"
|
||||||
Maximum="1"
|
Maximum="1"
|
||||||
SmallChange="0.05"
|
SmallChange="0.05"
|
||||||
@@ -136,46 +167,77 @@
|
|||||||
</Grid>
|
</Grid>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
<!-- Song request (hot swap) -->
|
<!-- Song request (hot swap) on the left, actions for the selected timeline row on the right -->
|
||||||
<Grid Grid.Row="4" Margin="0,0,0,12">
|
<StackPanel Grid.Row="4" Margin="0,0,0,12">
|
||||||
<Grid.ColumnDefinitions>
|
<Grid>
|
||||||
<ColumnDefinition Width="Auto" />
|
<Grid.ColumnDefinitions>
|
||||||
<ColumnDefinition Width="*" MaxWidth="420" />
|
<ColumnDefinition Width="Auto" />
|
||||||
<ColumnDefinition Width="Auto" />
|
<ColumnDefinition Width="4*" MaxWidth="320" />
|
||||||
<ColumnDefinition Width="*" />
|
<ColumnDefinition Width="Auto" />
|
||||||
</Grid.ColumnDefinitions>
|
<ColumnDefinition Width="*" />
|
||||||
<ui:TextBlock Grid.Column="0" VerticalAlignment="Center" Text="Song request" />
|
<ColumnDefinition Width="Auto" />
|
||||||
<ComboBox x:Name="RequestSong"
|
</Grid.ColumnDefinitions>
|
||||||
Grid.Column="1"
|
<ui:TextBlock Grid.Column="0" VerticalAlignment="Center" Text="Songwunsch" />
|
||||||
Margin="12,0,0,0"
|
<ComboBox x:Name="RequestSong"
|
||||||
AutomationProperties.Name="Requested song"
|
Grid.Column="1"
|
||||||
DisplayMemberPath="Label"
|
|
||||||
IsEditable="True"
|
|
||||||
IsTextSearchEnabled="True"
|
|
||||||
TextSearch.TextPath="Label"
|
|
||||||
SelectionChanged="OnRequestChanged" />
|
|
||||||
<ui:Button x:Name="SwapButton"
|
|
||||||
Grid.Column="2"
|
|
||||||
Margin="12,0,0,0"
|
|
||||||
Content="Play instead of selected"
|
|
||||||
Icon="{ui:SymbolIcon ArrowSwap24}"
|
|
||||||
IsEnabled="False"
|
|
||||||
Click="OnSwap" />
|
|
||||||
<ui:TextBlock x:Name="SwapHint"
|
|
||||||
Grid.Column="3"
|
|
||||||
Margin="12,0,0,0"
|
Margin="12,0,0,0"
|
||||||
VerticalAlignment="Center"
|
AutomationProperties.Name="GewĂĽnschter Song"
|
||||||
|
DisplayMemberPath="Label"
|
||||||
|
IsEditable="True"
|
||||||
|
IsTextSearchEnabled="True"
|
||||||
|
TextSearch.TextPath="Label"
|
||||||
|
SelectionChanged="OnRequestChanged" />
|
||||||
|
<ui:Button x:Name="SwapButton"
|
||||||
|
Grid.Column="2"
|
||||||
|
Margin="12,0,0,0"
|
||||||
|
Content="Auswahl ersetzen"
|
||||||
|
Icon="{ui:SymbolIcon ArrowSwap24}"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnSwap" />
|
||||||
|
<StackPanel Grid.Column="4" Margin="12,0,0,0" Orientation="Horizontal">
|
||||||
|
<ui:Button x:Name="MoveUpButton"
|
||||||
|
Icon="{ui:SymbolIcon ArrowUp24}"
|
||||||
|
ToolTip="Nach oben"
|
||||||
|
AutomationProperties.Name="Ausgewähltes Element nach oben verschieben"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnMoveUp" />
|
||||||
|
<ui:Button x:Name="MoveDownButton"
|
||||||
|
Margin="4,0,0,0"
|
||||||
|
Icon="{ui:SymbolIcon ArrowDown24}"
|
||||||
|
ToolTip="Nach unten"
|
||||||
|
AutomationProperties.Name="Ausgewähltes Element nach unten verschieben"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnMoveDown" />
|
||||||
|
<ui:Button x:Name="EditItemButton"
|
||||||
|
Margin="4,0,0,0"
|
||||||
|
Icon="{ui:SymbolIcon Edit24}"
|
||||||
|
ToolTip="Titel und Länge bearbeiten"
|
||||||
|
AutomationProperties.Name="Ausgewähltes Element bearbeiten"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnEditItem" />
|
||||||
|
<ui:Button x:Name="RemoveButton"
|
||||||
|
Margin="4,0,0,0"
|
||||||
|
Icon="{ui:SymbolIcon Delete24}"
|
||||||
|
ToolTip="Aus dem Plan entfernen"
|
||||||
|
AutomationProperties.Name="Ausgewähltes Element entfernen"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnRemove" />
|
||||||
|
</StackPanel>
|
||||||
|
</Grid>
|
||||||
|
<ui:TextBlock x:Name="SwapHint"
|
||||||
|
Margin="0,6,0,0"
|
||||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
TextTrimming="CharacterEllipsis"
|
TextWrapping="Wrap"
|
||||||
Text="Select an upcoming item in the schedule." />
|
Visibility="Collapsed" />
|
||||||
</Grid>
|
</StackPanel>
|
||||||
|
|
||||||
<ui:ListView x:Name="Timeline"
|
<ui:ListView x:Name="Timeline"
|
||||||
Grid.Row="5"
|
Grid.Row="5"
|
||||||
SelectionMode="Single"
|
SelectionMode="Single"
|
||||||
IsHitTestVisible="True"
|
IsHitTestVisible="True"
|
||||||
AutomationProperties.Name="Schedule timeline"
|
AutomationProperties.Name="Sendeplan"
|
||||||
SelectionChanged="OnTimelineSelectionChanged">
|
SelectionChanged="OnTimelineSelectionChanged"
|
||||||
|
MouseDoubleClick="OnEditItem">
|
||||||
<ui:ListView.View>
|
<ui:ListView.View>
|
||||||
<ui:GridView>
|
<ui:GridView>
|
||||||
<ui:GridViewColumn Width="36">
|
<ui:GridViewColumn Width="36">
|
||||||
@@ -185,7 +247,7 @@
|
|||||||
Symbol="Play24"
|
Symbol="Play24"
|
||||||
Filled="True"
|
Filled="True"
|
||||||
Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}"
|
Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}"
|
||||||
AutomationProperties.Name="On air"
|
AutomationProperties.Name="Auf Sendung"
|
||||||
Visibility="Collapsed" />
|
Visibility="Collapsed" />
|
||||||
<DataTemplate.Triggers>
|
<DataTemplate.Triggers>
|
||||||
<DataTrigger Binding="{Binding IsCurrent}" Value="True">
|
<DataTrigger Binding="{Binding IsCurrent}" Value="True">
|
||||||
@@ -200,15 +262,15 @@
|
|||||||
<Binding Path="Item.Start" StringFormat="HH:mm:ss" />
|
<Binding Path="Item.Start" StringFormat="HH:mm:ss" />
|
||||||
</ui:GridViewColumn.DisplayMemberBinding>
|
</ui:GridViewColumn.DisplayMemberBinding>
|
||||||
</ui:GridViewColumn>
|
</ui:GridViewColumn>
|
||||||
<ui:GridViewColumn Width="120" Header="Type">
|
<ui:GridViewColumn Width="120" Header="Typ">
|
||||||
<ui:GridViewColumn.CellTemplate>
|
<ui:GridViewColumn.CellTemplate>
|
||||||
<DataTemplate>
|
<DataTemplate>
|
||||||
<ContentPresenter Content="{Binding Item}" ContentTemplate="{StaticResource KindChip}" />
|
<ContentPresenter Content="{Binding Item}" ContentTemplate="{StaticResource KindChip}" />
|
||||||
</DataTemplate>
|
</DataTemplate>
|
||||||
</ui:GridViewColumn.CellTemplate>
|
</ui:GridViewColumn.CellTemplate>
|
||||||
</ui:GridViewColumn>
|
</ui:GridViewColumn>
|
||||||
<ui:GridViewColumn Width="420" Header="Title" DisplayMemberBinding="{Binding Item.Title}" />
|
<ui:GridViewColumn Width="360" Header="Titel" DisplayMemberBinding="{Binding Item.Title}" />
|
||||||
<ui:GridViewColumn Width="90" Header="Duration">
|
<ui:GridViewColumn Width="90" Header="Dauer">
|
||||||
<ui:GridViewColumn.DisplayMemberBinding>
|
<ui:GridViewColumn.DisplayMemberBinding>
|
||||||
<Binding Path="Item.Duration" StringFormat="m\:ss" />
|
<Binding Path="Item.Duration" StringFormat="m\:ss" />
|
||||||
</ui:GridViewColumn.DisplayMemberBinding>
|
</ui:GridViewColumn.DisplayMemberBinding>
|
||||||
@@ -222,7 +284,8 @@
|
|||||||
Margin="0,48,0,0"
|
Margin="0,48,0,0"
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
VerticalAlignment="Top"
|
VerticalAlignment="Top"
|
||||||
Text="No schedule yet. Choose the hours and create one."
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
|
Text="Noch kein Plan. Stunden wählen und Plan erstellen."
|
||||||
Visibility="Visible" />
|
Visibility="Visible" />
|
||||||
</Grid>
|
</Grid>
|
||||||
</Page>
|
</Page>
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Collections.ObjectModel;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Controls;
|
using System.Windows.Controls;
|
||||||
using System.Windows.Threading;
|
using System.Windows.Threading;
|
||||||
@@ -14,10 +15,24 @@ public partial class SchedulePage : Page
|
|||||||
private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) };
|
private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) };
|
||||||
private bool _loading;
|
private bool _loading;
|
||||||
private int _scrolledTo = -1;
|
private int _scrolledTo = -1;
|
||||||
|
private bool _shownPlaying;
|
||||||
|
|
||||||
|
// Weekday names in the start list follow the interface language, not the Windows setting.
|
||||||
|
private static readonly System.Globalization.CultureInfo German = new("de-DE");
|
||||||
|
|
||||||
|
// Bound once and updated row by row, so a click never rebuilds the whole list.
|
||||||
|
private readonly ObservableCollection<TimelineRow> _rows = [];
|
||||||
|
|
||||||
|
// A controller call is running on a pool thread; the buttons that would collide with it are off.
|
||||||
|
private bool _working;
|
||||||
|
|
||||||
|
// Optimistic state: what the user just asked for, shown before the engine has caught up.
|
||||||
|
private bool? _expectPlaying;
|
||||||
|
|
||||||
public SchedulePage()
|
public SchedulePage()
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
|
Timeline.ItemsSource = _rows;
|
||||||
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
|
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
|
||||||
_progressTimer.Tick += (_, _) =>
|
_progressTimer.Tick += (_, _) =>
|
||||||
{
|
{
|
||||||
@@ -36,6 +51,9 @@ public partial class SchedulePage : Page
|
|||||||
_loading = true;
|
_loading = true;
|
||||||
VolumeSlider.Value = _controller.Volume;
|
VolumeSlider.Value = _controller.Volume;
|
||||||
_loading = false;
|
_loading = false;
|
||||||
|
FillStartTimes();
|
||||||
|
if (_controller.Plan.Count > 0)
|
||||||
|
UnlimitedBox.IsChecked = _controller.IsUnlimited;
|
||||||
|
|
||||||
// The library can change on other pages.
|
// The library can change on other pages.
|
||||||
RequestSong.ItemsSource = _controller.LibrarySongs()
|
RequestSong.ItemsSource = _controller.LibrarySongs()
|
||||||
@@ -55,65 +73,148 @@ public partial class SchedulePage : Page
|
|||||||
_progressTimer.Stop();
|
_progressTimer.Stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnCreate(object sender, RoutedEventArgs e)
|
// The next 12 full hours; rebuilt when the list opens, so it never offers a past hour.
|
||||||
|
private void FillStartTimes()
|
||||||
{
|
{
|
||||||
var hours = (int)(HoursBox.Value ?? 1);
|
var selected = (StartBox.SelectedItem as StartOption)?.Time;
|
||||||
try
|
var now = DateTime.Now;
|
||||||
{
|
var next = now.Date.AddHours(now.Hour + 1);
|
||||||
_controller.CreatePlan(hours);
|
var options = Enumerable.Range(0, 12)
|
||||||
var plan = _controller.Plan;
|
.Select(i => next.AddHours(i))
|
||||||
ShowMessage(InfoBarSeverity.Success, "Schedule created",
|
.Select(t => new StartOption(t, t.Date == now.Date ? $"{t:HH:mm}" : t.ToString("ddd HH:mm", German)))
|
||||||
$"{hours} h from {plan[0].Start:HH:mm} to {plan[^1].End:HH:mm}, {plan.Count} items.");
|
.ToList();
|
||||||
}
|
StartBox.ItemsSource = options;
|
||||||
catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException)
|
StartBox.SelectedItem = options.FirstOrDefault(o => o.Time == selected) ?? options[0];
|
||||||
{
|
|
||||||
ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message);
|
|
||||||
}
|
|
||||||
ShowCurrent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnSwap(object sender, RoutedEventArgs e)
|
private void OnStartDropDownOpened(object? sender, EventArgs e) => FillStartTimes();
|
||||||
|
|
||||||
|
private void OnUnlimitedChanged(object sender, RoutedEventArgs e) =>
|
||||||
|
HoursBox.IsEnabled = UnlimitedBox.IsChecked != true;
|
||||||
|
|
||||||
|
private void OnCreate(object sender, RoutedEventArgs e) => CreatePlan(startNow: false);
|
||||||
|
|
||||||
|
private void OnStartNow(object sender, RoutedEventArgs e) => CreatePlan(startNow: true);
|
||||||
|
|
||||||
|
private async void CreatePlan(bool startNow)
|
||||||
|
{
|
||||||
|
int? hours = UnlimitedBox.IsChecked == true ? null : (int)(HoursBox.Value ?? 1);
|
||||||
|
var start = (StartBox.SelectedItem as StartOption)?.Time;
|
||||||
|
if (startNow)
|
||||||
|
_expectPlaying = true;
|
||||||
|
await RunAsync("Der Plan konnte nicht erstellt werden", () =>
|
||||||
|
{
|
||||||
|
if (startNow)
|
||||||
|
_controller.StartNow(hours);
|
||||||
|
else
|
||||||
|
_controller.CreatePlan(hours, start);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Runs a controller call that can take a moment (planning, waiting for the audio thread to stop)
|
||||||
|
/// off the UI thread, so the window stays responsive. Returns <c>false</c> after showing the error.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> RunAsync(string errorTitle, Action work)
|
||||||
|
{
|
||||||
|
_working = true;
|
||||||
|
UpdateButtons();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Run(work);
|
||||||
|
Message.IsOpen = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException or InvalidOperationException)
|
||||||
|
{
|
||||||
|
ShowMessage(InfoBarSeverity.Error, errorTitle, ex.Message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_working = false;
|
||||||
|
_expectPlaying = null;
|
||||||
|
ShowCurrent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void OnSwap(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
if (Timeline.SelectedItem is not TimelineRow row || RequestSong.SelectedItem is not SongOption song)
|
if (Timeline.SelectedItem is not TimelineRow row || RequestSong.SelectedItem is not SongOption song)
|
||||||
return;
|
return;
|
||||||
try
|
ScheduleItem? placed = null;
|
||||||
{
|
if (await RunAsync("Der Songwunsch konnte nicht eingeplant werden", () => placed = _controller.Swap(row.Index, song.Id)[row.Index]))
|
||||||
var plan = _controller.Swap(row.Index, song.Id);
|
ShowMessage(InfoBarSeverity.Success, "Songwunsch eingeplant",
|
||||||
var placed = plan[row.Index];
|
$"\"{placed!.Title}\" läuft um {placed.Start:HH:mm:ss}.");
|
||||||
ShowMessage(InfoBarSeverity.Success, "Song request planned",
|
|
||||||
$"\"{placed.Title}\" plays at {placed.Start:HH:mm:ss} instead of \"{row.Item.Title}\". The rest of that half hour was replanned, the news stays on time.");
|
|
||||||
}
|
|
||||||
catch (ScheduleException ex)
|
|
||||||
{
|
|
||||||
ShowMessage(InfoBarSeverity.Error, "Could not play the request", ex.Message);
|
|
||||||
}
|
|
||||||
ShowCurrent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
||||||
|
|
||||||
private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
private void OnMoveUp(object sender, RoutedEventArgs e) => MoveSelected(-1);
|
||||||
|
|
||||||
private void OnStart(object sender, RoutedEventArgs e)
|
private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1);
|
||||||
|
|
||||||
|
// The selection follows the item, so it can be moved several steps in a row.
|
||||||
|
private void MoveSelected(int offset) => ChangeSelected(row =>
|
||||||
|
{
|
||||||
|
_controller.Move(row.Index, offset);
|
||||||
|
Timeline.SelectedIndex = row.Index + offset;
|
||||||
|
});
|
||||||
|
|
||||||
|
private void OnEndNow(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
Message.IsOpen = false;
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_controller.Start();
|
_controller.EndCurrentNow();
|
||||||
|
Message.IsOpen = false;
|
||||||
}
|
}
|
||||||
catch (InvalidOperationException ex)
|
catch (ScheduleException ex)
|
||||||
{
|
{
|
||||||
ShowMessage(InfoBarSeverity.Warning, "Could not start", ex.Message);
|
ShowMessage(InfoBarSeverity.Error, "Das Element konnte nicht beendet werden", ex.Message);
|
||||||
}
|
}
|
||||||
ShowCurrent();
|
ShowCurrent();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnStop(object sender, RoutedEventArgs e)
|
private void OnRemove(object sender, RoutedEventArgs e) => ChangeSelected(row => _controller.Remove(row.Index));
|
||||||
|
|
||||||
|
private void OnEditItem(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
_controller.Stop();
|
if (!EditItemButton.IsEnabled || Timeline.SelectedItem is not TimelineRow row)
|
||||||
|
return;
|
||||||
|
var dialog = new ScheduleItemEditWindow(row.Item) { Owner = Window.GetWindow(this) };
|
||||||
|
if (dialog.ShowDialog() == true)
|
||||||
|
ChangeSelected(r => _controller.EditItem(r.Index, dialog.ItemTitle, dialog.Duration));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ChangeSelected(Action<TimelineRow> change)
|
||||||
|
{
|
||||||
|
if (Timeline.SelectedItem is not TimelineRow row)
|
||||||
|
return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
change(row);
|
||||||
|
Message.IsOpen = false;
|
||||||
|
}
|
||||||
|
catch (ScheduleException ex)
|
||||||
|
{
|
||||||
|
ShowMessage(InfoBarSeverity.Error, "Der Plan konnte nicht geändert werden", ex.Message);
|
||||||
|
}
|
||||||
ShowCurrent();
|
ShowCurrent();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
||||||
|
|
||||||
|
private async void OnPlayToggle(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
var stop = _controller.IsPlaying;
|
||||||
|
// The button and the card switch at once; stopping waits for the audio thread in the background.
|
||||||
|
_expectPlaying = !stop;
|
||||||
|
if (stop)
|
||||||
|
NowKind.Visibility = Visibility.Collapsed;
|
||||||
|
UpdateProgress();
|
||||||
|
await RunAsync("Start nicht möglich", stop ? _controller.Stop : _controller.Start);
|
||||||
|
}
|
||||||
|
|
||||||
private void OnVolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
|
private void OnVolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
|
||||||
{
|
{
|
||||||
if (!_loading) _controller.Volume = (float)e.NewValue;
|
if (!_loading) _controller.Volume = (float)e.NewValue;
|
||||||
@@ -123,15 +224,15 @@ public partial class SchedulePage : Page
|
|||||||
private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent);
|
private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent);
|
||||||
|
|
||||||
private void OnItemFailed(object? sender, string message) =>
|
private void OnItemFailed(object? sender, string message) =>
|
||||||
Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Item skipped", message));
|
Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Element ĂĽbersprungen", message));
|
||||||
|
|
||||||
private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
|
private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
|
||||||
{
|
{
|
||||||
ShowMessage(InfoBarSeverity.Informational, "Broadcast finished", "The whole schedule has been played.");
|
ShowMessage(InfoBarSeverity.Informational, "Sendung beendet", "Der ganze Plan wurde gespielt.");
|
||||||
ShowCurrent();
|
ShowCurrent();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Rebuilds the rows from the controller; the selection is the user's swap target and is kept.
|
// Syncs the rows with the controller; the selection is the user's swap target and is kept.
|
||||||
private void ShowCurrent()
|
private void ShowCurrent()
|
||||||
{
|
{
|
||||||
var item = _controller.CurrentItem;
|
var item = _controller.CurrentItem;
|
||||||
@@ -139,8 +240,19 @@ public partial class SchedulePage : Page
|
|||||||
var plan = _controller.Plan;
|
var plan = _controller.Plan;
|
||||||
|
|
||||||
var selected = Timeline.SelectedIndex;
|
var selected = Timeline.SelectedIndex;
|
||||||
var rows = plan.Select((p, i) => new TimelineRow(i, p, i == current)).ToList();
|
// Rows are records: only the ones whose content changed are replaced.
|
||||||
Timeline.ItemsSource = rows;
|
for (var i = 0; i < plan.Count; i++)
|
||||||
|
{
|
||||||
|
var updated = new TimelineRow(i, plan[i], i == current);
|
||||||
|
if (i == _rows.Count)
|
||||||
|
_rows.Add(updated);
|
||||||
|
else if (_rows[i] != updated)
|
||||||
|
_rows[i] = updated;
|
||||||
|
}
|
||||||
|
while (_rows.Count > plan.Count)
|
||||||
|
_rows.RemoveAt(_rows.Count - 1);
|
||||||
|
var rows = _rows;
|
||||||
|
GridColumns.Fit(Timeline);
|
||||||
Timeline.SelectedIndex = selected < rows.Count ? selected : -1;
|
Timeline.SelectedIndex = selected < rows.Count ? selected : -1;
|
||||||
// Follow the broadcast when it moves on; otherwise keep the user's row in view.
|
// Follow the broadcast when it moves on; otherwise keep the user's row in view.
|
||||||
if (current != _scrolledTo && current >= 0 && current < rows.Count)
|
if (current != _scrolledTo && current >= 0 && current < rows.Count)
|
||||||
@@ -152,7 +264,7 @@ public partial class SchedulePage : Page
|
|||||||
|
|
||||||
NowKind.Content = item;
|
NowKind.Content = item;
|
||||||
NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible;
|
NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible;
|
||||||
if (item is not null) NowTitle.Text = item.Title;
|
if (item is not null) NowTitle.Text = item.Title.Length > 0 ? item.Title : item.KindName;
|
||||||
|
|
||||||
UpdateButtons();
|
UpdateButtons();
|
||||||
UpdateProgress();
|
UpdateProgress();
|
||||||
@@ -160,38 +272,60 @@ public partial class SchedulePage : Page
|
|||||||
|
|
||||||
private void UpdateButtons()
|
private void UpdateButtons()
|
||||||
{
|
{
|
||||||
var playing = _controller.IsPlaying;
|
var playing = _expectPlaying ?? _controller.IsPlaying;
|
||||||
StartButton.IsEnabled = !playing && _controller.Plan.Count > 0;
|
PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0);
|
||||||
StopButton.IsEnabled = playing;
|
CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working;
|
||||||
|
// Called every timer tick, so the label and icon change only with the state.
|
||||||
|
if (playing != _shownPlaying)
|
||||||
|
{
|
||||||
|
_shownPlaying = playing;
|
||||||
|
PlayButton.Content = playing ? "Stopp" : "Start";
|
||||||
|
PlayButton.Icon = new SymbolIcon(playing ? SymbolRegular.Stop24 : SymbolRegular.Play24);
|
||||||
|
}
|
||||||
|
|
||||||
var row = Timeline.SelectedItem as TimelineRow;
|
var row = Timeline.SelectedItem as TimelineRow;
|
||||||
|
|
||||||
|
// Only items that are not on air or over can be moved or removed; the one on air can still be edited.
|
||||||
|
var count = _controller.Plan.Count;
|
||||||
|
var current = _controller.CurrentIndex;
|
||||||
|
bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current);
|
||||||
|
var index = row?.Index ?? -1;
|
||||||
|
MoveUpButton.IsEnabled = Editable(index) && Editable(index - 1);
|
||||||
|
MoveDownButton.IsEnabled = Editable(index) && Editable(index + 1);
|
||||||
|
RemoveButton.IsEnabled = Editable(index);
|
||||||
|
var onAir = !_working && playing && index >= 0 && index == current;
|
||||||
|
EditItemButton.IsEnabled = (Editable(index) || onAir) && row!.Item.Kind != ScheduleItemKind.Song;
|
||||||
|
EndNowButton.IsEnabled = !_working && _expectPlaying != false && _controller.CurrentItem is not null;
|
||||||
|
|
||||||
var blocker = row switch
|
var blocker = row switch
|
||||||
{
|
{
|
||||||
null => "Select an upcoming item in the schedule.",
|
null => "Ein kommendes Element im Plan auswählen.",
|
||||||
{ Item.Kind: ScheduleItemKind.News } => "News cannot be replaced.",
|
{ Item.Kind: ScheduleItemKind.News } => "Nachrichten können nicht ersetzt werden.",
|
||||||
_ when playing && row.Index <= _controller.CurrentIndex => "This item is already on air or over.",
|
_ when playing && row.Index <= _controller.CurrentIndex => "Dieses Element ist bereits auf Sendung oder vorbei.",
|
||||||
_ when RequestSong.SelectedItem is null => "Choose a song from the library.",
|
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
SwapHint.Text = blocker ?? $"Replaces the item at {row!.Item.Start:HH:mm:ss}.";
|
SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}.";
|
||||||
SwapButton.IsEnabled = blocker is null;
|
// The hint only matters once a song is chosen.
|
||||||
|
var requested = RequestSong.SelectedItem is not null;
|
||||||
|
SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed;
|
||||||
|
SwapButton.IsEnabled = !_working && requested && blocker is null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void UpdateProgress()
|
private void UpdateProgress()
|
||||||
{
|
{
|
||||||
if (_controller.CurrentItem is not { } item)
|
if (_expectPlaying == false || _controller.CurrentItem is not { } item)
|
||||||
{
|
{
|
||||||
NowProgress.Value = 0;
|
NowProgress.Value = 0;
|
||||||
// Checked here, not in ShowCurrent: the engine starts waiting a moment after Start.
|
// Checked here, not in ShowCurrent: the engine starts waiting a moment after Start.
|
||||||
var waiting = _controller.WaitingUntil;
|
var waiting = _expectPlaying == false ? null : _controller.WaitingUntil;
|
||||||
NowTitle.Text = waiting is { } at ? $"On air at {at:HH:mm:ss}" : "Nothing on air";
|
NowTitle.Text = waiting is { } at ? $"Auf Sendung um {at:HH:mm:ss}" : "Nichts auf Sendung";
|
||||||
NowTime.Text = waiting is null ? " " : "Waiting for the planned start, so the news comes at :00 and :30.";
|
NowTime.Text = " ";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var elapsed = _controller.CurrentElapsed;
|
var elapsed = _controller.CurrentElapsed;
|
||||||
NowProgress.Value = item.Duration.Ticks == 0 ? 0 : (double)elapsed.Ticks / item.Duration.Ticks;
|
NowProgress.Value = item.Duration.Ticks == 0 ? 0 : (double)elapsed.Ticks / item.Duration.Ticks;
|
||||||
NowTime.Text = $"{elapsed:m\\:ss} / {item.Duration:m\\:ss} · planned {item.Start:HH:mm:ss}";
|
NowTime.Text = $"{elapsed:m\\:ss} / {item.Duration:m\\:ss}";
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ShowMessage(InfoBarSeverity severity, string title, string text)
|
private void ShowMessage(InfoBarSeverity severity, string title, string text)
|
||||||
@@ -205,4 +339,6 @@ public partial class SchedulePage : Page
|
|||||||
private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent);
|
private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent);
|
||||||
|
|
||||||
private sealed record SongOption(long Id, string Label);
|
private sealed record SongOption(long Id, string Label);
|
||||||
|
|
||||||
|
private sealed record StartOption(DateTime Time, string Label);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
<Page x:Class="Radiosender.Views.Pages.SettingsPage"
|
||||||
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||||
|
Title="Einstellungen"
|
||||||
|
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||||
|
Loaded="OnLoaded">
|
||||||
|
<Page.Resources>
|
||||||
|
<Style x:Key="Card" TargetType="Border">
|
||||||
|
<Setter Property="Margin" Value="0,0,0,12" />
|
||||||
|
<Setter Property="Padding" Value="16" />
|
||||||
|
<Setter Property="CornerRadius" Value="8" />
|
||||||
|
<Setter Property="BorderThickness" Value="1" />
|
||||||
|
<Setter Property="BorderBrush" Value="{DynamicResource CardStrokeColorDefaultBrush}" />
|
||||||
|
<Setter Property="Background" Value="{DynamicResource CardBackgroundFillColorDefaultBrush}" />
|
||||||
|
</Style>
|
||||||
|
<Style x:Key="Seconds" TargetType="ui:NumberBox" BasedOn="{StaticResource {x:Type ui:NumberBox}}">
|
||||||
|
<Setter Property="Width" Value="130" />
|
||||||
|
<Setter Property="HorizontalAlignment" Value="Left" />
|
||||||
|
<Setter Property="Minimum" Value="5" />
|
||||||
|
<Setter Property="Maximum" Value="300" />
|
||||||
|
<Setter Property="SmallChange" Value="5" />
|
||||||
|
<Setter Property="MaxDecimalPlaces" Value="0" />
|
||||||
|
<Setter Property="ClearButtonEnabled" Value="False" />
|
||||||
|
</Style>
|
||||||
|
<Style x:Key="Minutes" TargetType="ui:NumberBox" BasedOn="{StaticResource {x:Type ui:NumberBox}}">
|
||||||
|
<Setter Property="Width" Value="130" />
|
||||||
|
<Setter Property="HorizontalAlignment" Value="Left" />
|
||||||
|
<Setter Property="Minimum" Value="0" />
|
||||||
|
<Setter Property="Maximum" Value="60" />
|
||||||
|
<Setter Property="SmallChange" Value="1" />
|
||||||
|
<Setter Property="MaxDecimalPlaces" Value="0" />
|
||||||
|
<Setter Property="ClearButtonEnabled" Value="False" />
|
||||||
|
</Style>
|
||||||
|
</Page.Resources>
|
||||||
|
|
||||||
|
<StackPanel MaxWidth="640" Margin="24" HorizontalAlignment="Left">
|
||||||
|
<ui:InfoBar x:Name="Message" Margin="0,0,0,12" IsClosable="True" IsOpen="False" />
|
||||||
|
|
||||||
|
<!-- Speaking alerts: one block per kind -->
|
||||||
|
<Border Style="{StaticResource Card}">
|
||||||
|
<Grid>
|
||||||
|
<Grid.ColumnDefinitions>
|
||||||
|
<ColumnDefinition Width="220" />
|
||||||
|
<ColumnDefinition Width="*" />
|
||||||
|
</Grid.ColumnDefinitions>
|
||||||
|
<Grid.RowDefinitions>
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
<ui:ToggleSwitch x:Name="NewsAlertSwitch" Grid.ColumnSpan="2" Content="Hinweis vor Nachrichten" />
|
||||||
|
<Label Grid.Row="1" Margin="0,12,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Sekunden vor dem Start"
|
||||||
|
Target="{Binding ElementName=NewsSecondsBox}"
|
||||||
|
IsEnabled="{Binding IsChecked, ElementName=NewsAlertSwitch}" />
|
||||||
|
<ui:NumberBox x:Name="NewsSecondsBox" Grid.Row="1" Grid.Column="1" Margin="0,12,0,0"
|
||||||
|
Style="{StaticResource Seconds}"
|
||||||
|
AutomationProperties.Name="Sekunden vor Nachrichten"
|
||||||
|
IsEnabled="{Binding IsChecked, ElementName=NewsAlertSwitch}" />
|
||||||
|
<CheckBox x:Name="NewsSoundBox" Grid.Row="2" Grid.ColumnSpan="2" Margin="0,8,0,0"
|
||||||
|
Content="Bing-Ton abspielen"
|
||||||
|
IsEnabled="{Binding IsChecked, ElementName=NewsAlertSwitch}" />
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<Border Style="{StaticResource Card}">
|
||||||
|
<Grid>
|
||||||
|
<Grid.ColumnDefinitions>
|
||||||
|
<ColumnDefinition Width="220" />
|
||||||
|
<ColumnDefinition Width="*" />
|
||||||
|
</Grid.ColumnDefinitions>
|
||||||
|
<Grid.RowDefinitions>
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
<ui:ToggleSwitch x:Name="ModeratorAlertSwitch" Grid.ColumnSpan="2" Content="Hinweis vor Moderation" />
|
||||||
|
<Label Grid.Row="1" Margin="0,12,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Sekunden vor dem Start"
|
||||||
|
Target="{Binding ElementName=ModeratorSecondsBox}"
|
||||||
|
IsEnabled="{Binding IsChecked, ElementName=ModeratorAlertSwitch}" />
|
||||||
|
<ui:NumberBox x:Name="ModeratorSecondsBox" Grid.Row="1" Grid.Column="1" Margin="0,12,0,0"
|
||||||
|
Style="{StaticResource Seconds}"
|
||||||
|
AutomationProperties.Name="Sekunden vor Moderation"
|
||||||
|
IsEnabled="{Binding IsChecked, ElementName=ModeratorAlertSwitch}" />
|
||||||
|
<CheckBox x:Name="ModeratorSoundBox" Grid.Row="2" Grid.ColumnSpan="2" Margin="0,8,0,0"
|
||||||
|
Content="Bing-Ton abspielen"
|
||||||
|
IsEnabled="{Binding IsChecked, ElementName=ModeratorAlertSwitch}" />
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Minutes per hour -->
|
||||||
|
<Border Style="{StaticResource Card}">
|
||||||
|
<Grid>
|
||||||
|
<Grid.ColumnDefinitions>
|
||||||
|
<ColumnDefinition Width="220" />
|
||||||
|
<ColumnDefinition Width="*" />
|
||||||
|
</Grid.ColumnDefinitions>
|
||||||
|
<Grid.RowDefinitions>
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
<ui:TextBlock Grid.ColumnSpan="2" FontTypography="BodyStrong" Text="Minuten pro Stunde" />
|
||||||
|
<Label Grid.Row="1" Margin="0,12,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Nachrichten" Target="{Binding ElementName=NewsMinutesBox}" />
|
||||||
|
<ui:NumberBox x:Name="NewsMinutesBox" Grid.Row="1" Grid.Column="1" Margin="0,12,0,0"
|
||||||
|
Style="{StaticResource Minutes}" Minimum="2"
|
||||||
|
AutomationProperties.Name="Nachrichten-Minuten pro Stunde" />
|
||||||
|
<Label Grid.Row="2" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Moderation" Target="{Binding ElementName=ModeratorMinutesBox}" />
|
||||||
|
<ui:NumberBox x:Name="ModeratorMinutesBox" Grid.Row="2" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
Style="{StaticResource Minutes}"
|
||||||
|
AutomationProperties.Name="Moderations-Minuten pro Stunde" />
|
||||||
|
<Label Grid.Row="3" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Werbung" Target="{Binding ElementName=AdMinutesBox}" />
|
||||||
|
<ui:NumberBox x:Name="AdMinutesBox" Grid.Row="3" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
Style="{StaticResource Minutes}"
|
||||||
|
AutomationProperties.Name="Werbe-Minuten pro Stunde" />
|
||||||
|
<ui:TextBlock Grid.Row="4" Grid.ColumnSpan="2" Margin="0,12,0,0" TextWrapping="Wrap"
|
||||||
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
|
Text="Sollwerte, zusammen höchstens 60 Minuten. Gilt für den nächsten Plan." />
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
|
||||||
|
<ui:Button Appearance="Primary" MinWidth="110" Content="Speichern" Icon="{ui:SymbolIcon Save24}" Click="OnSave" />
|
||||||
|
<ui:Button Margin="8,0,0,0" MinWidth="110" Content="ZurĂĽcksetzen" Icon="{ui:SymbolIcon ArrowReset24}"
|
||||||
|
ToolTip="Setzt die Standardwerte ins Formular. Mit Speichern ĂĽbernehmen."
|
||||||
|
Click="OnReset" />
|
||||||
|
</StackPanel>
|
||||||
|
</StackPanel>
|
||||||
|
</Page>
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
using System.IO;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using Radiosender.Services;
|
||||||
|
using Wpf.Ui.Controls;
|
||||||
|
|
||||||
|
namespace Radiosender.Views.Pages;
|
||||||
|
|
||||||
|
/// <summary>Edits <see cref="AppSettings"/>. Nothing changes until Save.</summary>
|
||||||
|
public partial class SettingsPage : Page
|
||||||
|
{
|
||||||
|
public SettingsPage() => InitializeComponent();
|
||||||
|
|
||||||
|
// Loaded fires on every navigation to the page, so unsaved edits from an earlier visit are dropped.
|
||||||
|
private void OnLoaded(object sender, RoutedEventArgs e) => Show(App.Settings);
|
||||||
|
|
||||||
|
private void Show(AppSettings settings)
|
||||||
|
{
|
||||||
|
NewsAlertSwitch.IsChecked = settings.NewsAlert;
|
||||||
|
NewsSecondsBox.Value = settings.NewsAlertSeconds;
|
||||||
|
NewsSoundBox.IsChecked = settings.NewsAlertSound;
|
||||||
|
ModeratorAlertSwitch.IsChecked = settings.ModeratorAlert;
|
||||||
|
ModeratorSecondsBox.Value = settings.ModeratorAlertSeconds;
|
||||||
|
ModeratorSoundBox.IsChecked = settings.ModeratorAlertSound;
|
||||||
|
NewsMinutesBox.Value = settings.NewsMinutesPerHour;
|
||||||
|
ModeratorMinutesBox.Value = settings.ModeratorMinutesPerHour;
|
||||||
|
AdMinutesBox.Value = settings.AdMinutesPerHour;
|
||||||
|
}
|
||||||
|
|
||||||
|
// An emptied number box counts as its default.
|
||||||
|
private static AppSettings Defaults { get; } = new();
|
||||||
|
|
||||||
|
private AppSettings Read() => new()
|
||||||
|
{
|
||||||
|
NewsAlert = NewsAlertSwitch.IsChecked == true,
|
||||||
|
NewsAlertSeconds = (int)(NewsSecondsBox.Value ?? Defaults.NewsAlertSeconds),
|
||||||
|
NewsAlertSound = NewsSoundBox.IsChecked == true,
|
||||||
|
ModeratorAlert = ModeratorAlertSwitch.IsChecked == true,
|
||||||
|
ModeratorAlertSeconds = (int)(ModeratorSecondsBox.Value ?? Defaults.ModeratorAlertSeconds),
|
||||||
|
ModeratorAlertSound = ModeratorSoundBox.IsChecked == true,
|
||||||
|
NewsMinutesPerHour = (int)(NewsMinutesBox.Value ?? Defaults.NewsMinutesPerHour),
|
||||||
|
ModeratorMinutesPerHour = (int)(ModeratorMinutesBox.Value ?? Defaults.ModeratorMinutesPerHour),
|
||||||
|
AdMinutesPerHour = (int)(AdMinutesBox.Value ?? Defaults.AdMinutesPerHour),
|
||||||
|
};
|
||||||
|
|
||||||
|
private void OnSave(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
var settings = Read();
|
||||||
|
if (settings.Validate() is { } problem)
|
||||||
|
{
|
||||||
|
ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", problem);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
App.SaveSettings(settings);
|
||||||
|
ShowMessage(InfoBarSeverity.Success, "Gespeichert", "Minuten pro Stunde gelten für den nächsten Plan.");
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnReset(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
Show(Defaults);
|
||||||
|
ShowMessage(InfoBarSeverity.Informational, "Standardwerte eingesetzt", "Mit Speichern ĂĽbernehmen.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ShowMessage(InfoBarSeverity severity, string title, string text)
|
||||||
|
{
|
||||||
|
Message.Severity = severity;
|
||||||
|
Message.Title = title;
|
||||||
|
Message.Message = text;
|
||||||
|
Message.IsOpen = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<ui:FluentWindow x:Class="Radiosender.Views.ScheduleItemEditWindow"
|
||||||
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||||
|
Title="Element bearbeiten"
|
||||||
|
Width="400" SizeToContent="Height"
|
||||||
|
ResizeMode="NoResize"
|
||||||
|
ShowInTaskbar="False"
|
||||||
|
ExtendsContentIntoTitleBar="True"
|
||||||
|
WindowBackdropType="Mica"
|
||||||
|
WindowStartupLocation="CenterOwner"
|
||||||
|
FocusManager.FocusedElement="{Binding ElementName=TitleBox}">
|
||||||
|
<StackPanel>
|
||||||
|
<ui:TitleBar x:Name="Bar" Title="Element bearbeiten" ShowMinimize="False" ShowMaximize="False" />
|
||||||
|
|
||||||
|
<StackPanel Margin="24,8,24,24">
|
||||||
|
<Label Content="_Titel" Target="{Binding ElementName=TitleBox}" />
|
||||||
|
<ui:TextBox x:Name="TitleBox" Margin="0,0,0,12" PlaceholderText="Optional" />
|
||||||
|
|
||||||
|
<Label x:Name="DurationLabel" Content="_Länge (m:ss)" Target="{Binding ElementName=DurationBox}" />
|
||||||
|
<ui:TextBox x:Name="DurationBox" />
|
||||||
|
|
||||||
|
<TextBlock x:Name="ErrorText"
|
||||||
|
Margin="0,12,0,0"
|
||||||
|
Foreground="{DynamicResource SystemFillColorCriticalBrush}"
|
||||||
|
Text="Länge als Minuten und Sekunden eingeben, zum Beispiel 5:00."
|
||||||
|
TextWrapping="Wrap"
|
||||||
|
Visibility="Collapsed" />
|
||||||
|
|
||||||
|
<StackPanel Margin="0,24,0,0" HorizontalAlignment="Right" Orientation="Horizontal">
|
||||||
|
<ui:Button Content="Speichern" Appearance="Primary" IsDefault="True" MinWidth="90" Click="OnSave" />
|
||||||
|
<ui:Button Margin="8,0,0,0" Content="Abbrechen" IsCancel="True" MinWidth="90" />
|
||||||
|
</StackPanel>
|
||||||
|
</StackPanel>
|
||||||
|
</StackPanel>
|
||||||
|
</ui:FluentWindow>
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Windows;
|
||||||
|
using Radiosender.Models;
|
||||||
|
using Wpf.Ui.Controls;
|
||||||
|
|
||||||
|
namespace Radiosender.Views;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Dialog for the title of a news, ad or moderator item and, for news and moderator items, its length.
|
||||||
|
/// Only collects input; the caller changes the schedule.
|
||||||
|
/// </summary>
|
||||||
|
public partial class ScheduleItemEditWindow : FluentWindow
|
||||||
|
{
|
||||||
|
private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"];
|
||||||
|
|
||||||
|
public ScheduleItemEditWindow(ScheduleItem item)
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
Title = Bar.Title = $"{item.KindName} bearbeiten";
|
||||||
|
TitleBox.Text = item.Title;
|
||||||
|
DurationBox.Text = item.Duration.ToString(@"m\:ss");
|
||||||
|
Duration = item.Duration;
|
||||||
|
// Ads keep their length.
|
||||||
|
DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string ItemTitle => TitleBox.Text;
|
||||||
|
|
||||||
|
public TimeSpan Duration { get; private set; }
|
||||||
|
|
||||||
|
private void OnSave(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
if (DurationBox.IsEnabled)
|
||||||
|
{
|
||||||
|
if (!TimeSpan.TryParseExact(DurationBox.Text.Trim(), DurationFormats, CultureInfo.InvariantCulture, out var duration)
|
||||||
|
|| duration <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
ErrorText.Visibility = Visibility.Visible;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Duration = duration;
|
||||||
|
}
|
||||||
|
|
||||||
|
DialogResult = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||||
Title="Edit song"
|
Title="Song bearbeiten"
|
||||||
Width="460" SizeToContent="Height"
|
Width="460" SizeToContent="Height"
|
||||||
ResizeMode="NoResize"
|
ResizeMode="NoResize"
|
||||||
ShowInTaskbar="False"
|
ShowInTaskbar="False"
|
||||||
@@ -11,30 +11,30 @@
|
|||||||
WindowStartupLocation="CenterOwner"
|
WindowStartupLocation="CenterOwner"
|
||||||
FocusManager.FocusedElement="{Binding ElementName=TitleBox}">
|
FocusManager.FocusedElement="{Binding ElementName=TitleBox}">
|
||||||
<StackPanel>
|
<StackPanel>
|
||||||
<ui:TitleBar Title="Edit song" ShowMinimize="False" ShowMaximize="False" />
|
<ui:TitleBar Title="Song bearbeiten" ShowMinimize="False" ShowMaximize="False" />
|
||||||
|
|
||||||
<StackPanel Margin="24,8,24,24">
|
<StackPanel Margin="24,8,24,24">
|
||||||
<Label Content="_Title" Target="{Binding ElementName=TitleBox}" />
|
<Label Content="_Titel" Target="{Binding ElementName=TitleBox}" />
|
||||||
<ui:TextBox x:Name="TitleBox" Margin="0,0,0,12" />
|
<ui:TextBox x:Name="TitleBox" Margin="0,0,0,12" />
|
||||||
|
|
||||||
<Label Content="_Artist" Target="{Binding ElementName=ArtistBox}" />
|
<Label Content="_Interpret" Target="{Binding ElementName=ArtistBox}" />
|
||||||
<ui:TextBox x:Name="ArtistBox" Margin="0,0,0,12" />
|
<ui:TextBox x:Name="ArtistBox" Margin="0,0,0,12" />
|
||||||
|
|
||||||
<Label Content="_License" Target="{Binding ElementName=LicenseBox}" />
|
<Label Content="_Lizenz" Target="{Binding ElementName=LicenseBox}" />
|
||||||
<ui:TextBox x:Name="LicenseBox" Margin="0,0,0,12" PlaceholderText="Optional, e.g. CC BY 4.0" />
|
<ui:TextBox x:Name="LicenseBox" Margin="0,0,0,12" PlaceholderText="Optional, z. B. CC BY 4.0" />
|
||||||
|
|
||||||
<Label Content="Attri_bution" Target="{Binding ElementName=AttributionBox}" />
|
<Label Content="_Namensnennung" Target="{Binding ElementName=AttributionBox}" />
|
||||||
<ui:TextBox x:Name="AttributionBox" PlaceholderText="Optional" />
|
<ui:TextBox x:Name="AttributionBox" PlaceholderText="Optional" />
|
||||||
|
|
||||||
<TextBlock x:Name="ErrorText"
|
<TextBlock x:Name="ErrorText"
|
||||||
Margin="0,12,0,0"
|
Margin="0,12,0,0"
|
||||||
Foreground="{DynamicResource SystemFillColorCriticalBrush}"
|
Foreground="{DynamicResource SystemFillColorCriticalBrush}"
|
||||||
Text="Title and artist are required."
|
Text="Titel und Interpret sind erforderlich."
|
||||||
Visibility="Collapsed" />
|
Visibility="Collapsed" />
|
||||||
|
|
||||||
<StackPanel Margin="0,24,0,0" HorizontalAlignment="Right" Orientation="Horizontal">
|
<StackPanel Margin="0,24,0,0" HorizontalAlignment="Right" Orientation="Horizontal">
|
||||||
<ui:Button Content="Save" Appearance="Primary" IsDefault="True" MinWidth="90" Click="OnSave" />
|
<ui:Button Content="Speichern" Appearance="Primary" IsDefault="True" MinWidth="90" Click="OnSave" />
|
||||||
<ui:Button Margin="8,0,0,0" Content="Cancel" IsCancel="True" MinWidth="90" />
|
<ui:Button Margin="8,0,0,0" Content="Abbrechen" IsCancel="True" MinWidth="90" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Tests;
|
||||||
|
|
||||||
|
public sealed class AppSettingsTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
|
||||||
|
|
||||||
|
private string File => Path.Combine(_directory, "settings.json");
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (Directory.Exists(_directory))
|
||||||
|
Directory.Delete(_directory, recursive: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Defaults_AreValidAndMatchTheOriginalSchedule()
|
||||||
|
{
|
||||||
|
var defaults = new AppSettings();
|
||||||
|
|
||||||
|
Assert.Null(defaults.Validate());
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(5), defaults.ToScheduleOptions().NewsDuration);
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(20), defaults.ToScheduleOptions().AdsPerHour);
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(10), defaults.ToScheduleOptions().ModeratorPerHour);
|
||||||
|
Assert.True(defaults.NewsAlert && defaults.ModeratorAlert);
|
||||||
|
Assert.True(defaults.NewsAlertSound && defaults.ModeratorAlertSound);
|
||||||
|
Assert.Equal(30, defaults.NewsAlertSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SaveAndLoad_RoundTrip()
|
||||||
|
{
|
||||||
|
var settings = new AppSettings { NewsAlert = false, ModeratorAlertSeconds = 45, ModeratorAlertSound = true, AdMinutesPerHour = 6 };
|
||||||
|
|
||||||
|
settings.Save(File);
|
||||||
|
|
||||||
|
Assert.Equal(settings, AppSettings.Load(File));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Load_FallsBackToDefaultsForMissingBrokenOrInvalidFiles()
|
||||||
|
{
|
||||||
|
Assert.Equal(new AppSettings(), AppSettings.Load(File));
|
||||||
|
|
||||||
|
Directory.CreateDirectory(_directory);
|
||||||
|
System.IO.File.WriteAllText(File, "{ not json");
|
||||||
|
Assert.Equal(new AppSettings(), AppSettings.Load(File));
|
||||||
|
|
||||||
|
System.IO.File.WriteAllText(File, """{"AdMinutesPerHour":500}""");
|
||||||
|
Assert.Equal(new AppSettings(), AppSettings.Load(File));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(10, 30, 20)] // exactly one hour
|
||||||
|
[InlineData(2, 0, 0)]
|
||||||
|
public void Validate_AcceptsUpToSixtyMinutesTogether(int news, int moderator, int ads)
|
||||||
|
{
|
||||||
|
Assert.Null(new AppSettings { NewsMinutesPerHour = news, ModeratorMinutesPerHour = moderator, AdMinutesPerHour = ads }.Validate());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(4, 30, 10, 10, 10)] // alert too early
|
||||||
|
[InlineData(30, 301, 10, 10, 10)] // alert too late
|
||||||
|
[InlineData(30, 30, 1, 10, 10)] // too little news
|
||||||
|
[InlineData(30, 30, 10, 25, 26)] // more than 60 minutes together
|
||||||
|
[InlineData(30, 30, 10, -1, 5)] // negative
|
||||||
|
public void Validate_ReportsValuesOutOfRange(int newsSeconds, int moderatorSeconds, int news, int moderator, int ads)
|
||||||
|
{
|
||||||
|
var settings = new AppSettings
|
||||||
|
{
|
||||||
|
NewsAlertSeconds = newsSeconds,
|
||||||
|
ModeratorAlertSeconds = moderatorSeconds,
|
||||||
|
NewsMinutesPerHour = news,
|
||||||
|
ModeratorMinutesPerHour = moderator,
|
||||||
|
AdMinutesPerHour = ads,
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.NotNull(settings.Validate());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,6 +52,16 @@ public sealed class OpenverseTests : IDisposable
|
|||||||
|
|
||||||
private string[] MusicFiles() => Directory.Exists(MusicFolder) ? Directory.GetFiles(MusicFolder) : [];
|
private string[] MusicFiles() => Directory.Exists(MusicFolder) ? Directory.GetFiles(MusicFolder) : [];
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Track_DecodesHtmlEntitiesInTexts()
|
||||||
|
{
|
||||||
|
var track = new OpenverseTrack { Title = "Rock & Roll", Creator = "Angus & Friends", Attribution = ""Rock" by Angus" };
|
||||||
|
|
||||||
|
Assert.Equal("Rock & Roll", track.Title);
|
||||||
|
Assert.Equal("Angus & Friends", track.Creator);
|
||||||
|
Assert.Equal("\"Rock\" by Angus", track.Attribution);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Search_ParsesResults()
|
public async Task Search_ParsesResults()
|
||||||
{
|
{
|
||||||
@@ -87,7 +97,7 @@ public sealed class OpenverseTests : IDisposable
|
|||||||
|
|
||||||
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
|
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
|
||||||
|
|
||||||
Assert.Contains("rate limit", error.Message);
|
Assert.Contains("Limit erreicht", error.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -101,7 +111,7 @@ public sealed class OpenverseTests : IDisposable
|
|||||||
|
|
||||||
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
|
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
|
||||||
|
|
||||||
Assert.Contains("timed out", error.Message);
|
Assert.Contains("ZeitĂĽberschreitung", error.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -228,7 +238,7 @@ public sealed class OpenverseTests : IDisposable
|
|||||||
|
|
||||||
var error = await Assert.ThrowsAsync<OpenverseException>(() => controller.ImportAsync(Track()));
|
var error = await Assert.ThrowsAsync<OpenverseException>(() => controller.ImportAsync(Track()));
|
||||||
|
|
||||||
Assert.Contains("already in the library", error.Message);
|
Assert.Contains("bereits in der Bibliothek", error.Message);
|
||||||
Assert.Equal(1, downloads);
|
Assert.Equal(1, downloads);
|
||||||
Assert.Single(songs.GetAll());
|
Assert.Single(songs.GetAll());
|
||||||
Assert.Single(MusicFiles());
|
Assert.Single(MusicFiles());
|
||||||
|
|||||||
@@ -52,6 +52,254 @@ public sealed class ScheduleControllerTests : IDisposable
|
|||||||
Assert.Same(plan, controller.Plan);
|
Assert.Same(plan, controller.Plan);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CreatePlan_StartsAtTheGivenHour()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
|
||||||
|
var plan = Create().CreatePlan(1, new DateTime(2026, 11, 23, 18, 0, 0));
|
||||||
|
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 23, 18, 0, 0), plan[0].Start);
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 23, 19, 0, 0), plan[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CreatePlan_UnlimitedPlansTheLookahead()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
|
||||||
|
var plan = controller.CreatePlan(null);
|
||||||
|
|
||||||
|
Assert.True(controller.IsUnlimited);
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 23, 20, 0, 0), plan[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unlimited_AppendsHoursWhilePlaying()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var hold = new TaskCompletionSource();
|
||||||
|
var controller = Create((_, token) => hold.Task.WaitAsync(token));
|
||||||
|
controller.CreatePlan(null); // 15:00 to 20:00
|
||||||
|
var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
controller.ItemStarted += (_, _) => first.TrySetResult();
|
||||||
|
|
||||||
|
_now = new DateTime(2026, 11, 23, 16, 30, 0); // the news at 16:30 goes on air
|
||||||
|
controller.Start();
|
||||||
|
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
var plan = controller.Plan;
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 23, 22, 0, 0), plan[^1].End); // 5 h ahead of 16:30, in full hours
|
||||||
|
for (var i = 1; i < plan.Count; i++)
|
||||||
|
Assert.Equal(plan[i - 1].End, plan[i].Start);
|
||||||
|
Assert.Equal(ScheduleItemKind.News, controller.CurrentItem!.Kind);
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StartNow_PlansFromThisMomentAndGoesOnAir()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var hold = new TaskCompletionSource();
|
||||||
|
var controller = Create((_, token) => hold.Task.WaitAsync(token));
|
||||||
|
|
||||||
|
controller.StartNow(1);
|
||||||
|
|
||||||
|
Assert.True(controller.IsPlaying);
|
||||||
|
Assert.Equal(_now, controller.Plan[0].Start);
|
||||||
|
Assert.NotEqual(ScheduleItemKind.News, controller.Plan[0].Kind);
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 23, 16, 0, 0), controller.Plan[^1].End);
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertContiguousFrom(IReadOnlyList<ScheduleItem> plan, DateTime start)
|
||||||
|
{
|
||||||
|
Assert.Equal(start, plan[0].Start);
|
||||||
|
for (var i = 1; i < plan.Count; i++)
|
||||||
|
Assert.Equal(plan[i - 1].End, plan[i].Start);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Move_SwapsItemsAndShiftsTheTimes()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
var before = controller.CreatePlan(1);
|
||||||
|
|
||||||
|
var plan = controller.Move(2, -2);
|
||||||
|
|
||||||
|
Assert.Equal(before[2].Song?.Id, plan[0].Song?.Id);
|
||||||
|
Assert.Equal(before[2].Kind, plan[0].Kind);
|
||||||
|
Assert.Equal(ScheduleItemKind.News, plan[1].Kind);
|
||||||
|
Assert.Equal(before.Count, plan.Count);
|
||||||
|
AssertContiguousFrom(plan, before[0].Start);
|
||||||
|
Assert.Equal(before[^1].End, plan[^1].End);
|
||||||
|
Assert.Same(plan, controller.Plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Move_PastTheEdgeThrows()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
controller.CreatePlan(1);
|
||||||
|
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.Move(0, -1));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Remove_ClosesTheGap()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
var before = controller.CreatePlan(1);
|
||||||
|
|
||||||
|
var plan = controller.Remove(1);
|
||||||
|
|
||||||
|
Assert.Equal(before.Count - 1, plan.Count);
|
||||||
|
AssertContiguousFrom(plan, before[0].Start);
|
||||||
|
Assert.Equal(before[^1].End - before[1].Duration, plan[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EditItem_SetsTitleAndLengthOfNews()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
var before = controller.CreatePlan(1);
|
||||||
|
|
||||||
|
var plan = controller.EditItem(0, " Evening news ", TimeSpan.FromMinutes(3));
|
||||||
|
|
||||||
|
Assert.Equal("Evening news", plan[0].Title);
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(3), plan[0].Duration);
|
||||||
|
AssertContiguousFrom(plan, before[0].Start);
|
||||||
|
Assert.Equal(before[^1].End - TimeSpan.FromMinutes(2), plan[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EditItem_RejectsSongsAndAdLengths()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
var plan = controller.CreatePlan(1);
|
||||||
|
var song = plan.ToList().FindIndex(i => i.Kind == ScheduleItemKind.Song);
|
||||||
|
var ad = plan.ToList().FindIndex(i => i.Kind == ScheduleItemKind.Ad);
|
||||||
|
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.EditItem(song, "x", plan[song].Duration));
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.EditItem(ad, "x", plan[ad].Duration + TimeSpan.FromSeconds(1)));
|
||||||
|
Assert.Equal("Spot", controller.EditItem(ad, "Spot", plan[ad].Duration)[ad].Title);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Edits_WhilePlayingRejectTheItemOnAir()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var hold = new TaskCompletionSource();
|
||||||
|
var controller = Create((_, token) => hold.Task.WaitAsync(token));
|
||||||
|
controller.CreatePlan(1);
|
||||||
|
var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
controller.ItemStarted += (_, _) => first.TrySetResult();
|
||||||
|
_now = controller.Plan[0].Start;
|
||||||
|
controller.Start();
|
||||||
|
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.Remove(0));
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.Move(1, -1));
|
||||||
|
var count = controller.Plan.Count;
|
||||||
|
Assert.Equal(count - 1, controller.Remove(1).Count);
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<(ScheduleController Controller, SemaphoreSlim Started)> OnAirWithTheFirstNewsAsync()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var hold = new TaskCompletionSource();
|
||||||
|
var controller = Create((_, token) => hold.Task.WaitAsync(token));
|
||||||
|
controller.CreatePlan(1);
|
||||||
|
var started = new SemaphoreSlim(0);
|
||||||
|
controller.ItemStarted += (_, _) => started.Release();
|
||||||
|
_now = controller.Plan[0].Start;
|
||||||
|
controller.Start();
|
||||||
|
Assert.True(await started.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||||
|
return (controller, started);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EndCurrentNow_EndsTheItemOnAirAndStartsTheNext()
|
||||||
|
{
|
||||||
|
var (controller, started) = await OnAirWithTheFirstNewsAsync();
|
||||||
|
_now = _now.AddMinutes(2);
|
||||||
|
|
||||||
|
var plan = controller.EndCurrentNow();
|
||||||
|
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(2), plan[0].Duration);
|
||||||
|
AssertContiguousFrom(plan, plan[0].Start);
|
||||||
|
Assert.Equal(_now, plan[1].Start);
|
||||||
|
Assert.True(await started.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||||
|
Assert.Equal(1, controller.CurrentIndex);
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EndCurrentNow_WithNothingOnAirThrows()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
controller.CreatePlan(1);
|
||||||
|
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.EndCurrentNow());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EditItem_ChangesTheItemOnAirButItCannotBeRemoved()
|
||||||
|
{
|
||||||
|
var (controller, _) = await OnAirWithTheFirstNewsAsync();
|
||||||
|
var start = controller.Plan[0].Start;
|
||||||
|
|
||||||
|
var plan = controller.EditItem(0, "Late news", TimeSpan.FromMinutes(7));
|
||||||
|
|
||||||
|
Assert.Equal("Late news", plan[0].Title);
|
||||||
|
Assert.Equal(start.AddMinutes(7), plan[1].Start);
|
||||||
|
Assert.Equal(0, controller.CurrentIndex);
|
||||||
|
Assert.Equal("Late news", controller.CurrentItem!.Title);
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.Remove(0));
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EditItem_ShorteningTheItemOnAirBelowItsRunTimeEndsIt()
|
||||||
|
{
|
||||||
|
var (controller, started) = await OnAirWithTheFirstNewsAsync();
|
||||||
|
_now = _now.AddMinutes(3);
|
||||||
|
|
||||||
|
controller.EditItem(0, "", TimeSpan.FromMinutes(1));
|
||||||
|
|
||||||
|
Assert.True(await started.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||||
|
Assert.Equal(1, controller.CurrentIndex);
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UpcomingSpeech_ReturnsNewsWithinTheLeadTimeWhileOnAir()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var hold = new TaskCompletionSource();
|
||||||
|
var controller = Create((_, token) => hold.Task.WaitAsync(token));
|
||||||
|
controller.CreatePlan(1); // news at 15:00
|
||||||
|
var lead = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_now = new DateTime(2026, 11, 23, 14, 59, 40);
|
||||||
|
Assert.Null(controller.UpcomingSpeech(lead, lead)); // not on air
|
||||||
|
controller.Start();
|
||||||
|
Assert.Equal(ScheduleItemKind.News, controller.UpcomingSpeech(lead, lead)!.Kind);
|
||||||
|
Assert.Null(controller.UpcomingSpeech(null, lead)); // news alert switched off
|
||||||
|
_now = new DateTime(2026, 11, 23, 14, 59, 0);
|
||||||
|
Assert.Null(controller.UpcomingSpeech(lead, lead));
|
||||||
|
Assert.NotNull(controller.UpcomingSpeech(TimeSpan.FromSeconds(60), null)); // longer lead time
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void CreatePlan_ThrowsScheduleExceptionForEmptyLibrary()
|
public void CreatePlan_ThrowsScheduleExceptionForEmptyLibrary()
|
||||||
{
|
{
|
||||||
@@ -146,7 +394,7 @@ public sealed class ScheduleControllerTests : IDisposable
|
|||||||
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
var onAir = Assert.Throws<ScheduleException>(() => controller.Swap(0, request.Id));
|
var onAir = Assert.Throws<ScheduleException>(() => controller.Swap(0, request.Id));
|
||||||
Assert.Contains("already on air", onAir.Message);
|
Assert.Contains("bereits auf Sendung", onAir.Message);
|
||||||
controller.Swap(1, request.Id);
|
controller.Swap(1, request.Id);
|
||||||
Assert.Equal(request.Id, controller.Plan[1].Song!.Id);
|
Assert.Equal(request.Id, controller.Plan[1].Song!.Id);
|
||||||
controller.Stop();
|
controller.Stop();
|
||||||
|
|||||||
@@ -75,21 +75,29 @@ public class ScheduleGeneratorTests
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static TimeSpan Total(IEnumerable<ScheduleItem> items, ScheduleItemKind kind) =>
|
||||||
|
TimeSpan.FromTicks(items.Where(i => i.Kind == kind).Sum(i => i.Duration.Ticks));
|
||||||
|
|
||||||
|
// The targets are met as closely as the songs allow; with this library that is within a few seconds per hour.
|
||||||
|
private static readonly TimeSpan TargetTolerance = TimeSpan.FromSeconds(15);
|
||||||
|
|
||||||
|
private static void AssertNear(TimeSpan expected, TimeSpan actual, string what) =>
|
||||||
|
Assert.True((actual - expected).Duration() <= TargetTolerance, $"{what}: {actual}, target {expected}");
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[MemberData(nameof(Seeds))]
|
[MemberData(nameof(Seeds))]
|
||||||
public void AdsAndModeratorStayWithinTwentyMinutesPerHour(int seed)
|
public void AdsAndModeratorMeetTheirTargetsPerHour(int seed)
|
||||||
{
|
{
|
||||||
|
var options = new ScheduleOptions();
|
||||||
var items = Generate(seed);
|
var items = Generate(seed);
|
||||||
|
|
||||||
for (var hour = 0; hour < 3; hour++)
|
for (var hour = 0; hour < 3; hour++)
|
||||||
{
|
{
|
||||||
var from = Start.AddHours(hour);
|
var from = Start.AddHours(hour);
|
||||||
var filler = items
|
var inHour = items.Where(i => i.Start >= from && i.Start < from.AddHours(1)).ToList();
|
||||||
.Where(i => i.Start >= from && i.Start < from.AddHours(1))
|
|
||||||
.Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator)
|
|
||||||
.Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration);
|
|
||||||
|
|
||||||
Assert.InRange(filler, TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(20));
|
AssertNear(options.AdsPerHour, Total(inHour, ScheduleItemKind.Ad), $"ads in hour {hour}");
|
||||||
|
AssertNear(options.ModeratorPerHour, Total(inHour, ScheduleItemKind.Moderator), $"moderator in hour {hour}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,6 +105,7 @@ public class ScheduleGeneratorTests
|
|||||||
[MemberData(nameof(Seeds))]
|
[MemberData(nameof(Seeds))]
|
||||||
public void NoAdBlockIsLongerThanTheConfiguredMaximum(int seed)
|
public void NoAdBlockIsLongerThanTheConfiguredMaximum(int seed)
|
||||||
{
|
{
|
||||||
|
// Moderator talk separates the ad pieces, so ten one-minute ads per half hour never run together.
|
||||||
var options = new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(1) };
|
var options = new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(1) };
|
||||||
var block = TimeSpan.Zero;
|
var block = TimeSpan.Zero;
|
||||||
|
|
||||||
@@ -133,13 +142,87 @@ public class ScheduleGeneratorTests
|
|||||||
Assert.Throws<ScheduleException>(() => generator.Generate(Start, 1, []));
|
Assert.Throws<ScheduleException>(() => generator.Generate(Start, 1, []));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Seeds))]
|
||||||
|
public void Generate_FromAnOddTimeLeadsInWithMusicUpToTheFirstNews(int seed)
|
||||||
|
{
|
||||||
|
var start = Start.AddMinutes(37).AddSeconds(12);
|
||||||
|
var items = new ScheduleGenerator(new ScheduleOptions(), new Random(seed)).Generate(start, 1, Library);
|
||||||
|
|
||||||
|
Assert.Equal(start, items[0].Start);
|
||||||
|
for (var i = 1; i < items.Count; i++)
|
||||||
|
Assert.Equal(items[i - 1].End, items[i].Start);
|
||||||
|
var firstNews = items.ToList().FindIndex(i => i.Kind == ScheduleItemKind.News);
|
||||||
|
Assert.Equal(Start.AddHours(1), items[firstNews].Start);
|
||||||
|
Assert.Equal(ScheduleItemKind.Song, items[firstNews - 1].Kind);
|
||||||
|
Assert.Equal(Start.AddHours(2), items[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Generate_FillsALeadInTooShortForASongWithModeratorTalk()
|
||||||
|
{
|
||||||
|
var start = Start.AddMinutes(28);
|
||||||
|
var items = new ScheduleGenerator(new ScheduleOptions(), new Random(1)).Generate(start, 1, Library);
|
||||||
|
|
||||||
|
Assert.Equal(ScheduleItemKind.Moderator, items[0].Kind);
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(2), items[0].Duration);
|
||||||
|
Assert.Equal(ScheduleItemKind.News, items[1].Kind);
|
||||||
|
Assert.Equal(Start.AddMinutes(90), items[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Generate_LeavesNewsAdAndModeratorTitlesEmpty()
|
||||||
|
{
|
||||||
|
var items = Generate(1);
|
||||||
|
|
||||||
|
Assert.All(items, i => Assert.Equal(i.Kind != ScheduleItemKind.Song, i.Title.Length == 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Seeds))]
|
||||||
|
public void Generate_FollowsChangedTargets(int seed)
|
||||||
|
{
|
||||||
|
var options = new ScheduleOptions
|
||||||
|
{
|
||||||
|
NewsDuration = TimeSpan.FromMinutes(3),
|
||||||
|
AdsPerHour = TimeSpan.FromMinutes(4),
|
||||||
|
ModeratorPerHour = TimeSpan.FromMinutes(12),
|
||||||
|
};
|
||||||
|
var items = Generate(seed, hours: 2, options);
|
||||||
|
|
||||||
|
Assert.All(items.Where(i => i.Kind == ScheduleItemKind.News), n => Assert.Equal(TimeSpan.FromMinutes(3), n.Duration));
|
||||||
|
for (var hour = 0; hour < 2; hour++)
|
||||||
|
{
|
||||||
|
var inHour = items.Where(i => i.Start >= Start.AddHours(hour) && i.Start < Start.AddHours(hour + 1)).ToList();
|
||||||
|
AssertNear(options.AdsPerHour, Total(inHour, ScheduleItemKind.Ad), $"ads in hour {hour}");
|
||||||
|
AssertNear(options.ModeratorPerHour, Total(inHour, ScheduleItemKind.Moderator), $"moderator in hour {hour}");
|
||||||
|
}
|
||||||
|
Assert.Equal(Start.AddHours(2), items[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Generate_FillsAnHourWithoutMusicWhenTheTargetsTakeAllOfIt()
|
||||||
|
{
|
||||||
|
var options = new ScheduleOptions
|
||||||
|
{
|
||||||
|
NewsDuration = TimeSpan.FromMinutes(5),
|
||||||
|
AdsPerHour = TimeSpan.FromMinutes(20),
|
||||||
|
ModeratorPerHour = TimeSpan.FromMinutes(30),
|
||||||
|
};
|
||||||
|
var items = Generate(1, hours: 1, options);
|
||||||
|
|
||||||
|
Assert.DoesNotContain(items, i => i.Kind == ScheduleItemKind.Song);
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(20), Total(items, ScheduleItemKind.Ad));
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(30), Total(items, ScheduleItemKind.Moderator));
|
||||||
|
Assert.Equal(Start.AddHours(1), items[^1].End);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Generate_RejectsInvalidInput()
|
public void Generate_RejectsInvalidInput()
|
||||||
{
|
{
|
||||||
var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1));
|
var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1));
|
||||||
|
|
||||||
Assert.Throws<ArgumentOutOfRangeException>(() => generator.Generate(Start, 0, Library));
|
Assert.Throws<ArgumentOutOfRangeException>(() => generator.Generate(Start, 0, Library));
|
||||||
Assert.Throws<ArgumentException>(() => generator.Generate(Start.AddMinutes(15), 1, Library));
|
|
||||||
Assert.Throws<ArgumentException>(() =>
|
Assert.Throws<ArgumentException>(() =>
|
||||||
new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library));
|
new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library));
|
||||||
}
|
}
|
||||||
@@ -171,7 +254,7 @@ public class ScheduleGeneratorTests
|
|||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[MemberData(nameof(Seeds))]
|
[MemberData(nameof(Seeds))]
|
||||||
public void Replace_KeepsFillerLimitsAndNoAdsBackToBack(int seed)
|
public void Replace_KeepsTheSlotOnTimeAndNoAdsBackToBack(int seed)
|
||||||
{
|
{
|
||||||
var plan = Generate(seed, hours: 1);
|
var plan = Generate(seed, hours: 1);
|
||||||
// Every non-news item in the first half hour, so prefixes with filler are covered too.
|
// Every non-news item in the first half hour, so prefixes with filler are covered too.
|
||||||
@@ -182,9 +265,7 @@ public class ScheduleGeneratorTests
|
|||||||
try { swapped = Generator(seed).Replace(plan, index, Request, Library); }
|
try { swapped = Generator(seed).Replace(plan, index, Request, Library); }
|
||||||
catch (ScheduleException) { continue; } // too little time left before the news
|
catch (ScheduleException) { continue; } // too little time left before the news
|
||||||
|
|
||||||
var filler = swapped.Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator)
|
Assert.Equal(plan[^1].End, swapped[^1].End);
|
||||||
.Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration);
|
|
||||||
Assert.True(filler <= TimeSpan.FromMinutes(20), $"{filler} filler after swap at {index}");
|
|
||||||
for (var i = 1; i < swapped.Count; i++)
|
for (var i = 1; i < swapped.Count; i++)
|
||||||
Assert.False(swapped[i - 1].Kind == ScheduleItemKind.Ad && swapped[i].Kind == ScheduleItemKind.Ad,
|
Assert.False(swapped[i - 1].Kind == ScheduleItemKind.Ad && swapped[i].Kind == ScheduleItemKind.Ad,
|
||||||
$"Ads back to back at {swapped[i].Start:HH:mm:ss}");
|
$"Ads back to back at {swapped[i].Start:HH:mm:ss}");
|
||||||
@@ -199,7 +280,7 @@ public class ScheduleGeneratorTests
|
|||||||
var tooLong = Song(98, 25 * 60);
|
var tooLong = Song(98, 25 * 60);
|
||||||
|
|
||||||
var ex = Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, beforeNews, tooLong, Library));
|
var ex = Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, beforeNews, tooLong, Library));
|
||||||
Assert.Contains("does not fit", ex.Message);
|
Assert.Contains("passt nicht", ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -126,6 +126,6 @@ public sealed class SongImportServiceTests : IDisposable
|
|||||||
Assert.Equal([true, false, true], results.Select(r => r.Success));
|
Assert.Equal([true, false, true], results.Select(r => r.Success));
|
||||||
Assert.Equal("first", results[0].Song!.Title);
|
Assert.Equal("first", results[0].Song!.Title);
|
||||||
Assert.Null(results[1].Song);
|
Assert.Null(results[1].Song);
|
||||||
Assert.Contains("MP3 and WAV", results[1].Message);
|
Assert.Contains("MP3- und WAV", results[1].Message);
|
||||||
Assert.Equal(2, _repository.GetAll().Count);
|
Assert.Equal(2, _repository.GetAll().Count);
|
||||||
}}
|
}}
|
||||||
Reference in new issue
Block a user