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
@@ -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.
|
||||
services.AddSingleton<IMusicProvider, OpenverseProvider>();
|
||||
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<OnlineImportController>();
|
||||
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)
|
||||
{
|
||||
_services?.GetRequiredService<LiveController>().Stop();
|
||||
_services?.GetRequiredService<ScheduleController>().Stop();
|
||||
_services?.Dispose();
|
||||
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>
|
||||
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
|
||||
{
|
||||
/// <summary>Every provider registered in <c>App</c>, in registration order.</summary>
|
||||
public IReadOnlyList<IMusicProvider> Providers { get; } = providers.ToList();
|
||||
private readonly IReadOnlyList<IMusicProvider> _providers = 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>
|
||||
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
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>
|
||||
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(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
|
||||
|
||||
@@ -52,6 +87,17 @@ public record AppSettings
|
||||
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.";
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -83,4 +129,24 @@ public record AppSettings
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
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>
|
||||
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>
|
||||
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 WaveOut? _broadcastDevice;
|
||||
private WaveOut? _monitorDevice;
|
||||
private volatile BufferedWaveProvider? _liveFeed;
|
||||
|
||||
private ProgramOutput()
|
||||
{
|
||||
@@ -81,6 +82,37 @@ public sealed class ProgramOutput
|
||||
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>
|
||||
public void Remove(ISampleProvider input) => Mixer.Remove(input);
|
||||
|
||||
@@ -111,7 +143,7 @@ public sealed class ProgramOutput
|
||||
if (monitor < 0)
|
||||
{
|
||||
// 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
|
||||
{
|
||||
@@ -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,
|
||||
// so the two device clocks drifting apart never builds up a delay.
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -158,9 +190,9 @@ public sealed class ProgramOutput
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
private sealed class Tap(ProgramMixer mixer, BufferedWaveProvider? monitorBuffer) : ISampleProvider
|
||||
private sealed class Tap(ProgramOutput output, BufferedWaveProvider? monitorBuffer) : ISampleProvider
|
||||
{
|
||||
private float[] _other = [];
|
||||
|
||||
@@ -172,15 +204,19 @@ public sealed class ProgramOutput
|
||||
_other = new float[buffer.Length];
|
||||
var other = _other.AsSpan(0, buffer.Length);
|
||||
|
||||
Span<float> broadcast;
|
||||
if (monitorBuffer is null)
|
||||
{
|
||||
mixer.Mix(other, buffer);
|
||||
output.Mixer.Mix(other, buffer);
|
||||
broadcast = other;
|
||||
}
|
||||
else
|
||||
{
|
||||
mixer.Mix(buffer, other);
|
||||
output.Mixer.Mix(buffer, 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,18 @@ namespace Radiosender.Services;
|
||||
internal static partial class ProviderParsing
|
||||
{
|
||||
/// <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>
|
||||
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
|
||||
{
|
||||
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)
|
||||
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.
|
||||
|
||||
@@ -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}"
|
||||
ToolTip="Plant ab diesem Moment und geht sofort auf Sendung. Die Startzeit wird ignoriert."
|
||||
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>
|
||||
|
||||
<ui:InfoBar x:Name="Message"
|
||||
|
||||
@@ -31,10 +31,12 @@ public partial class SchedulePage : Page
|
||||
|
||||
private readonly Microphone _microphone;
|
||||
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;
|
||||
_live = live;
|
||||
_microphone = microphone;
|
||||
_mixer = output.Mixer;
|
||||
InitializeComponent();
|
||||
@@ -53,6 +55,7 @@ public partial class SchedulePage : Page
|
||||
_controller.ItemStarted += OnItemStarted;
|
||||
_controller.ItemFailed += OnItemFailed;
|
||||
_controller.Finished += OnFinished;
|
||||
_live.Problem += OnLiveProblem;
|
||||
|
||||
_loading = true;
|
||||
VolumeSlider.Value = _controller.Volume;
|
||||
@@ -63,6 +66,7 @@ public partial class SchedulePage : Page
|
||||
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
|
||||
_loading = false;
|
||||
ShowMicrophone(); // it stays on while the user visits other pages
|
||||
ShowLive();
|
||||
FillStartTimes();
|
||||
if (_controller.Plan.Count > 0)
|
||||
UnlimitedBox.IsChecked = _controller.IsUnlimited;
|
||||
@@ -82,6 +86,7 @@ public partial class SchedulePage : Page
|
||||
_controller.ItemStarted -= OnItemStarted;
|
||||
_controller.ItemFailed -= OnItemFailed;
|
||||
_controller.Finished -= OnFinished;
|
||||
_live.Problem -= OnLiveProblem;
|
||||
_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");
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -154,6 +154,74 @@
|
||||
</Grid>
|
||||
</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">
|
||||
<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}"
|
||||
|
||||
@@ -41,8 +41,21 @@ public partial class SettingsPage : Page
|
||||
NewsMinutesBox.Value = settings.NewsMinutesPerHour;
|
||||
ModeratorMinutesBox.Value = settings.ModeratorMinutesPerHour;
|
||||
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.
|
||||
private static AppSettings Defaults { get; } = new();
|
||||
|
||||
@@ -59,6 +72,14 @@ public partial class SettingsPage : Page
|
||||
AdMinutesPerHour = (int)(AdMinutesBox.Value ?? Defaults.AdMinutesPerHour),
|
||||
BroadcastDevice = BroadcastDeviceBox.SelectedIndex > 0 ? (string)BroadcastDeviceBox.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)
|
||||
|
||||
Reference in new issue
Block a user