55 lines
1.8 KiB
C#
55 lines
1.8 KiB
C#
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace webmusic.Pages;
|
|
|
|
[ApiController]
|
|
[Route("/log")]
|
|
public class Log : Controller {
|
|
public const bool StatisticsEnabled = true;
|
|
public const string StatisticsUser = "zotan";
|
|
|
|
private const string StatisticsUrl = "https://zotan.pw/np/log";
|
|
private const string StatisticsSource = "music.ztn.sh";
|
|
private readonly string _statisticsToken = System.IO.File.Exists(".bearer_token") ? System.IO.File.ReadAllLines(".bearer_token")[0] : "";
|
|
|
|
[HttpGet]
|
|
public string Get(string artist, string album, string url) {
|
|
if (StatisticsEnabled && Request.Headers["Remote-User"].Equals(StatisticsUser)) {
|
|
var res = MakeRestRequest(new LogPlaybackRequest { Artist = artist, Title = album, Link = url, Source = StatisticsSource });
|
|
Response.StatusCode = (int)res;
|
|
|
|
return res switch {
|
|
HttpStatusCode.Created => $"Logged: {artist} - {album}",
|
|
HttpStatusCode.Accepted => $"Skipped: {artist} - {album}",
|
|
HttpStatusCode.Forbidden => "Invalid token.",
|
|
_ => $"Error {Response.StatusCode} \"{res}\" occured."
|
|
};
|
|
}
|
|
|
|
Response.StatusCode = 403;
|
|
return null;
|
|
}
|
|
|
|
private HttpStatusCode MakeRestRequest(LogPlaybackRequest rq) {
|
|
using var client = new HttpClient();
|
|
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(_statisticsToken);
|
|
|
|
var json = JsonSerializer.Serialize(rq);
|
|
var data = new StringContent(json, Encoding.UTF8, "application/json");
|
|
var response = client.PostAsync(StatisticsUrl, data).Result;
|
|
return response.StatusCode;
|
|
}
|
|
|
|
private class LogPlaybackRequest {
|
|
public string Artist { get; set; }
|
|
public string Title { get; set; }
|
|
public string Source { get; set; }
|
|
public string Link { get; set; }
|
|
}
|
|
}
|