feat: stream live to laut.fm and import from its library
The Settings page gets a laut.fm card: a switch, the live access data from Radioadmin (server, port, mountpoint, user, password) and the station id and Radioadmin token for the library. Password and token are written to settings.json encrypted with DPAPI for the Windows user. While laut.fm is on, the Schedule page shows a Live button next to "Jetzt starten". It logs in at the Icecast server with PUT and sends a copy of the broadcast mix as MP3 at 128 kbit/s, encoded by Windows Media Foundation. ProgramOutput hands that copy out through a live feed. Each item that starts sets the stream title; ad items send START_AD_BREAK at most once every 15 minutes. LautFmProvider searches the station's tracks through the Radioadmin API and the Import page lists it while laut.fm is on, so laut.fm tracks are imported into the same library as local songs. Providers can now hide themselves with IsAvailable. Nothing was tested against a real laut.fm account; the tests use a local fake server and fake HTTP answers. Refs #15 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5d261717fe
commit
a94fb862d2
16 files changed
+999
-16
No files matched your search
@@ -29,7 +29,7 @@ The interface is in German. This section names the controls as they appear on sc
|
|||||||
|
|
||||||
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.
|
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.
|
- **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.
|
||||||
- **Online**: choose Openverse or the Internet Archive in the list next to the search box. Search the 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.
|
- **Online**: choose Openverse, the Internet Archive or, while laut.fm is switched on, laut.fm in the list next to the search box. Search the 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.
|
2. **Bibliothek**: lists and searches all songs. Edit title, artist, license and attribution, or delete a song.
|
||||||
3. **Sendeplan** (the start page):
|
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**.
|
1. Choose the start (one of the next 12 full hours) and the number of hours (1 to 24), then click **Plan erstellen**.
|
||||||
@@ -42,8 +42,9 @@ The interface is in German. This section names the controls as they appear on sc
|
|||||||
6. **Microphone**: **Mikro ein** in the now-playing card puts the default microphone on air, also over running music; the button turns red and reads **Mikro aus**. It works with or without a broadcast and stays on while you visit other pages.
|
6. **Microphone**: **Mikro ein** in the now-playing card puts the default microphone on air, also over running music; the button turns red and reads **Mikro aus**. It works with or without a broadcast and stays on while you visit other pages.
|
||||||
7. **Mix levels**, below the now-playing row: **Musik für andere** and **Ich für andere** set how loud the music and the microphone are for the listeners, **Musik für mich** how loud the music is on your own device. **Sendung 1:1 hören** lets you hear exactly what the listeners hear. The slider next to the loudspeaker stays the overall music volume.
|
7. **Mix levels**, below the now-playing row: **Musik für andere** and **Ich für andere** set how loud the music and the microphone are for the listeners, **Musik für mich** how loud the music is on your own device. **Sendung 1:1 hören** lets you hear exactly what the listeners hear. The slider next to the loudspeaker stays the overall music volume.
|
||||||
8. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running.
|
8. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running.
|
||||||
|
9. **Live** (only while laut.fm is switched on): sends everything on air, songs and microphone, live to your laut.fm station. It does not depend on the plan; the button turns red and reads **Live beenden**. See [laut.fm](#lautfm).
|
||||||
|
|
||||||
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. Choose the playback device for the broadcast (for the listeners) and, if you have a second one such as headphones, the device for yourself. 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.
|
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. Choose the playback device for the broadcast (for the listeners) and, if you have a second one such as headphones, the device for yourself. 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. The **laut.fm** switch turns on live streaming and the station's library; its fields are described under [laut.fm](#lautfm).
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -68,7 +69,7 @@ The app follows the MVC pattern and uses [WPF UI](https://github.com/lepoco/wpfu
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Model | `src/Radiosender/Models` | `Song`, `ScheduleItem`, `MusicTrack`, `OpenverseTrack` |
|
| Model | `src/Radiosender/Models` | `Song`, `ScheduleItem`, `MusicTrack`, `OpenverseTrack` |
|
||||||
| View | `src/Radiosender/Views` | `MainWindow` with navigation, one page per feature, `SongEditWindow` |
|
| View | `src/Radiosender/Views` | `MainWindow` with navigation, one page per feature, `SongEditWindow` |
|
||||||
| Controller | `src/Radiosender/Controllers` | `LibraryController`, `UploadController`, `OnlineImportController`, `ScheduleController` |
|
| Controller | `src/Radiosender/Controllers` | `LibraryController`, `UploadController`, `OnlineImportController`, `ScheduleController`, `LiveController` |
|
||||||
| Services | `src/Radiosender/Services` | database, audio, schedule logic and API access used by the controllers |
|
| Services | `src/Radiosender/Services` | database, audio, schedule logic and API access used by the controllers |
|
||||||
|
|
||||||
Views only handle input and display. They call a controller, and the controller works with the models and services. `App` is the composition root: it registers every service, controller and page in a `Microsoft.Extensions.DependencyInjection` container, and the navigation view asks that container for each page, so pages get their controllers through the constructor. The `SongRepository` and the `ScheduleController` are singletons. A running broadcast therefore keeps playing when the user switches pages.
|
Views only handle input and display. They call a controller, and the controller works with the models and services. `App` is the composition root: it registers every service, controller and page in a `Microsoft.Extensions.DependencyInjection` container, and the navigation view asks that container for each page, so pages get their controllers through the constructor. The `SongRepository` and the `ScheduleController` are singletons. A running broadcast therefore keeps playing when the user switches pages.
|
||||||
@@ -77,7 +78,7 @@ Main services:
|
|||||||
|
|
||||||
- `SongRepository`: CRUD for songs in SQLite through Entity Framework Core, without SQL in the code
|
- `SongRepository`: CRUD for songs in SQLite through Entity Framework Core, without SQL in the code
|
||||||
- `SongImportService`: copies an uploaded file into the music folder, reads its tags with TagLibSharp and its duration with NAudio
|
- `SongImportService`: copies an uploaded file into the music folder, reads its tags with TagLibSharp and its duration with NAudio
|
||||||
- `IMusicProvider`: an online catalog that can be searched. `OpenverseProvider` uses the anonymous Openverse API and `InternetArchiveProvider` the Internet Archive search, limited to Creative Commons licensed MP3 files.
|
- `IMusicProvider`: an online catalog that can be searched. `OpenverseProvider` uses the anonymous Openverse API and `InternetArchiveProvider` the Internet Archive search, limited to Creative Commons licensed MP3 files. `LautFmProvider` searches the library of the user's laut.fm station.
|
||||||
- `TrackDownloader`: downloads a search result into the music folder, the same way for every provider
|
- `TrackDownloader`: downloads a search result into the music folder, the same way for every provider
|
||||||
- `ProgramMixer`: mixes songs and the microphone twice in one pass, once for the listeners and once for the person at the desk, each with its own levels
|
- `ProgramMixer`: mixes songs and the microphone twice in one pass, once for the listeners and once for the person at the desk, each with its own levels
|
||||||
- `ProgramOutput`: the station's audio channel. It plays the broadcast mix on one device and, if a second device is chosen, the monitor mix on that one
|
- `ProgramOutput`: the station's audio channel. It plays the broadcast mix on one device and, if a second device is chosen, the monitor mix on that one
|
||||||
@@ -85,8 +86,9 @@ Main services:
|
|||||||
- `Microphone`: captures the default recording device and puts it on the `ProgramOutput`
|
- `Microphone`: captures the default recording device and puts it on the `ProgramOutput`
|
||||||
- `ScheduleGenerator`: builds the plan and handles song requests
|
- `ScheduleGenerator`: builds the plan and handles song requests
|
||||||
- `PlaybackEngine`: runs the plan item by item on a background thread and plays songs through `MusicPlayer`
|
- `PlaybackEngine`: runs the plan item by item on a background thread and plays songs through `MusicPlayer`
|
||||||
|
- `IcecastStream`: logs in at an Icecast server as a live source, encodes a copy of the broadcast mix to MP3 with Windows Media Foundation and sends it. `LiveController` starts and stops it and sets the stream title for each item through `StreamTitles`
|
||||||
|
|
||||||
Tests are in `tests/Radiosender.Tests` (xUnit). They cover the repository, import, Openverse parsing, the generator rules, the playback engine and the schedule controller.
|
Tests are in `tests/Radiosender.Tests` (xUnit). They cover the repository, import, Openverse parsing, the generator rules, the playback engine, the schedule controller and laut.fm (settings, Icecast login, ad trigger, track parsing).
|
||||||
|
|
||||||
## Adding a music provider
|
## Adding a music provider
|
||||||
|
|
||||||
@@ -95,6 +97,7 @@ Online sources sit behind `IMusicProvider`, so a new one needs no change to the
|
|||||||
1. Write a class that implements `IMusicProvider`: a `Name` for the interface and `SearchAsync`, which returns `MusicTrack` items (title, creator, https link to the audio file, license, attribution, duration).
|
1. Write a class that implements `IMusicProvider`: a `Name` for the interface and `SearchAsync`, which returns `MusicTrack` items (title, creator, https link to the audio file, license, attribution, duration).
|
||||||
2. Give every track an `Id` that no other provider uses, for example prefixed with the provider name. Openverse ids are stored as they come.
|
2. Give every track an `Id` that no other provider uses, for example prefixed with the provider name. Openverse ids are stored as they come.
|
||||||
3. Register the class in `App.BuildServices` with `services.AddSingleton<IMusicProvider, YourProvider>()`.
|
3. Register the class in `App.BuildServices` with `services.AddSingleton<IMusicProvider, YourProvider>()`.
|
||||||
|
4. A provider that depends on a setting can return `false` from `IsAvailable`; the import page then leaves it out.
|
||||||
|
|
||||||
With one provider the import tab carries its name. With several, the tab is called "Online" and a list next to the search box chooses the provider.
|
With one provider the import tab carries its name. With several, the tab is called "Online" and a list next to the search box chooses the provider.
|
||||||
|
|
||||||
@@ -124,6 +127,28 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
|
|||||||
| The player really plays music | `MusicPlayer` with NAudio | Done |
|
| The player really plays music | `MusicPlayer` with NAudio | Done |
|
||||||
| C#, WPF with MVC, WPF UI | .NET 10, folders above, WPF UI 4.3 | Done |
|
| C#, WPF with MVC, WPF UI | .NET 10, folders above, WPF UI 4.3 | Done |
|
||||||
|
|
||||||
|
## laut.fm
|
||||||
|
|
||||||
|
With laut.fm switched on in the settings, the app streams live to a [laut.fm](https://laut.fm) station and offers the station's music on the Import page.
|
||||||
|
|
||||||
|
1. In Radioadmin, open **Live senden** and copy server, port, mountpoint, user and password into the laut.fm card on the Settings page. Save.
|
||||||
|
2. For the library, enter the station id and the Radioadmin token. The token is the value of `laut.fm.api.token` in the browser's local storage after logging in to Radioadmin (developer tools).
|
||||||
|
3. On the Sendeplan page, **Live** connects to laut.fm and sends the broadcast mix as MP3 at 128 kbit/s. laut.fm then plays the live stream instead of the station's regular program.
|
||||||
|
|
||||||
|
The app connects as an Icecast source (`PUT` to the mountpoint with the user and password). Each item that starts sets the stream title: `Artist - Title` for songs and the item title otherwise. Ad items send `START_AD_BREAK`, which laut.fm needs to start its ad break; the app sends it at most once every 15 minutes, as laut.fm requires.
|
||||||
|
|
||||||
|
Password and token are stored in `settings.json` encrypted with Windows DPAPI for the current Windows user. Another user or computer cannot read them and has to enter them again.
|
||||||
|
|
||||||
|
Risks:
|
||||||
|
|
||||||
|
- The library uses the API behind Radioadmin (`api.radioadmin.laut.fm`). laut.fm does not publish it for other programs, so it can change or stop working without notice, and the token expires when Radioadmin logs out.
|
||||||
|
- The import downloads the prelisten link that Radioadmin uses. Whether that is the full track or a shorter preview has not been checked against a real station.
|
||||||
|
- laut.fm licenses the station's music for broadcasting on laut.fm. Imported laut.fm tracks are marked with that license and must not be played anywhere else.
|
||||||
|
- Nothing here has been tested against a real laut.fm account. The tests run against a local fake server. If laut.fm expects a different format or login method, the settings show the error but do not adapt.
|
||||||
|
- The source connection and the title updates use plain HTTP, like every Icecast source client, so the live password crosses the network unencrypted.
|
||||||
|
- The MP3 encoder comes with Windows. Windows "N" editions lack it until the Media Feature Pack is installed; **Live** then reports the missing encoder.
|
||||||
|
- laut.fm wants the ad trigger at least once every half hour. With 0 ad minutes per hour the plan has no ad items and the app never sends it.
|
||||||
|
|
||||||
## Known limitations
|
## Known limitations
|
||||||
|
|
||||||
- **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.
|
- **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.
|
||||||
|
|||||||
@@ -41,6 +41,15 @@ public partial class App : Application
|
|||||||
// Music providers: add a line here for each new IMusicProvider; the import page lists them all.
|
// Music providers: add a line here for each new IMusicProvider; the import page lists them all.
|
||||||
services.AddSingleton<IMusicProvider, OpenverseProvider>();
|
services.AddSingleton<IMusicProvider, OpenverseProvider>();
|
||||||
services.AddSingleton<IMusicProvider, InternetArchiveProvider>();
|
services.AddSingleton<IMusicProvider, InternetArchiveProvider>();
|
||||||
|
// The station's own library; listed only while laut.fm is switched on in the settings.
|
||||||
|
services.AddSingleton<IMusicProvider>(provider => new LautFmProvider(
|
||||||
|
provider.GetRequiredService<System.Net.Http.HttpClient>(), () => provider.GetRequiredService<SettingsStore>().Current));
|
||||||
|
services.AddSingleton(provider => new LiveController(
|
||||||
|
provider.GetRequiredService<ScheduleController>(),
|
||||||
|
provider.GetRequiredService<SettingsStore>(),
|
||||||
|
provider.GetRequiredService<ProgramOutput>(),
|
||||||
|
provider.GetRequiredService<System.Net.Http.HttpClient>(),
|
||||||
|
() => DateTime.Now));
|
||||||
services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService<System.Net.Http.HttpClient>(), TrackDownloader.DefaultMusicFolder));
|
services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService<System.Net.Http.HttpClient>(), TrackDownloader.DefaultMusicFolder));
|
||||||
services.AddSingleton<OnlineImportController>();
|
services.AddSingleton<OnlineImportController>();
|
||||||
services.AddSingleton(provider => new SongImportService(provider.GetRequiredService<SongRepository>(), SongImportService.DefaultMusicDirectory));
|
services.AddSingleton(provider => new SongImportService(provider.GetRequiredService<SongRepository>(), SongImportService.DefaultMusicDirectory));
|
||||||
@@ -70,6 +79,7 @@ public partial class App : Application
|
|||||||
|
|
||||||
protected override void OnExit(ExitEventArgs e)
|
protected override void OnExit(ExitEventArgs e)
|
||||||
{
|
{
|
||||||
|
_services?.GetRequiredService<LiveController>().Stop();
|
||||||
_services?.GetRequiredService<ScheduleController>().Stop();
|
_services?.GetRequiredService<ScheduleController>().Stop();
|
||||||
_services?.Dispose();
|
_services?.Dispose();
|
||||||
base.OnExit(e);
|
base.OnExit(e);
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
using System.Net.Http;
|
||||||
|
using NAudio.Wave;
|
||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends the broadcast mix live to laut.fm, independent of the plan: whatever is on air goes out,
|
||||||
|
/// and each item that starts sets the stream title.
|
||||||
|
/// </summary>
|
||||||
|
public class LiveController
|
||||||
|
{
|
||||||
|
private readonly ScheduleController _schedule;
|
||||||
|
private readonly SettingsStore _settings;
|
||||||
|
private readonly ProgramOutput _output;
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly StreamTitles _titles;
|
||||||
|
private readonly Lock _lock = new();
|
||||||
|
private IcecastStream? _stream;
|
||||||
|
private BufferedWaveProvider? _feed;
|
||||||
|
private IcecastTarget? _target;
|
||||||
|
|
||||||
|
public LiveController(ScheduleController schedule, SettingsStore settings, ProgramOutput output, HttpClient http, Func<DateTime> now)
|
||||||
|
{
|
||||||
|
_schedule = schedule;
|
||||||
|
_settings = settings;
|
||||||
|
_output = output;
|
||||||
|
_http = http;
|
||||||
|
_titles = new StreamTitles(now);
|
||||||
|
_schedule.ItemStarted += (_, _) => SendCurrentTitle();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>laut.fm is switched on in the settings.</summary>
|
||||||
|
public bool IsEnabled => _settings.Current.LautFmEnabled;
|
||||||
|
|
||||||
|
public bool IsLive => _stream is not null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Something went wrong: the stream broke (then <see cref="IsLive"/> is false) or a title was not taken.
|
||||||
|
/// Raised on a background thread.
|
||||||
|
/// </summary>
|
||||||
|
public event EventHandler<string>? Problem;
|
||||||
|
|
||||||
|
/// <exception cref="LiveStreamException">laut.fm is off or cannot be reached, or the login was refused.</exception>
|
||||||
|
/// <exception cref="NAudio.MmException">No audio output device can be opened; the broadcast device sets the pace.</exception>
|
||||||
|
public async Task StartAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (IsLive)
|
||||||
|
return;
|
||||||
|
var settings = _settings.Current;
|
||||||
|
if (!settings.LautFmEnabled)
|
||||||
|
throw new LiveStreamException("laut.fm ist in den Einstellungen ausgeschaltet.");
|
||||||
|
var target = IcecastTarget.From(settings);
|
||||||
|
var feed = _output.OpenLiveFeed();
|
||||||
|
IcecastStream stream;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stream = await IcecastStream.ConnectAsync(target, feed, cancellationToken);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
_output.CloseLiveFeed(feed);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
stream.Failed += OnFailed;
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_stream = stream;
|
||||||
|
_feed = feed;
|
||||||
|
_target = target;
|
||||||
|
}
|
||||||
|
SendCurrentTitle();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Stop() => Stop(null);
|
||||||
|
|
||||||
|
// With a stream given, stops only if that one is still the current stream.
|
||||||
|
private void Stop(IcecastStream? only)
|
||||||
|
{
|
||||||
|
IcecastStream stream;
|
||||||
|
BufferedWaveProvider feed;
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_stream is null || _feed is null || (only is not null && _stream != only))
|
||||||
|
return;
|
||||||
|
(stream, feed) = (_stream, _feed);
|
||||||
|
(_stream, _feed, _target) = (null, null, null);
|
||||||
|
}
|
||||||
|
stream.Failed -= OnFailed;
|
||||||
|
stream.Dispose();
|
||||||
|
_output.CloseLiveFeed(feed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnFailed(object? sender, string message)
|
||||||
|
{
|
||||||
|
Stop(sender as IcecastStream);
|
||||||
|
Problem?.Invoke(this, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void SendCurrentTitle()
|
||||||
|
{
|
||||||
|
IcecastTarget target;
|
||||||
|
string title;
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_target is null || _schedule.CurrentItem is not { } item)
|
||||||
|
return;
|
||||||
|
target = _target;
|
||||||
|
title = _titles.For(item);
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await IcecastStream.UpdateTitleAsync(_http, target, title);
|
||||||
|
}
|
||||||
|
catch (LiveStreamException ex)
|
||||||
|
{
|
||||||
|
Problem?.Invoke(this, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,8 +7,10 @@ namespace Radiosender.Controllers;
|
|||||||
/// <summary>Searches the registered music providers and imports their results into the library.</summary>
|
/// <summary>Searches the registered music providers and imports their results into the library.</summary>
|
||||||
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
|
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
|
||||||
{
|
{
|
||||||
/// <summary>Every provider registered in <c>App</c>, in registration order.</summary>
|
private readonly IReadOnlyList<IMusicProvider> _providers = providers.ToList();
|
||||||
public IReadOnlyList<IMusicProvider> Providers { get; } = providers.ToList();
|
|
||||||
|
/// <summary>The providers registered in <c>App</c> that are available now, in registration order.</summary>
|
||||||
|
public IReadOnlyList<IMusicProvider> Providers => _providers.Where(provider => provider.IsAvailable).ToList();
|
||||||
|
|
||||||
/// <summary>Ids of the provider results that are already in the library.</summary>
|
/// <summary>Ids of the provider results that are already in the library.</summary>
|
||||||
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
|
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace Radiosender.Services;
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
@@ -38,6 +41,38 @@ public record AppSettings
|
|||||||
/// <summary>Playback device for the person at the desk; <c>null</c> means no device of its own.</summary>
|
/// <summary>Playback device for the person at the desk; <c>null</c> means no device of its own.</summary>
|
||||||
public string? MonitorDevice { get; init; }
|
public string? MonitorDevice { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Streaming to laut.fm and its library on the Import page; the Live button shows only while this is on.</summary>
|
||||||
|
public bool LautFmEnabled { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The station's id in Radioadmin, needed for the library.</summary>
|
||||||
|
public string LautFmStationId { get; init; } = "";
|
||||||
|
|
||||||
|
/// <summary>Live access data from Radioadmin, "Live senden".</summary>
|
||||||
|
public string LautFmHost { get; init; } = "";
|
||||||
|
|
||||||
|
public int LautFmPort { get; init; } = 8080;
|
||||||
|
|
||||||
|
public string LautFmMount { get; init; } = "";
|
||||||
|
|
||||||
|
public string LautFmUser { get; init; } = "source";
|
||||||
|
|
||||||
|
/// <summary>Kept in memory as is; the file only holds it encrypted for the Windows user.</summary>
|
||||||
|
[JsonIgnore]
|
||||||
|
public string LautFmPassword { get; init; } = "";
|
||||||
|
|
||||||
|
/// <summary>The Radioadmin login token for the library; stored encrypted like the password.</summary>
|
||||||
|
[JsonIgnore]
|
||||||
|
public string LautFmToken { get; init; } = "";
|
||||||
|
|
||||||
|
[JsonInclude, JsonPropertyName("LautFmPassword")]
|
||||||
|
private string? ProtectedLautFmPassword { get => Protect(LautFmPassword); init => LautFmPassword = Unprotect(value); }
|
||||||
|
|
||||||
|
[JsonInclude, JsonPropertyName("LautFmToken")]
|
||||||
|
private string? ProtectedLautFmToken { get => Protect(LautFmToken); init => LautFmToken = Unprotect(value); }
|
||||||
|
|
||||||
|
// Records print every property; the password and token stay out of logs and debugger views.
|
||||||
|
public override string ToString() => nameof(AppSettings);
|
||||||
|
|
||||||
public static string DefaultPath { get; } = Path.Combine(
|
public static string DefaultPath { get; } = Path.Combine(
|
||||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
|
||||||
|
|
||||||
@@ -52,6 +87,17 @@ public record AppSettings
|
|||||||
return "Minuten pro Stunde dĂĽrfen nicht negativ sein.";
|
return "Minuten pro Stunde dĂĽrfen nicht negativ sein.";
|
||||||
if (NewsMinutesPerHour + ModeratorMinutesPerHour + AdMinutesPerHour > 60)
|
if (NewsMinutesPerHour + ModeratorMinutesPerHour + AdMinutesPerHour > 60)
|
||||||
return "Nachrichten, Moderation und Werbung dürfen zusammen höchstens 60 Minuten pro Stunde dauern.";
|
return "Nachrichten, Moderation und Werbung dürfen zusammen höchstens 60 Minuten pro Stunde dauern.";
|
||||||
|
if (LautFmEnabled)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(LautFmHost) || Uri.CheckHostName(LautFmHost.Trim()) == UriHostNameType.Unknown)
|
||||||
|
return "FĂĽr laut.fm fehlt ein gĂĽltiger Server.";
|
||||||
|
if (LautFmPort is < 1 or > 65535)
|
||||||
|
return "Der laut.fm-Port muss zwischen 1 und 65535 liegen.";
|
||||||
|
if (string.IsNullOrWhiteSpace(LautFmMount))
|
||||||
|
return "FĂĽr laut.fm fehlt der Mountpoint.";
|
||||||
|
if (LautFmToken.Length > 0 && string.IsNullOrWhiteSpace(LautFmStationId))
|
||||||
|
return "FĂĽr die laut.fm-Bibliothek fehlt die Stations-ID.";
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,4 +129,24 @@ public record AppSettings
|
|||||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||||
File.WriteAllText(path, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }));
|
File.WriteAllText(path, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DPAPI: only this Windows user on this computer can read the value back.
|
||||||
|
private static string? Protect(string secret) => secret.Length == 0
|
||||||
|
? null
|
||||||
|
: Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(secret), null, DataProtectionScope.CurrentUser));
|
||||||
|
|
||||||
|
// A value from another user or computer cannot be read; the user enters it again.
|
||||||
|
private static string Unprotect(string? stored)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(stored))
|
||||||
|
return "";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(stored), null, DataProtectionScope.CurrentUser));
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is CryptographicException or FormatException)
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,9 @@ public interface IMusicProvider
|
|||||||
/// <summary>Name shown to the user, for example "Openverse".</summary>
|
/// <summary>Name shown to the user, for example "Openverse".</summary>
|
||||||
string Name { get; }
|
string Name { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the import page offers this provider now; one that needs a setting can hide itself.</summary>
|
||||||
|
bool IsAvailable => true;
|
||||||
|
|
||||||
/// <exception cref="MusicProviderException">The search failed.</exception>
|
/// <exception cref="MusicProviderException">The search failed.</exception>
|
||||||
Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default);
|
Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
using System.IO;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Text;
|
||||||
|
using NAudio.MediaFoundation;
|
||||||
|
using NAudio.Wave;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
/// <summary>Error of a live stream, with a message that can be shown to the user as is.</summary>
|
||||||
|
public class LiveStreamException(string message, Exception? inner = null) : Exception(message, inner);
|
||||||
|
|
||||||
|
/// <summary>Where and how a live source logs in. laut.fm shows these values in Radioadmin under "Live senden".</summary>
|
||||||
|
public record IcecastTarget(string Host, int Port, string Mount, string User, string Password)
|
||||||
|
{
|
||||||
|
public string Path => Mount.StartsWith('/') ? Mount : "/" + Mount;
|
||||||
|
|
||||||
|
public static IcecastTarget From(AppSettings settings) => new(
|
||||||
|
settings.LautFmHost.Trim(), settings.LautFmPort, settings.LautFmMount.Trim(), settings.LautFmUser.Trim(), settings.LautFmPassword);
|
||||||
|
|
||||||
|
/// <summary>Value of the Basic authorization header.</summary>
|
||||||
|
public string Credentials => Convert.ToBase64String(Encoding.UTF8.GetBytes($"{User}:{Password}"));
|
||||||
|
|
||||||
|
// The password stays out of logs and debugger views.
|
||||||
|
public override string ToString() => $"{User}@{Host}:{Port}{Path}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A source connection to an Icecast server, which is what laut.fm takes for live broadcasts.
|
||||||
|
/// Reads 32-bit float audio from a feed and sends it as MP3 at 128 kbit/s until disposed.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class IcecastStream : IDisposable
|
||||||
|
{
|
||||||
|
public const int Bitrate = 128_000;
|
||||||
|
private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
private readonly TcpClient _client;
|
||||||
|
private readonly FeedReader _reader;
|
||||||
|
private readonly Thread _thread;
|
||||||
|
private volatile bool _stopping;
|
||||||
|
|
||||||
|
private IcecastStream(TcpClient client, IWaveProvider feed)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_reader = new FeedReader(feed);
|
||||||
|
_thread = new Thread(Run) { IsBackground = true, Name = "Icecast stream" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The connection broke or the encoder stopped. Raised on the stream's own thread.</summary>
|
||||||
|
public event EventHandler<string>? Failed;
|
||||||
|
|
||||||
|
/// <summary>Logs in at the server and starts sending.</summary>
|
||||||
|
/// <param name="target">Server and login.</param>
|
||||||
|
/// <param name="feed">32-bit float audio that returns 0 bytes while nothing new is there, like <see cref="BufferedWaveProvider"/>.</param>
|
||||||
|
/// <param name="cancellationToken">Cancels the login.</param>
|
||||||
|
/// <exception cref="LiveStreamException">The server cannot be reached or refused the login.</exception>
|
||||||
|
public static async Task<IcecastStream> ConnectAsync(IcecastTarget target, IWaveProvider feed, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
// These values end up in the request line and headers; a line break there would change the request.
|
||||||
|
if (new[] { target.Host, target.Path, target.User }.Any(value => value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|
||||||
|
|| target.User.Contains(':'))
|
||||||
|
throw new LiveStreamException("Server, Mountpoint oder Benutzer enthalten ungĂĽltige Zeichen.");
|
||||||
|
|
||||||
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
|
timeout.CancelAfter(ConnectTimeout);
|
||||||
|
var client = new TcpClient();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await client.ConnectAsync(target.Host, target.Port, timeout.Token);
|
||||||
|
var network = client.GetStream();
|
||||||
|
var request =
|
||||||
|
$"PUT {target.Path} HTTP/1.1\r\n" +
|
||||||
|
$"Host: {target.Host}:{target.Port}\r\n" +
|
||||||
|
$"Authorization: Basic {target.Credentials}\r\n" +
|
||||||
|
"User-Agent: Radiosender/1.0\r\n" +
|
||||||
|
"Content-Type: audio/mpeg\r\n" +
|
||||||
|
"Ice-Public: 0\r\n" +
|
||||||
|
$"Ice-Bitrate: {Bitrate / 1000}\r\n" +
|
||||||
|
"Expect: 100-continue\r\n\r\n";
|
||||||
|
await network.WriteAsync(Encoding.ASCII.GetBytes(request), timeout.Token);
|
||||||
|
|
||||||
|
var status = await ReadStatusAsync(network, timeout.Token);
|
||||||
|
if (status is not (100 or 200))
|
||||||
|
{
|
||||||
|
throw new LiveStreamException(status switch
|
||||||
|
{
|
||||||
|
401 => "laut.fm hat die Anmeldung abgelehnt: Benutzer oder Passwort stimmen nicht.",
|
||||||
|
403 => "laut.fm nimmt gerade keinen Livestream an: Der Mountpoint ist belegt oder nicht freigeschaltet.",
|
||||||
|
404 => "Diesen Mountpoint gibt es auf dem Server nicht.",
|
||||||
|
_ => $"Der Server hat den Livestream abgelehnt (HTTP {status}).",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var stream = new IcecastStream(client, feed);
|
||||||
|
stream._thread.Start();
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
client.Dispose();
|
||||||
|
if (ex is LiveStreamException || cancellationToken.IsCancellationRequested)
|
||||||
|
throw;
|
||||||
|
throw ex switch
|
||||||
|
{
|
||||||
|
OperationCanceledException => new LiveStreamException("Der laut.fm-Server antwortet nicht.", ex),
|
||||||
|
SocketException or IOException => new LiveStreamException($"Keine Verbindung zum laut.fm-Server: {ex.Message}", ex),
|
||||||
|
_ => ex,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sets the title listeners see, through the server's admin interface with the same login.</summary>
|
||||||
|
/// <exception cref="LiveStreamException">The server did not take the title.</exception>
|
||||||
|
public static async Task UpdateTitleAsync(HttpClient http, IcecastTarget target, string title, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
// Plain http, like the source connection itself: Icecast takes sources without TLS.
|
||||||
|
var url = new UriBuilder(Uri.UriSchemeHttp, target.Host, target.Port, "/admin/metadata")
|
||||||
|
{
|
||||||
|
Query = $"mount={Uri.EscapeDataString(target.Path)}&mode=updinfo&song={Uri.EscapeDataString(title)}",
|
||||||
|
}.Uri;
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||||
|
request.Headers.Authorization = new("Basic", target.Credentials);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = await http.SendAsync(request, cancellationToken);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
throw new LiveStreamException($"laut.fm hat den Titel nicht angenommen (HTTP {(int)response.StatusCode}).");
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException && !cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw new LiveStreamException($"Der Titel konnte nicht an laut.fm gesendet werden: {ex.Message}", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stops sending and closes the connection.</summary>
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_stopping = true;
|
||||||
|
_reader.Stop();
|
||||||
|
// The encoder ends once the reader returns 0; a stalled connection is cut by closing the socket.
|
||||||
|
if (Thread.CurrentThread != _thread && _thread.IsAlive)
|
||||||
|
_thread.Join(TimeSpan.FromSeconds(2));
|
||||||
|
_client.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Run()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
MediaFoundationApi.Startup();
|
||||||
|
var pcm = _reader.ToSampleProvider().ToWaveProvider16();
|
||||||
|
var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, pcm.WaveFormat, Bitrate)
|
||||||
|
?? throw new LiveStreamException("Windows hat keinen MP3-Encoder.");
|
||||||
|
using var encoder = new MediaFoundationEncoder(mediaType);
|
||||||
|
encoder.Encode(_client.GetStream(), pcm, TranscodeContainerTypes.MFTranscodeContainerType_MP3);
|
||||||
|
if (!_stopping)
|
||||||
|
Failed?.Invoke(this, "Der Livestream wurde unerwartet beendet.");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// While stopping, closing the socket under the encoder is expected.
|
||||||
|
if (!_stopping)
|
||||||
|
Failed?.Invoke(this, ex is LiveStreamException ? ex.Message : $"Verbindung zu laut.fm verloren: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<int> ReadStatusAsync(NetworkStream network, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var header = new StringBuilder();
|
||||||
|
var buffer = new byte[512];
|
||||||
|
while (!header.ToString().Contains("\r\n\r\n"))
|
||||||
|
{
|
||||||
|
var read = await network.ReadAsync(buffer, cancellationToken);
|
||||||
|
if (read == 0 || header.Length > 8192)
|
||||||
|
throw new LiveStreamException("Der Server hat die Verbindung ohne gĂĽltige Antwort beendet.");
|
||||||
|
header.Append(Encoding.ASCII.GetString(buffer, 0, read));
|
||||||
|
}
|
||||||
|
// "HTTP/1.1 100 Continue" or "HTTP/1.0 200 OK"
|
||||||
|
var parts = header.ToString().Split(' ', 3);
|
||||||
|
return parts.Length >= 2 && int.TryParse(parts[1], out var status)
|
||||||
|
? status
|
||||||
|
: throw new LiveStreamException("Der Server hat ungĂĽltig geantwortet.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Waits for audio instead of ending when the feed is empty, so the encoder keeps going in real time.</summary>
|
||||||
|
private sealed class FeedReader(IWaveProvider feed) : IWaveProvider
|
||||||
|
{
|
||||||
|
private volatile bool _stopped;
|
||||||
|
|
||||||
|
public WaveFormat WaveFormat => feed.WaveFormat;
|
||||||
|
|
||||||
|
public void Stop() => _stopped = true;
|
||||||
|
|
||||||
|
public int Read(Span<byte> buffer)
|
||||||
|
{
|
||||||
|
while (!_stopped)
|
||||||
|
{
|
||||||
|
var read = feed.Read(buffer);
|
||||||
|
if (read > 0)
|
||||||
|
return read;
|
||||||
|
Thread.Sleep(10);
|
||||||
|
}
|
||||||
|
return 0; // the encoder finishes and returns
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
using System.Net.Http;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Radiosender.Models;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Searches the music library of the user's laut.fm station, so laut.fm tracks can be imported next to
|
||||||
|
/// local songs. Uses the API behind Radioadmin with the user's login token. laut.fm does not publish
|
||||||
|
/// this API for other programs, so it can change without notice.
|
||||||
|
/// </summary>
|
||||||
|
public class LautFmProvider(HttpClient http, Func<AppSettings> settings) : IMusicProvider
|
||||||
|
{
|
||||||
|
public const string ApiBase = "https://api.radioadmin.laut.fm/";
|
||||||
|
|
||||||
|
public string Name => "laut.fm";
|
||||||
|
|
||||||
|
public bool IsAvailable => settings().LautFmEnabled;
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var current = settings();
|
||||||
|
var station = current.LautFmStationId.Trim();
|
||||||
|
if (current.LautFmToken.Length == 0 || station.Length == 0)
|
||||||
|
throw new MusicProviderException("FĂĽr die laut.fm-Bibliothek fehlen Stations-ID oder Token in den Einstellungen.");
|
||||||
|
var words = query.Trim();
|
||||||
|
if (words.Length == 0)
|
||||||
|
return [];
|
||||||
|
|
||||||
|
// The API filters one field at a time, so title and artist are two searches.
|
||||||
|
var url = $"{ApiBase}stations/{Uri.EscapeDataString(station)}/tracks?";
|
||||||
|
var results = await Task.WhenAll(
|
||||||
|
SearchFieldAsync($"{url}title={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken),
|
||||||
|
SearchFieldAsync($"{url}artist={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken));
|
||||||
|
return results.SelectMany(tracks => tracks).DistinctBy(track => track.Id).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<MusicTrack>> SearchFieldAsync(string url, string token, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using var json = await ProviderParsing.GetJsonAsync(http, url, Name, cancellationToken, token);
|
||||||
|
if (!json.RootElement.TryGetProperty("tracks", out var tracks) || tracks.ValueKind != JsonValueKind.Array)
|
||||||
|
throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort.");
|
||||||
|
|
||||||
|
var result = new List<MusicTrack>();
|
||||||
|
foreach (var track in tracks.EnumerateArray())
|
||||||
|
{
|
||||||
|
if (ProviderParsing.Text(track, "id") is not { } id
|
||||||
|
|| ProviderParsing.Text(track, "title") is not { } title
|
||||||
|
|| PrelistenUrl(track) is not { } audio)
|
||||||
|
continue;
|
||||||
|
result.Add(new MusicTrack
|
||||||
|
{
|
||||||
|
// Prefixed, so the id cannot collide with one from another provider.
|
||||||
|
Id = $"lautfm:{id}",
|
||||||
|
Title = title,
|
||||||
|
Creator = ProviderParsing.Text(track, "artist"),
|
||||||
|
Url = audio,
|
||||||
|
FileType = "mp3",
|
||||||
|
// The station's tracks are licensed by laut.fm for broadcasting on laut.fm only.
|
||||||
|
License = "laut.fm (nur fĂĽr laut.fm)",
|
||||||
|
Duration = ProviderParsing.Duration(ProviderParsing.Text(track, "duration")),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The link the Radioadmin player uses; it needs no login. Relative links are taken against the API.
|
||||||
|
private static string? PrelistenUrl(JsonElement track)
|
||||||
|
{
|
||||||
|
if (!track.TryGetProperty("_links", out var links) || links.ValueKind != JsonValueKind.Object
|
||||||
|
|| !links.TryGetProperty("prelisten_authless", out var link)
|
||||||
|
|| ProviderParsing.Text(link, "href") is not { } href
|
||||||
|
|| !Uri.TryCreate(new Uri(ApiBase), href, out var uri)
|
||||||
|
|| uri.Scheme != Uri.UriSchemeHttps)
|
||||||
|
return null;
|
||||||
|
return uri.AbsoluteUri;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ public sealed class ProgramOutput
|
|||||||
private bool _started;
|
private bool _started;
|
||||||
private WaveOut? _broadcastDevice;
|
private WaveOut? _broadcastDevice;
|
||||||
private WaveOut? _monitorDevice;
|
private WaveOut? _monitorDevice;
|
||||||
|
private volatile BufferedWaveProvider? _liveFeed;
|
||||||
|
|
||||||
private ProgramOutput()
|
private ProgramOutput()
|
||||||
{
|
{
|
||||||
@@ -81,6 +82,37 @@ public sealed class ProgramOutput
|
|||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Starts a copy of the broadcast mix for a live stream and opens the output devices if needed, because
|
||||||
|
/// the broadcast device sets the pace. Only one feed at a time: a new one replaces the old.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="NAudio.MmException">No audio output device can be opened.</exception>
|
||||||
|
public BufferedWaveProvider OpenLiveFeed()
|
||||||
|
{
|
||||||
|
// Holds a few seconds; if the reader falls behind, the newest audio is dropped instead of piling up.
|
||||||
|
var feed = new BufferedWaveProvider(Format, TimeSpan.FromSeconds(5)) { DiscardOnBufferOverflow = true, ReadFully = false };
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (!_started)
|
||||||
|
{
|
||||||
|
OpenDevices();
|
||||||
|
_started = true;
|
||||||
|
}
|
||||||
|
_liveFeed = feed;
|
||||||
|
}
|
||||||
|
return feed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stops copying into the feed from <see cref="OpenLiveFeed"/>.</summary>
|
||||||
|
public void CloseLiveFeed(BufferedWaveProvider feed)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_liveFeed == feed)
|
||||||
|
_liveFeed = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Takes an input off air. Returns once the audio thread no longer reads from it.</summary>
|
/// <summary>Takes an input off air. Returns once the audio thread no longer reads from it.</summary>
|
||||||
public void Remove(ISampleProvider input) => Mixer.Remove(input);
|
public void Remove(ISampleProvider input) => Mixer.Remove(input);
|
||||||
|
|
||||||
@@ -111,7 +143,7 @@ public sealed class ProgramOutput
|
|||||||
if (monitor < 0)
|
if (monitor < 0)
|
||||||
{
|
{
|
||||||
// One device: the person at the desk hears the monitor mix; nothing is sent anywhere else.
|
// One device: the person at the desk hears the monitor mix; nothing is sent anywhere else.
|
||||||
_broadcastDevice = Open(broadcast, new Tap(Mixer, null));
|
_broadcastDevice = Open(broadcast, new Tap(this, null));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -119,7 +151,7 @@ public sealed class ProgramOutput
|
|||||||
// which waits in a short buffer for the second device. The buffer drops what it cannot hold,
|
// which waits in a short buffer for the second device. The buffer drops what it cannot hold,
|
||||||
// so the two device clocks drifting apart never builds up a delay.
|
// so the two device clocks drifting apart never builds up a delay.
|
||||||
var monitorBuffer = new BufferedWaveProvider(Format, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
|
var monitorBuffer = new BufferedWaveProvider(Format, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
|
||||||
_broadcastDevice = Open(broadcast, new Tap(Mixer, monitorBuffer));
|
_broadcastDevice = Open(broadcast, new Tap(this, monitorBuffer));
|
||||||
_monitorDevice = Open(monitor, monitorBuffer.ToSampleProvider());
|
_monitorDevice = Open(monitor, monitorBuffer.ToSampleProvider());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -158,9 +190,9 @@ public sealed class ProgramOutput
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// What the pacing device plays. With a monitor buffer it plays the broadcast mix and feeds the buffer;
|
/// What the pacing device plays. With a monitor buffer it plays the broadcast mix and feeds the buffer;
|
||||||
/// without one it plays the monitor mix itself.
|
/// without one it plays the monitor mix itself. Either way the broadcast mix also goes to the live feed, if there is one.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private sealed class Tap(ProgramMixer mixer, BufferedWaveProvider? monitorBuffer) : ISampleProvider
|
private sealed class Tap(ProgramOutput output, BufferedWaveProvider? monitorBuffer) : ISampleProvider
|
||||||
{
|
{
|
||||||
private float[] _other = [];
|
private float[] _other = [];
|
||||||
|
|
||||||
@@ -172,15 +204,19 @@ public sealed class ProgramOutput
|
|||||||
_other = new float[buffer.Length];
|
_other = new float[buffer.Length];
|
||||||
var other = _other.AsSpan(0, buffer.Length);
|
var other = _other.AsSpan(0, buffer.Length);
|
||||||
|
|
||||||
|
Span<float> broadcast;
|
||||||
if (monitorBuffer is null)
|
if (monitorBuffer is null)
|
||||||
{
|
{
|
||||||
mixer.Mix(other, buffer);
|
output.Mixer.Mix(other, buffer);
|
||||||
|
broadcast = other;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
mixer.Mix(buffer, other);
|
output.Mixer.Mix(buffer, other);
|
||||||
monitorBuffer.AddSamples(MemoryMarshal.AsBytes(other));
|
monitorBuffer.AddSamples(MemoryMarshal.AsBytes(other));
|
||||||
|
broadcast = buffer;
|
||||||
}
|
}
|
||||||
|
output._liveFeed?.AddSamples(MemoryMarshal.AsBytes(broadcast));
|
||||||
return buffer.Length; // never ends: silence while nothing is on air
|
return buffer.Length; // never ends: silence while nothing is on air
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,12 +9,18 @@ namespace Radiosender.Services;
|
|||||||
internal static partial class ProviderParsing
|
internal static partial class ProviderParsing
|
||||||
{
|
{
|
||||||
/// <summary>Fetches <paramref name="url"/> and parses it as JSON, whatever content type the server names.</summary>
|
/// <summary>Fetches <paramref name="url"/> and parses it as JSON, whatever content type the server names.</summary>
|
||||||
|
/// <param name="bearerToken">Sent as the Authorization header when set.</param>
|
||||||
/// <exception cref="MusicProviderException">The request failed or the answer is not JSON.</exception>
|
/// <exception cref="MusicProviderException">The request failed or the answer is not JSON.</exception>
|
||||||
public static async Task<JsonDocument> GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken)
|
public static async Task<JsonDocument> GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken, string? bearerToken = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var response = await http.GetAsync(url, cancellationToken);
|
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||||
|
if (bearerToken is not null)
|
||||||
|
request.Headers.Authorization = new("Bearer", bearerToken);
|
||||||
|
using var response = await http.SendAsync(request, cancellationToken);
|
||||||
|
if (response.StatusCode is System.Net.HttpStatusCode.Unauthorized or System.Net.HttpStatusCode.Forbidden && bearerToken is not null)
|
||||||
|
throw new MusicProviderException($"{provider} hat die Anmeldung abgelehnt. Den Token in den Einstellungen prĂĽfen.");
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
throw new MusicProviderException($"{provider} hat HTTP {(int)response.StatusCode} geliefert.");
|
throw new MusicProviderException($"{provider} hat HTTP {(int)response.StatusCode} geliefert.");
|
||||||
// Parsed without looking at the content type: not every API labels its JSON as such.
|
// Parsed without looking at the content type: not every API labels its JSON as such.
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using Radiosender.Models;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The stream title for each item. laut.fm starts its ad break when the title is "START_AD_BREAK" and
|
||||||
|
/// wants that at most once in 15 minutes, so later ad items within that time keep their own title.
|
||||||
|
/// </summary>
|
||||||
|
public class StreamTitles(Func<DateTime> now)
|
||||||
|
{
|
||||||
|
public const string AdBreak = "START_AD_BREAK";
|
||||||
|
public static readonly TimeSpan MinAdBreakSpacing = TimeSpan.FromMinutes(15);
|
||||||
|
|
||||||
|
private DateTime? _lastAdBreak;
|
||||||
|
|
||||||
|
public string For(ScheduleItem item)
|
||||||
|
{
|
||||||
|
if (item.Kind == ScheduleItemKind.Ad)
|
||||||
|
{
|
||||||
|
var time = now();
|
||||||
|
if (_lastAdBreak is not { } last || time - last >= MinAdBreakSpacing)
|
||||||
|
{
|
||||||
|
_lastAdBreak = time;
|
||||||
|
return AdBreak;
|
||||||
|
}
|
||||||
|
return item.Title;
|
||||||
|
}
|
||||||
|
return item.Song is { } song ? $"{song.Artist} - {song.Title}" : item.Title;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -86,6 +86,16 @@
|
|||||||
Icon="{ui:SymbolIcon Play24}"
|
Icon="{ui:SymbolIcon Play24}"
|
||||||
ToolTip="Plant ab diesem Moment und geht sofort auf Sendung. Die Startzeit wird ignoriert."
|
ToolTip="Plant ab diesem Moment und geht sofort auf Sendung. Die Startzeit wird ignoriert."
|
||||||
Click="OnStartNow" />
|
Click="OnStartNow" />
|
||||||
|
<!-- Only while laut.fm is on: sends the program live to the station, independent of the plan. -->
|
||||||
|
<ui:Button x:Name="LiveButton"
|
||||||
|
MinWidth="100"
|
||||||
|
Margin="8,8,0,0"
|
||||||
|
VerticalAlignment="Center"
|
||||||
|
Content="Live"
|
||||||
|
Icon="{ui:SymbolIcon Live24}"
|
||||||
|
ToolTip="Sendet alles, was auf Sendung ist, live auf deine laut.fm-Station."
|
||||||
|
Visibility="Collapsed"
|
||||||
|
Click="OnLiveToggle" />
|
||||||
</WrapPanel>
|
</WrapPanel>
|
||||||
|
|
||||||
<ui:InfoBar x:Name="Message"
|
<ui:InfoBar x:Name="Message"
|
||||||
|
|||||||
@@ -31,10 +31,12 @@ public partial class SchedulePage : Page
|
|||||||
|
|
||||||
private readonly Microphone _microphone;
|
private readonly Microphone _microphone;
|
||||||
private readonly ProgramMixer _mixer;
|
private readonly ProgramMixer _mixer;
|
||||||
|
private readonly LiveController _live;
|
||||||
|
|
||||||
public SchedulePage(ScheduleController controller, Microphone microphone, ProgramOutput output)
|
public SchedulePage(ScheduleController controller, Microphone microphone, ProgramOutput output, LiveController live)
|
||||||
{
|
{
|
||||||
_controller = controller;
|
_controller = controller;
|
||||||
|
_live = live;
|
||||||
_microphone = microphone;
|
_microphone = microphone;
|
||||||
_mixer = output.Mixer;
|
_mixer = output.Mixer;
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
@@ -53,6 +55,7 @@ public partial class SchedulePage : Page
|
|||||||
_controller.ItemStarted += OnItemStarted;
|
_controller.ItemStarted += OnItemStarted;
|
||||||
_controller.ItemFailed += OnItemFailed;
|
_controller.ItemFailed += OnItemFailed;
|
||||||
_controller.Finished += OnFinished;
|
_controller.Finished += OnFinished;
|
||||||
|
_live.Problem += OnLiveProblem;
|
||||||
|
|
||||||
_loading = true;
|
_loading = true;
|
||||||
VolumeSlider.Value = _controller.Volume;
|
VolumeSlider.Value = _controller.Volume;
|
||||||
@@ -63,6 +66,7 @@ public partial class SchedulePage : Page
|
|||||||
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
|
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
|
||||||
_loading = false;
|
_loading = false;
|
||||||
ShowMicrophone(); // it stays on while the user visits other pages
|
ShowMicrophone(); // it stays on while the user visits other pages
|
||||||
|
ShowLive();
|
||||||
FillStartTimes();
|
FillStartTimes();
|
||||||
if (_controller.Plan.Count > 0)
|
if (_controller.Plan.Count > 0)
|
||||||
UnlimitedBox.IsChecked = _controller.IsUnlimited;
|
UnlimitedBox.IsChecked = _controller.IsUnlimited;
|
||||||
@@ -82,6 +86,7 @@ public partial class SchedulePage : Page
|
|||||||
_controller.ItemStarted -= OnItemStarted;
|
_controller.ItemStarted -= OnItemStarted;
|
||||||
_controller.ItemFailed -= OnItemFailed;
|
_controller.ItemFailed -= OnItemFailed;
|
||||||
_controller.Finished -= OnFinished;
|
_controller.Finished -= OnFinished;
|
||||||
|
_live.Problem -= OnLiveProblem;
|
||||||
_progressTimer.Stop();
|
_progressTimer.Stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,6 +221,47 @@ public partial class SchedulePage : Page
|
|||||||
System.Windows.Automation.AutomationProperties.SetName(MicButton, on ? "Mikrofon ausschalten, es ist auf Sendung" : "Mikrofon einschalten");
|
System.Windows.Automation.AutomationProperties.SetName(MicButton, on ? "Mikrofon ausschalten, es ist auf Sendung" : "Mikrofon einschalten");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async void OnLiveToggle(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
LiveButton.IsEnabled = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_live.IsLive)
|
||||||
|
{
|
||||||
|
await Task.Run(_live.Stop);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Opening the devices and the connection can take a moment, so it runs off the UI thread.
|
||||||
|
await Task.Run(() => _live.StartAsync());
|
||||||
|
Message.IsOpen = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is LiveStreamException or NAudio.MmException)
|
||||||
|
{
|
||||||
|
ShowMessage(InfoBarSeverity.Error, "Live nicht möglich", ex.Message);
|
||||||
|
}
|
||||||
|
LiveButton.IsEnabled = true;
|
||||||
|
ShowLive();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comes from a background thread; the stream may have ended.
|
||||||
|
private void OnLiveProblem(object? sender, string message) => Dispatcher.BeginInvoke(() =>
|
||||||
|
{
|
||||||
|
ShowMessage(InfoBarSeverity.Warning, "laut.fm", message);
|
||||||
|
ShowLive();
|
||||||
|
});
|
||||||
|
|
||||||
|
private void ShowLive()
|
||||||
|
{
|
||||||
|
var live = _live.IsLive;
|
||||||
|
// Stays visible while live, so a stream can be stopped after laut.fm was switched off.
|
||||||
|
LiveButton.Visibility = _live.IsEnabled || live ? Visibility.Visible : Visibility.Collapsed;
|
||||||
|
LiveButton.Content = live ? "Live beenden" : "Live";
|
||||||
|
LiveButton.Appearance = live ? ControlAppearance.Danger : ControlAppearance.Secondary;
|
||||||
|
System.Windows.Automation.AutomationProperties.SetName(LiveButton, live ? "Livestream zu laut.fm beenden, er läuft" : "Livestream zu laut.fm starten");
|
||||||
|
}
|
||||||
|
|
||||||
private void OnEndNow(object sender, RoutedEventArgs e)
|
private void OnEndNow(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -154,6 +154,74 @@
|
|||||||
</Grid>
|
</Grid>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
|
<!-- laut.fm: live streaming and the station's library -->
|
||||||
|
<Border Style="{StaticResource Card}">
|
||||||
|
<StackPanel>
|
||||||
|
<ui:ToggleSwitch x:Name="LautFmSwitch" Content="laut.fm"
|
||||||
|
Checked="OnLautFmChanged" Unchecked="OnLautFmChanged" />
|
||||||
|
<ui:TextBlock Margin="0,8,0,0" TextWrapping="Wrap"
|
||||||
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
|
Text="Sendet live auf deine laut.fm-Station und bietet ihre Musik beim Import an. Im Plan erscheint dann der Button „Live“." />
|
||||||
|
<Grid x:Name="LautFmFields" Margin="0,4,0,0">
|
||||||
|
<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" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
<ui:TextBlock Margin="0,12,0,0" Grid.ColumnSpan="2" FontTypography="BodyStrong" Text="Live senden" />
|
||||||
|
<Label Grid.Row="1" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Server" Target="{Binding ElementName=LautFmHostBox}" />
|
||||||
|
<ui:TextBox x:Name="LautFmHostBox" Grid.Row="1" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
AutomationProperties.Name="laut.fm-Server" />
|
||||||
|
<Label Grid.Row="2" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Port" Target="{Binding ElementName=LautFmPortBox}" />
|
||||||
|
<ui:NumberBox x:Name="LautFmPortBox" Grid.Row="2" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
Width="130" HorizontalAlignment="Left" Minimum="1" Maximum="65535"
|
||||||
|
MaxDecimalPlaces="0" SmallChange="1" ClearButtonEnabled="False"
|
||||||
|
AutomationProperties.Name="laut.fm-Port" />
|
||||||
|
<Label Grid.Row="3" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Mountpoint" Target="{Binding ElementName=LautFmMountBox}" />
|
||||||
|
<ui:TextBox x:Name="LautFmMountBox" Grid.Row="3" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
AutomationProperties.Name="laut.fm-Mountpoint" />
|
||||||
|
<Label Grid.Row="4" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Benutzer" Target="{Binding ElementName=LautFmUserBox}" />
|
||||||
|
<ui:TextBox x:Name="LautFmUserBox" Grid.Row="4" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
AutomationProperties.Name="laut.fm-Benutzer" />
|
||||||
|
<Label Grid.Row="5" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Passwort" Target="{Binding ElementName=LautFmPasswordBox}" />
|
||||||
|
<ui:PasswordBox x:Name="LautFmPasswordBox" Grid.Row="5" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
AutomationProperties.Name="laut.fm-Passwort" />
|
||||||
|
<ui:TextBlock Grid.Row="6" Grid.ColumnSpan="2" Margin="0,8,0,0" TextWrapping="Wrap"
|
||||||
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
|
Text="Diese Werte stehen in Radioadmin unter „Live senden“." />
|
||||||
|
<ui:TextBlock Grid.Row="7" Margin="0,16,0,0" Grid.ColumnSpan="2" FontTypography="BodyStrong" Text="Bibliothek" />
|
||||||
|
<Label Grid.Row="8" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Stations-ID" Target="{Binding ElementName=LautFmStationBox}" />
|
||||||
|
<ui:TextBox x:Name="LautFmStationBox" Grid.Row="8" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
AutomationProperties.Name="laut.fm-Stations-ID" />
|
||||||
|
<Label Grid.Row="9" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||||
|
Content="Radioadmin-Token" Target="{Binding ElementName=LautFmTokenBox}" />
|
||||||
|
<ui:PasswordBox x:Name="LautFmTokenBox" Grid.Row="9" Grid.Column="1" Margin="0,8,0,0"
|
||||||
|
AutomationProperties.Name="Radioadmin-Token"
|
||||||
|
ToolTip="Nach dem Login in Radioadmin in den Entwicklertools des Browsers: Lokaler Speicher, SchlĂĽssel laut.fm.api.token." />
|
||||||
|
</Grid>
|
||||||
|
<ui:TextBlock x:Name="LautFmHint" Margin="0,12,0,0" TextWrapping="Wrap"
|
||||||
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
|
Text="Passwort und Token werden verschlĂĽsselt fĂĽr deinen Windows-Benutzer gespeichert. Die Bibliothek nutzt eine nicht offizielle laut.fm-Schnittstelle und kann ohne Vorwarnung ausfallen." />
|
||||||
|
</StackPanel>
|
||||||
|
</Border>
|
||||||
|
|
||||||
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
|
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
|
||||||
<ui:Button Appearance="Primary" MinWidth="110" Content="Speichern" Icon="{ui:SymbolIcon Save24}" Click="OnSave" />
|
<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}"
|
<ui:Button Margin="8,0,0,0" MinWidth="110" Content="ZurĂĽcksetzen" Icon="{ui:SymbolIcon ArrowReset24}"
|
||||||
|
|||||||
@@ -41,8 +41,21 @@ public partial class SettingsPage : Page
|
|||||||
NewsMinutesBox.Value = settings.NewsMinutesPerHour;
|
NewsMinutesBox.Value = settings.NewsMinutesPerHour;
|
||||||
ModeratorMinutesBox.Value = settings.ModeratorMinutesPerHour;
|
ModeratorMinutesBox.Value = settings.ModeratorMinutesPerHour;
|
||||||
AdMinutesBox.Value = settings.AdMinutesPerHour;
|
AdMinutesBox.Value = settings.AdMinutesPerHour;
|
||||||
|
LautFmSwitch.IsChecked = settings.LautFmEnabled;
|
||||||
|
LautFmHostBox.Text = settings.LautFmHost;
|
||||||
|
LautFmPortBox.Value = settings.LautFmPort;
|
||||||
|
LautFmMountBox.Text = settings.LautFmMount;
|
||||||
|
LautFmUserBox.Text = settings.LautFmUser;
|
||||||
|
LautFmPasswordBox.Password = settings.LautFmPassword;
|
||||||
|
LautFmStationBox.Text = settings.LautFmStationId;
|
||||||
|
LautFmTokenBox.Password = settings.LautFmToken;
|
||||||
|
OnLautFmChanged(this, new RoutedEventArgs());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The access fields only matter while laut.fm is on.
|
||||||
|
private void OnLautFmChanged(object sender, RoutedEventArgs e) =>
|
||||||
|
LautFmFields.Visibility = LautFmSwitch.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
|
||||||
|
|
||||||
// An emptied number box counts as its default.
|
// An emptied number box counts as its default.
|
||||||
private static AppSettings Defaults { get; } = new();
|
private static AppSettings Defaults { get; } = new();
|
||||||
|
|
||||||
@@ -59,6 +72,14 @@ public partial class SettingsPage : Page
|
|||||||
AdMinutesPerHour = (int)(AdMinutesBox.Value ?? Defaults.AdMinutesPerHour),
|
AdMinutesPerHour = (int)(AdMinutesBox.Value ?? Defaults.AdMinutesPerHour),
|
||||||
BroadcastDevice = BroadcastDeviceBox.SelectedIndex > 0 ? (string)BroadcastDeviceBox.SelectedItem : null,
|
BroadcastDevice = BroadcastDeviceBox.SelectedIndex > 0 ? (string)BroadcastDeviceBox.SelectedItem : null,
|
||||||
MonitorDevice = MonitorDeviceBox.SelectedIndex > 0 ? (string)MonitorDeviceBox.SelectedItem : null,
|
MonitorDevice = MonitorDeviceBox.SelectedIndex > 0 ? (string)MonitorDeviceBox.SelectedItem : null,
|
||||||
|
LautFmEnabled = LautFmSwitch.IsChecked == true,
|
||||||
|
LautFmHost = LautFmHostBox.Text.Trim(),
|
||||||
|
LautFmPort = (int)(LautFmPortBox.Value ?? Defaults.LautFmPort),
|
||||||
|
LautFmMount = LautFmMountBox.Text.Trim(),
|
||||||
|
LautFmUser = LautFmUserBox.Text.Trim(),
|
||||||
|
LautFmPassword = LautFmPasswordBox.Password,
|
||||||
|
LautFmStationId = LautFmStationBox.Text.Trim(),
|
||||||
|
LautFmToken = LautFmTokenBox.Password.Trim(),
|
||||||
};
|
};
|
||||||
|
|
||||||
private void OnSave(object sender, RoutedEventArgs e)
|
private void OnSave(object sender, RoutedEventArgs e)
|
||||||
|
|||||||
@@ -0,0 +1,256 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Text;
|
||||||
|
using NAudio.Wave;
|
||||||
|
using NAudio.Wave.SampleProviders;
|
||||||
|
using Radiosender.Controllers;
|
||||||
|
using Radiosender.Models;
|
||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Tests;
|
||||||
|
|
||||||
|
public sealed class LautFmTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
|
||||||
|
|
||||||
|
private static readonly AppSettings Live = new()
|
||||||
|
{
|
||||||
|
LautFmEnabled = true,
|
||||||
|
LautFmHost = "live.example.test",
|
||||||
|
LautFmPort = 8080,
|
||||||
|
LautFmMount = "/station",
|
||||||
|
LautFmUser = "source",
|
||||||
|
LautFmPassword = "geheim-passwort",
|
||||||
|
LautFmStationId = "123",
|
||||||
|
LautFmToken = "geheimer-token",
|
||||||
|
};
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||||
|
if (Directory.Exists(_directory))
|
||||||
|
Directory.Delete(_directory, recursive: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Settings_CheckTheLiveDataOnlyWhenSwitchedOn()
|
||||||
|
{
|
||||||
|
Assert.Null(Live.Validate());
|
||||||
|
Assert.Null(new AppSettings { LautFmEnabled = false, LautFmHost = "" }.Validate());
|
||||||
|
Assert.Contains("Server", (Live with { LautFmHost = "" }).Validate());
|
||||||
|
Assert.Contains("Port", (Live with { LautFmPort = 0 }).Validate());
|
||||||
|
Assert.Contains("Mountpoint", (Live with { LautFmMount = " " }).Validate());
|
||||||
|
Assert.Contains("Stations-ID", (Live with { LautFmStationId = "" }).Validate());
|
||||||
|
Assert.Null((Live with { LautFmStationId = "", LautFmToken = "" }).Validate()); // live only, no library
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Settings_StoreSecretsEncrypted()
|
||||||
|
{
|
||||||
|
var file = Path.Combine(_directory, "settings.json");
|
||||||
|
|
||||||
|
Live.Save(file);
|
||||||
|
var text = System.IO.File.ReadAllText(file);
|
||||||
|
var loaded = AppSettings.Load(file);
|
||||||
|
|
||||||
|
Assert.DoesNotContain(Live.LautFmPassword, text);
|
||||||
|
Assert.DoesNotContain(Live.LautFmToken, text);
|
||||||
|
Assert.Contains("\"LautFmPassword\"", text);
|
||||||
|
Assert.Equal(Live, loaded);
|
||||||
|
Assert.Equal("geheim-passwort", loaded.LautFmPassword);
|
||||||
|
Assert.DoesNotContain("geheim", Live.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Settings_SecretsThatCannotBeDecryptedAreEmpty()
|
||||||
|
{
|
||||||
|
var file = Path.Combine(_directory, "settings.json");
|
||||||
|
Directory.CreateDirectory(_directory);
|
||||||
|
System.IO.File.WriteAllText(file, """{"LautFmPassword":"bm90IGVuY3J5cHRlZA==","LautFmToken":"%%%"}""");
|
||||||
|
|
||||||
|
var loaded = AppSettings.Load(file);
|
||||||
|
|
||||||
|
Assert.Equal("", loaded.LautFmPassword);
|
||||||
|
Assert.Equal("", loaded.LautFmToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StreamTitles_SendTheAdTriggerAtMostEvery15Minutes()
|
||||||
|
{
|
||||||
|
var now = new DateTime(2026, 11, 25, 12, 0, 0);
|
||||||
|
var titles = new StreamTitles(() => now);
|
||||||
|
var ad = new ScheduleItem(ScheduleItemKind.Ad, "Werbung", now, TimeSpan.FromMinutes(2));
|
||||||
|
|
||||||
|
Assert.Equal(StreamTitles.AdBreak, titles.For(ad));
|
||||||
|
now = now.AddMinutes(2);
|
||||||
|
Assert.Equal("Werbung", titles.For(ad)); // second ad of the same break
|
||||||
|
now = now.AddMinutes(12);
|
||||||
|
Assert.Equal("Werbung", titles.For(ad)); // 14 minutes after the trigger
|
||||||
|
now = now.AddMinutes(1);
|
||||||
|
Assert.Equal(StreamTitles.AdBreak, titles.For(ad));
|
||||||
|
|
||||||
|
var song = new Song { Title = "Lied", Artist = "Band", Duration = TimeSpan.FromMinutes(3), FilePath = "x.mp3" };
|
||||||
|
Assert.Equal("Band - Lied", titles.For(new ScheduleItem(ScheduleItemKind.Song, "Lied", now, song.Duration, song)));
|
||||||
|
Assert.Equal("Nachrichten", titles.For(new ScheduleItem(ScheduleItemKind.News, "Nachrichten", now, TimeSpan.FromMinutes(5))));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Icecast_LogsInWithPutAndSendsMp3()
|
||||||
|
{
|
||||||
|
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||||
|
listener.Start();
|
||||||
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||||
|
var server = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
using var client = await listener.AcceptTcpClientAsync();
|
||||||
|
var network = client.GetStream();
|
||||||
|
var header = await ReadHeaderAsync(network);
|
||||||
|
await network.WriteAsync("HTTP/1.1 100 Continue\r\n\r\n"u8.ToArray());
|
||||||
|
var audio = new MemoryStream();
|
||||||
|
var buffer = new byte[4096];
|
||||||
|
while (audio.Length < 4000)
|
||||||
|
{
|
||||||
|
var read = await network.ReadAsync(buffer);
|
||||||
|
if (read == 0)
|
||||||
|
break;
|
||||||
|
audio.Write(buffer, 0, read);
|
||||||
|
}
|
||||||
|
return (header, audio.ToArray());
|
||||||
|
});
|
||||||
|
|
||||||
|
using var stream = await IcecastStream.ConnectAsync(new IcecastTarget("127.0.0.1", port, "live", "source", "pw"), Feed());
|
||||||
|
var (header, audio) = await server.WaitAsync(TimeSpan.FromSeconds(20));
|
||||||
|
|
||||||
|
Assert.StartsWith("PUT /live HTTP/1.1\r\n", header);
|
||||||
|
Assert.Contains($"Authorization: Basic {Convert.ToBase64String("source:pw"u8.ToArray())}\r\n", header);
|
||||||
|
Assert.Contains("Content-Type: audio/mpeg\r\n", header);
|
||||||
|
Assert.True(audio.Length >= 4000, $"only {audio.Length} bytes of audio arrived");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Icecast_RefusedLoginIsAReadableError()
|
||||||
|
{
|
||||||
|
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||||
|
listener.Start();
|
||||||
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||||
|
var server = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
using var client = await listener.AcceptTcpClientAsync();
|
||||||
|
var network = client.GetStream();
|
||||||
|
await ReadHeaderAsync(network);
|
||||||
|
await network.WriteAsync("HTTP/1.1 401 Authentication Required\r\n\r\n"u8.ToArray());
|
||||||
|
});
|
||||||
|
|
||||||
|
var error = await Assert.ThrowsAsync<LiveStreamException>(() =>
|
||||||
|
IcecastStream.ConnectAsync(new IcecastTarget("127.0.0.1", port, "/live", "source", "falsch"), Feed()));
|
||||||
|
await server;
|
||||||
|
|
||||||
|
Assert.Contains("Passwort", error.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Icecast_RejectsLineBreaksInTheRequest()
|
||||||
|
{
|
||||||
|
await Assert.ThrowsAsync<LiveStreamException>(() =>
|
||||||
|
IcecastStream.ConnectAsync(new IcecastTarget("127.0.0.1", 1, "live\r\nX: y", "source", "pw"), Feed()));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Icecast_TitleGoesToTheAdminInterface()
|
||||||
|
{
|
||||||
|
HttpRequestMessage? sent = null;
|
||||||
|
var http = new HttpClient(new FakeHandler(request =>
|
||||||
|
{
|
||||||
|
sent = request;
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||||
|
}));
|
||||||
|
|
||||||
|
await IcecastStream.UpdateTitleAsync(http, new IcecastTarget("live.example.test", 8080, "station", "source", "pw"), StreamTitles.AdBreak);
|
||||||
|
|
||||||
|
Assert.Equal("http://live.example.test:8080/admin/metadata?mount=%2Fstation&mode=updinfo&song=START_AD_BREAK", sent!.RequestUri!.AbsoluteUri);
|
||||||
|
Assert.Equal("Basic", sent.Headers.Authorization!.Scheme);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Provider_SearchesTitleAndArtistWithTheToken()
|
||||||
|
{
|
||||||
|
var requests = new List<HttpRequestMessage>();
|
||||||
|
var provider = new LautFmProvider(new HttpClient(new FakeHandler(request =>
|
||||||
|
{
|
||||||
|
lock (requests)
|
||||||
|
requests.Add(request);
|
||||||
|
return Json("""
|
||||||
|
{"tracks":[
|
||||||
|
{"id":7,"title":"Sommer","artist":"Band","duration":184,"_links":{"prelisten_authless":{"href":"/tracks/7/prelisten"}}},
|
||||||
|
{"id":8,"title":"Ohne Link","artist":"Band","duration":100,"_links":{}},
|
||||||
|
{"id":9,"title":"Unsicher","artist":"Band","duration":100,"_links":{"prelisten_authless":{"href":"http://example.test/9.mp3"}}}
|
||||||
|
],"_links":{}}
|
||||||
|
""");
|
||||||
|
})), () => Live);
|
||||||
|
|
||||||
|
var tracks = await provider.SearchAsync("Sommer");
|
||||||
|
|
||||||
|
var track = Assert.Single(tracks); // the same track from both searches, once; links that are missing or not https are skipped
|
||||||
|
Assert.Equal("lautfm:7", track.Id);
|
||||||
|
Assert.Equal("Sommer", track.Title);
|
||||||
|
Assert.Equal("Band", track.Creator);
|
||||||
|
Assert.Equal(TimeSpan.FromSeconds(184), track.Duration);
|
||||||
|
Assert.Equal("https://api.radioadmin.laut.fm/tracks/7/prelisten", track.Url);
|
||||||
|
Assert.Equal(2, requests.Count);
|
||||||
|
Assert.All(requests, r => Assert.Equal("Bearer geheimer-token", r.Headers.Authorization!.ToString()));
|
||||||
|
Assert.Contains(requests, r => r.RequestUri!.AbsoluteUri == "https://api.radioadmin.laut.fm/stations/123/tracks?title=Sommer");
|
||||||
|
Assert.Contains(requests, r => r.RequestUri!.AbsoluteUri == "https://api.radioadmin.laut.fm/stations/123/tracks?artist=Sommer");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Provider_ExplainsMissingOrRefusedLogin()
|
||||||
|
{
|
||||||
|
var refused = new LautFmProvider(new HttpClient(new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.Unauthorized))), () => Live);
|
||||||
|
var missing = new LautFmProvider(new HttpClient(new FakeHandler(_ => Json("{}"))), () => Live with { LautFmToken = "" });
|
||||||
|
|
||||||
|
Assert.Contains("Token", (await Assert.ThrowsAsync<MusicProviderException>(() => refused.SearchAsync("x"))).Message);
|
||||||
|
Assert.Contains("Token", (await Assert.ThrowsAsync<MusicProviderException>(() => missing.SearchAsync("x"))).Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ImportPage_ListsLautFmOnlyWhileSwitchedOn()
|
||||||
|
{
|
||||||
|
var settings = Live with { LautFmEnabled = false };
|
||||||
|
var lautFm = new LautFmProvider(new HttpClient(new FakeHandler(_ => Json("{}"))), () => settings);
|
||||||
|
var http = new HttpClient(new FakeHandler(_ => Json("{}")));
|
||||||
|
var controller = new OnlineImportController(
|
||||||
|
[new OpenverseProvider(http), lautFm], new TrackDownloader(http, _directory), new SongRepository(Path.Combine(_directory, "test.db")));
|
||||||
|
|
||||||
|
Assert.Equal(["Openverse"], controller.Providers.Select(p => p.Name));
|
||||||
|
settings = Live;
|
||||||
|
Assert.Equal(["Openverse", "laut.fm"], controller.Providers.Select(p => p.Name));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Three seconds of a tone, then nothing new: like the live feed of a quiet program.
|
||||||
|
private static BufferedWaveProvider Feed()
|
||||||
|
{
|
||||||
|
var feed = new BufferedWaveProvider(ProgramOutput.Format, TimeSpan.FromSeconds(10)) { ReadFully = false };
|
||||||
|
var tone = new SignalGenerator(44100, 2) { Frequency = 440, Gain = 0.2 };
|
||||||
|
var samples = new float[44100 * 2 * 3];
|
||||||
|
tone.Read(samples);
|
||||||
|
feed.AddSamples(System.Runtime.InteropServices.MemoryMarshal.AsBytes(samples.AsSpan()));
|
||||||
|
return feed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> ReadHeaderAsync(NetworkStream network)
|
||||||
|
{
|
||||||
|
var header = new StringBuilder();
|
||||||
|
var buffer = new byte[1];
|
||||||
|
while (!header.ToString().EndsWith("\r\n\r\n") && await network.ReadAsync(buffer) == 1)
|
||||||
|
header.Append((char)buffer[0]);
|
||||||
|
return header.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK) { Content = new StringContent(json) };
|
||||||
|
|
||||||
|
private sealed class FakeHandler(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||||
|
Task.FromResult(respond(request));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user