nixos-configs/configurations/homie/modules/home-assistant/netdaemon/apps/Spotify/PlaySong/PlaySong.cs

70 lines
2.3 KiB
C#
Raw Normal View History

using System;
using System.Reflection;
2024-12-18 16:44:21 -05:00
using System.Text.Json;
using HomeAssistantGenerated;
using NetDaemon.AppModel;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Integration;
2024-12-18 19:25:22 -05:00
using NetDaemonConfig.Apps.Spotify.Types;
namespace NetDaemonConfig.Apps.Spotify.PlaySong
{
public record PlaySongData(string? artist, string? song);
[NetDaemonApp]
public class PlaySong
{
// Snake-case json options
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
};
public PlaySong(IHaContext ha, Services services)
{
ha.RegisterServiceCallBack<PlaySongData>(
"spotify_play_song",
async (e) =>
{
try
{
SpotifyplusSearchTracksResponse? result = (
await services.Spotifyplus.SearchTracksAsync(
criteria: $"{e?.artist} {e?.song}",
limitTotal: 1,
2024-12-18 19:25:22 -05:00
entityId: Globals.DefaultEntityId,
// My Defaults
market: "CA",
includeExternal: "audio"
)
).Value.Deserialize<SpotifyplusSearchTracksResponse>(_jsonOptions);
string uri = result?.Result?.Items?[0]?.Uri ?? throw new TargetException(
$"The song {e?.song}{(e?.artist is null ? "" : $" by {e?.artist}")} could not be found."
);
services.Spotifyplus.PlayerMediaPlayTracks(
uris: uri,
2024-12-18 19:25:22 -05:00
entityId: Globals.DefaultEntityId,
deviceId: Globals.DefaultDevId,
// My Defaults
positionMs: 0,
delay: 0.50
);
}
catch (Exception error)
{
services.Notify.PersistentNotification(
message: error.Message,
title: "Erreur Spotify");
}
}
);
}
}
}