Add project files.
This commit is contained in:
12
TomatenMusic Api/.config/dotnet-tools.json
Normal file
12
TomatenMusic Api/.config/dotnet-tools.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-ef": {
|
||||
"version": "6.0.3",
|
||||
"commands": [
|
||||
"dotnet-ef"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
37
TomatenMusic Api/Auth/Controllers/UsersController.cs
Normal file
37
TomatenMusic Api/Auth/Controllers/UsersController.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
namespace WebApi.Controllers;
|
||||
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TomatenMusic_Api.Auth.Helpers;
|
||||
using TomatenMusic_Api.Auth.Models;
|
||||
using TomatenMusic_Api.Auth.Services;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class UsersController : ControllerBase
|
||||
{
|
||||
private IUserService _userService;
|
||||
|
||||
public UsersController(IUserService userService)
|
||||
{
|
||||
_userService = userService;
|
||||
}
|
||||
|
||||
[HttpPost("authenticate")]
|
||||
public IActionResult Authenticate(AuthenticateRequest model)
|
||||
{
|
||||
var response = _userService.Authenticate(model);
|
||||
|
||||
if (response == null)
|
||||
return BadRequest(new { message = "Username or password is incorrect" });
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
[HttpGet]
|
||||
public IActionResult GetAll()
|
||||
{
|
||||
var users = _userService.GetAll();
|
||||
return Ok(users);
|
||||
}
|
||||
}
|
14
TomatenMusic Api/Auth/Entities/User.cs
Normal file
14
TomatenMusic Api/Auth/Entities/User.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace TomatenMusic_Api.Auth.Entities;
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
public class User
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
public string Username { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public string Password { get; set; }
|
||||
}
|
6
TomatenMusic Api/Auth/Helpers/AppSettings.cs
Normal file
6
TomatenMusic Api/Auth/Helpers/AppSettings.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace TomatenMusic_Api.Auth.Helpers;
|
||||
|
||||
public class AppSettings
|
||||
{
|
||||
public string Secret { get; set; }
|
||||
}
|
19
TomatenMusic Api/Auth/Helpers/AuthorizeAttribute.cs
Normal file
19
TomatenMusic Api/Auth/Helpers/AuthorizeAttribute.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
namespace TomatenMusic_Api.Auth.Helpers;
|
||||
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using TomatenMusic_Api.Auth.Entities;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
|
||||
{
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
var user = (User)context.HttpContext.Items["User"];
|
||||
if (user == null)
|
||||
{
|
||||
// not logged in
|
||||
context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
|
||||
}
|
||||
}
|
||||
}
|
58
TomatenMusic Api/Auth/Helpers/JwtMiddleware.cs
Normal file
58
TomatenMusic Api/Auth/Helpers/JwtMiddleware.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
namespace TomatenMusic_Api.Auth.Helpers;
|
||||
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Text;
|
||||
using TomatenMusic_Api.Auth.Services;
|
||||
|
||||
public class JwtMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly AppSettings _appSettings;
|
||||
|
||||
public JwtMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings)
|
||||
{
|
||||
_next = next;
|
||||
_appSettings = appSettings.Value;
|
||||
}
|
||||
|
||||
public async Task Invoke(HttpContext context, IUserService userService)
|
||||
{
|
||||
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
|
||||
|
||||
if (token != null)
|
||||
attachUserToContext(context, userService, token);
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
|
||||
private void attachUserToContext(HttpContext context, IUserService userService, string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
|
||||
tokenHandler.ValidateToken(token, new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(key),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
// set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
|
||||
ClockSkew = TimeSpan.Zero
|
||||
}, out SecurityToken validatedToken);
|
||||
|
||||
var jwtToken = (JwtSecurityToken)validatedToken;
|
||||
var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
|
||||
|
||||
// attach user to context on successful jwt validation
|
||||
context.Items["User"] = userService.GetById(userId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// do nothing if jwt validation fails
|
||||
// user is not attached to context so request won't have access to secure routes
|
||||
}
|
||||
}
|
||||
}
|
12
TomatenMusic Api/Auth/Models/AuthenticateRequest.cs
Normal file
12
TomatenMusic Api/Auth/Models/AuthenticateRequest.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace TomatenMusic_Api.Auth.Models;
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
public class AuthenticateRequest
|
||||
{
|
||||
[Required]
|
||||
public string Username { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Password { get; set; }
|
||||
}
|
22
TomatenMusic Api/Auth/Models/AuthenticateResponse.cs
Normal file
22
TomatenMusic Api/Auth/Models/AuthenticateResponse.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
namespace TomatenMusic_Api.Auth.Models;
|
||||
|
||||
using TomatenMusic_Api.Auth.Entities;
|
||||
|
||||
public class AuthenticateResponse
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
public string Username { get; set; }
|
||||
public string Token { get; set; }
|
||||
|
||||
|
||||
public AuthenticateResponse(User user, string token)
|
||||
{
|
||||
Id = user.Id;
|
||||
FirstName = user.FirstName;
|
||||
LastName = user.LastName;
|
||||
Username = user.Username;
|
||||
Token = token;
|
||||
}
|
||||
}
|
75
TomatenMusic Api/Auth/Services/UserService.cs
Normal file
75
TomatenMusic Api/Auth/Services/UserService.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
namespace TomatenMusic_Api.Auth.Services;
|
||||
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using TomatenMusic_Api.Auth.Entities;
|
||||
using TomatenMusic_Api.Auth.Helpers;
|
||||
using TomatenMusic_Api.Auth.Models;
|
||||
|
||||
public interface IUserService
|
||||
{
|
||||
AuthenticateResponse Authenticate(AuthenticateRequest model);
|
||||
IEnumerable<User> GetAll();
|
||||
User GetById(int id);
|
||||
}
|
||||
|
||||
public class UserService : IUserService
|
||||
{
|
||||
// users hardcoded for simplicity, store in a db with hashed passwords in production applications
|
||||
private List<User> _users = new List<User>
|
||||
{
|
||||
new User { Id = 1, FirstName = "Jannick", LastName = "Voss", Username = "Glowman", Password = "RX5GXstLLBvdt#_N" },
|
||||
new User { Id = 2, FirstName = "Tim", LastName= "M<>ller", Password= "SGWaldsolms9", Username = "Tueem"}
|
||||
|
||||
};
|
||||
|
||||
private readonly AppSettings _appSettings;
|
||||
|
||||
public UserService(IOptions<AppSettings> appSettings)
|
||||
{
|
||||
_appSettings = appSettings.Value;
|
||||
}
|
||||
|
||||
public AuthenticateResponse Authenticate(AuthenticateRequest model)
|
||||
{
|
||||
var user = _users.SingleOrDefault(x => x.Username == model.Username && x.Password == model.Password);
|
||||
|
||||
// return null if user not found
|
||||
if (user == null) return null;
|
||||
|
||||
// authentication successful so generate jwt token
|
||||
var token = generateJwtToken(user);
|
||||
|
||||
return new AuthenticateResponse(user, token);
|
||||
}
|
||||
|
||||
public IEnumerable<User> GetAll()
|
||||
{
|
||||
return _users;
|
||||
}
|
||||
|
||||
public User GetById(int id)
|
||||
{
|
||||
return _users.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
|
||||
// helper methods
|
||||
|
||||
private string generateJwtToken(User user)
|
||||
{
|
||||
// generate token that is valid for 7 days
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
|
||||
Expires = DateTime.UtcNow.AddDays(1),
|
||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
||||
};
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
return tokenHandler.WriteToken(token);
|
||||
}
|
||||
}
|
92
TomatenMusic Api/Controllers/PlayerController.cs
Normal file
92
TomatenMusic Api/Controllers/PlayerController.cs
Normal file
@@ -0,0 +1,92 @@
|
||||
using DSharpPlus.Entities;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TomatenMusic;
|
||||
using TomatenMusic_Api;
|
||||
using TomatenMusic_Api.Auth.Helpers;
|
||||
using TomatenMusic_Api.Models;
|
||||
|
||||
namespace TomatenMusic_Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize]
|
||||
public class PlayerController : ControllerBase
|
||||
{
|
||||
|
||||
|
||||
private readonly ILogger<PlayerController> _logger;
|
||||
private readonly InProcessEventBus _eventBus;
|
||||
private readonly TomatenMusicDataService _tomatenMusicDataService;
|
||||
|
||||
public PlayerController(
|
||||
ILogger<PlayerController> logger,
|
||||
InProcessEventBus eventBus, TomatenMusicDataService dataService)
|
||||
|
||||
{
|
||||
_logger = logger;
|
||||
_eventBus = eventBus;
|
||||
_tomatenMusicDataService = dataService;
|
||||
}
|
||||
|
||||
[HttpGet("{guild_id}")]
|
||||
public async Task<IActionResult> Get(ulong guild_Id)
|
||||
{
|
||||
Models.PlayerConnectionInfo response = await _tomatenMusicDataService.GetConnectionInfoAsync(guild_Id);
|
||||
|
||||
if (response == null)
|
||||
{
|
||||
return BadRequest("The Bot is not connected or the guild is unknown");
|
||||
}
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get()
|
||||
{
|
||||
List<Models.PlayerConnectionInfo> response = await _tomatenMusicDataService.GetAllGuildPlayersAsync();
|
||||
|
||||
if (response == null)
|
||||
{
|
||||
return BadRequest("An Error occured while parsing the Guilds, Guilds were Empty");
|
||||
}
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
[HttpPost("connect")]
|
||||
public async Task<IActionResult> PostConnection(ChannelConnectRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _tomatenMusicDataService.GetGuildAsync(request.Guild_Id);
|
||||
}catch (Exception ex)
|
||||
{
|
||||
return NotFound("That Guild was not found");
|
||||
}
|
||||
|
||||
|
||||
Boolean? playing = await _tomatenMusicDataService.IsPlayingAsync(request.Guild_Id);
|
||||
|
||||
DiscordChannel channel;
|
||||
|
||||
if (playing == true)
|
||||
return BadRequest("The Bot is already playing");
|
||||
|
||||
if (await _tomatenMusicDataService.IsConnectedAsync(request.Guild_Id) == true)
|
||||
return BadRequest("The Bot is already connected");
|
||||
|
||||
try
|
||||
{
|
||||
channel = await _tomatenMusicDataService.GetDiscordChannelAsync(request.Channel_Id);
|
||||
}catch (Exception ex)
|
||||
{
|
||||
return NotFound("Channel was not Found");
|
||||
}
|
||||
|
||||
|
||||
|
||||
_eventBus.OnConnectRequestEvent(new InProcessEventBus.ChannelConnectEventArgs(request.Guild_Id, channel));
|
||||
|
||||
return Ok();
|
||||
}
|
||||
}
|
42
TomatenMusic Api/Models/BasicTrackInfo.cs
Normal file
42
TomatenMusic Api/Models/BasicTrackInfo.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using Lavalink4NET.Player;
|
||||
using System.Text.Json.Serialization;
|
||||
using TomatenMusic.Music.Entitites;
|
||||
|
||||
namespace TomatenMusic_Api.Models
|
||||
{
|
||||
public class BasicTrackInfo
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
public TrackPlatform Platform { get; set; }
|
||||
|
||||
public string YoutubeId { get; set; }
|
||||
|
||||
public string SpotifyId { get; set; }
|
||||
|
||||
public Uri URL { get; set; }
|
||||
|
||||
public BasicTrackInfo(LavalinkTrack track)
|
||||
{
|
||||
if (track == null)
|
||||
return;
|
||||
FullTrackContext ctx = (FullTrackContext)track.Context;
|
||||
|
||||
if (ctx == null)
|
||||
return;
|
||||
|
||||
Name = track.Title;
|
||||
Platform = ctx.SpotifyIdentifier == null ? TrackPlatform.YOUTUBE : TrackPlatform.SPOTIFY;
|
||||
YoutubeId = track.Identifier;
|
||||
SpotifyId = ctx.SpotifyIdentifier;
|
||||
URL = ctx.YoutubeUri;
|
||||
}
|
||||
}
|
||||
|
||||
public enum TrackPlatform
|
||||
{
|
||||
YOUTUBE,
|
||||
SPOTIFY,
|
||||
FILE
|
||||
}
|
||||
}
|
13
TomatenMusic Api/Models/ChannelConnectRequest.cs
Normal file
13
TomatenMusic Api/Models/ChannelConnectRequest.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using DSharpPlus.Entities;
|
||||
using Emzi0767.Utilities;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace TomatenMusic_Api.Models
|
||||
{
|
||||
public class ChannelConnectRequest
|
||||
{
|
||||
public ulong Channel_Id { get; set; }
|
||||
public ulong Guild_Id { get; set; }
|
||||
|
||||
}
|
||||
}
|
62
TomatenMusic Api/Models/PlayerConnectionInfo.cs
Normal file
62
TomatenMusic Api/Models/PlayerConnectionInfo.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using DSharpPlus.Entities;
|
||||
using Lavalink4NET;
|
||||
using Lavalink4NET.Player;
|
||||
using TomatenMusic;
|
||||
using TomatenMusic.Music;
|
||||
|
||||
namespace TomatenMusic_Api.Models
|
||||
{
|
||||
public class PlayerConnectionInfo
|
||||
{
|
||||
|
||||
public static async Task<PlayerConnectionInfo> Create(GuildPlayer player)
|
||||
{
|
||||
PlayerConnectionInfo response = new PlayerConnectionInfo();
|
||||
|
||||
response.PlaybackPosition = player.TrackPosition;
|
||||
response.Channel_Id = (ulong)player.VoiceChannelId;
|
||||
response.Guild_Id = player.GuildId;
|
||||
response.Paused = player.State == PlayerState.Paused;
|
||||
response.CurrentTrack = new BasicTrackInfo(player.CurrentTrack);
|
||||
response.LoopType = player.PlayerQueue.LoopType;
|
||||
|
||||
response.Queue = player.PlayerQueue.Queue.ToList().ConvertAll(x => new BasicTrackInfo(x));
|
||||
response.PlayedTracks = player.PlayerQueue.PlayedTracks.ToList().ConvertAll(x => new BasicTrackInfo(x));
|
||||
response.State = player.State;
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// Summary:
|
||||
// Gets the current playback position.
|
||||
public TimeSpan PlaybackPosition
|
||||
{
|
||||
get;
|
||||
internal set;
|
||||
}
|
||||
public PlayerState State { get; set; }
|
||||
//
|
||||
// Summary:
|
||||
// Gets the voice channel associated with this connection.
|
||||
public ulong Channel_Id { get; set; }
|
||||
|
||||
//
|
||||
// Summary:
|
||||
// Gets the guild associated with this connection.
|
||||
public ulong Guild_Id {get; set; }
|
||||
|
||||
public bool Paused { get; set; }
|
||||
|
||||
public BasicTrackInfo CurrentTrack { get; set; }
|
||||
|
||||
public LoopType LoopType { get; set; }
|
||||
|
||||
public List<BasicTrackInfo> Queue { get; set; }
|
||||
|
||||
public List<BasicTrackInfo> PlayedTracks { get; set; }
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
45
TomatenMusic Api/Program.cs
Normal file
45
TomatenMusic Api/Program.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using TomatenMusic_Api;
|
||||
using TomatenMusic_Api.Auth.Helpers;
|
||||
using TomatenMusic_Api.Auth.Services;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddCors();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
// configure strongly typed settings object
|
||||
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
|
||||
builder.Services.AddScoped<IUserService, UserService>();
|
||||
|
||||
builder.Services.AddSingleton<InProcessEventBus>();
|
||||
|
||||
builder.Services.AddSingleton<IHostedService, TomatenMusicService>();
|
||||
builder.Services.AddSingleton<TomatenMusicDataService>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseWebSockets();
|
||||
|
||||
app.UseCors(x => x
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader());
|
||||
|
||||
// custom jwt auth middleware
|
||||
app.UseMiddleware<JwtMiddleware>();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
|
||||
app.Run();
|
31
TomatenMusic Api/Properties/launchSettings.json
Normal file
31
TomatenMusic Api/Properties/launchSettings.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:46317",
|
||||
"sslPort": 44369
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"TomatenMusic_Api": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7210;http://localhost:5210",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
30
TomatenMusic Api/Services/EventBus.cs
Normal file
30
TomatenMusic Api/Services/EventBus.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using DSharpPlus.Entities;
|
||||
using Emzi0767.Utilities;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TomatenMusic_Api.Models;
|
||||
|
||||
namespace TomatenMusic_Api;
|
||||
|
||||
public class InProcessEventBus
|
||||
{
|
||||
public event AsyncEventHandler<InProcessEventBus, ChannelConnectEventArgs>? OnConnectRequest;
|
||||
|
||||
public void OnConnectRequestEvent(ChannelConnectEventArgs e)
|
||||
{
|
||||
_ = OnConnectRequest?.Invoke(this, e);
|
||||
}
|
||||
|
||||
public class ChannelConnectEventArgs : AsyncEventArgs
|
||||
{
|
||||
public ulong Guild_Id { get; set; }
|
||||
|
||||
public DiscordChannel Channel { get; set; }
|
||||
|
||||
public ChannelConnectEventArgs(ulong guild_Id, DiscordChannel channel)
|
||||
{
|
||||
Guild_Id = guild_Id;
|
||||
Channel = channel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
88
TomatenMusic Api/Services/TomatenMusicDataService.cs
Normal file
88
TomatenMusic Api/Services/TomatenMusicDataService.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using TomatenMusic.Music;
|
||||
using DSharpPlus;
|
||||
using DSharpPlus.Entities;
|
||||
using TomatenMusic_Api.Models;
|
||||
using Lavalink4NET.Player;
|
||||
using TomatenMusic;
|
||||
using Lavalink4NET;
|
||||
|
||||
namespace TomatenMusic_Api
|
||||
{
|
||||
public class TomatenMusicDataService : IHostedService
|
||||
{
|
||||
private ILogger<TomatenMusicDataService> _logger;
|
||||
public IServiceProvider _serviceProvider { get; set; } = TomatenMusicBot.ServiceProvider;
|
||||
public IAudioService _audioService { get; set; }
|
||||
public TomatenMusicDataService(ILogger<TomatenMusicDataService> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_audioService = _serviceProvider.GetRequiredService<IAudioService>();
|
||||
}
|
||||
|
||||
public async Task<PlayerConnectionInfo> GetConnectionInfoAsync(ulong guild_id)
|
||||
{
|
||||
GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(guild_id);
|
||||
if (player == null)
|
||||
return null;
|
||||
return await PlayerConnectionInfo.Create(player);
|
||||
}
|
||||
|
||||
public async Task<Boolean?> IsPlayingAsync(ulong guild_id)
|
||||
{
|
||||
GuildPlayer player = _audioService.GetPlayer<GuildPlayer>(guild_id);
|
||||
|
||||
if (player == null)
|
||||
return false;
|
||||
return player.State == PlayerState.Playing;
|
||||
}
|
||||
public async Task<Boolean?> IsConnectedAsync(ulong guild_id)
|
||||
{
|
||||
GuildPlayer player = _audioService.GetPlayer<GuildPlayer>(guild_id);
|
||||
|
||||
if (player == null)
|
||||
return false;
|
||||
|
||||
return player.State != PlayerState.NotConnected;
|
||||
}
|
||||
|
||||
public async Task<List<PlayerConnectionInfo>> GetAllGuildPlayersAsync()
|
||||
{
|
||||
List<PlayerConnectionInfo> list = new List<PlayerConnectionInfo>();
|
||||
foreach (var guild in _audioService.GetPlayers<GuildPlayer>())
|
||||
{
|
||||
list.Add(await PlayerConnectionInfo.Create(guild));
|
||||
}
|
||||
if (list.Count == 0)
|
||||
return null;
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public Task<DiscordChannel> GetDiscordChannelAsync(ulong channel_id)
|
||||
{
|
||||
DiscordClient client = _serviceProvider.GetRequiredService<DiscordClient>();
|
||||
|
||||
return client.GetChannelAsync(channel_id);
|
||||
}
|
||||
|
||||
public Task<DiscordGuild> GetGuildAsync(ulong guild_id)
|
||||
{
|
||||
DiscordClient client = _serviceProvider.GetRequiredService<DiscordClient>();
|
||||
|
||||
return client.GetGuildAsync(guild_id);
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("TomatenMusicDataService starting...");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("TomatenMusicDataService stopping...");
|
||||
return Task.CompletedTask;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
54
TomatenMusic Api/Services/TomatenMusicService.cs
Normal file
54
TomatenMusic Api/Services/TomatenMusicService.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using Lavalink4NET;
|
||||
using TomatenMusic;
|
||||
using TomatenMusic.Music;
|
||||
using TomatenMusic_Api.Models;
|
||||
using static TomatenMusic_Api.InProcessEventBus;
|
||||
|
||||
namespace TomatenMusic_Api
|
||||
{
|
||||
public class TomatenMusicService : IHostedService
|
||||
{
|
||||
private readonly InProcessEventBus _inProcessEventBus;
|
||||
private readonly ILogger<TomatenMusicService> _logger;
|
||||
public TomatenMusicBot _bot { get; set; }
|
||||
public IAudioService _audioService { get; set; }
|
||||
|
||||
public TomatenMusicService(InProcessEventBus inProcessEventBus, ILogger<TomatenMusicService> logger)
|
||||
{
|
||||
_inProcessEventBus = inProcessEventBus;
|
||||
_logger = logger;
|
||||
|
||||
Initialize();
|
||||
}
|
||||
|
||||
private void Initialize()
|
||||
{
|
||||
_inProcessEventBus.OnConnectRequest += _inProcessEventBus_OnConnectRequest;
|
||||
}
|
||||
|
||||
private async Task _inProcessEventBus_OnConnectRequest(InProcessEventBus sender, ChannelConnectEventArgs e)
|
||||
{
|
||||
_logger.LogInformation("Channel Connected!");
|
||||
GuildPlayer player = await _audioService.JoinAsync<GuildPlayer>(e.Guild_Id, e.Channel.Id, true);
|
||||
}
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Starting service...");
|
||||
_bot = new TomatenMusicBot();
|
||||
await _bot.InitBotAsync();
|
||||
_audioService = TomatenMusicBot.ServiceProvider.GetRequiredService<IAudioService>();
|
||||
_logger.LogInformation("Service started!");
|
||||
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Shutting down service...");
|
||||
await _bot.ShutdownBotAsync();
|
||||
_logger.LogInformation("Service shut down!");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
35
TomatenMusic Api/TomatenMusic Api.csproj
Normal file
35
TomatenMusic Api/TomatenMusic Api.csproj
Normal file
@@ -0,0 +1,35 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>TomatenMusic_Api</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Remove="config.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="config.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.WebSockets" Version="0.2.3.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\TomatenMusicCore\TomatenMusicCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Auth\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
8
TomatenMusic Api/appsettings.Development.json
Normal file
8
TomatenMusic Api/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
11
TomatenMusic Api/appsettings.json
Normal file
11
TomatenMusic Api/appsettings.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"AppSettings": {
|
||||
"Secret": "WWT9uwYzMkhOnUrZD7CSeT9forbwpbci"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"Microsoft.AspNetCore": "Debug"
|
||||
}
|
||||
}
|
||||
}
|
7
TomatenMusic Api/config.json
Normal file
7
TomatenMusic Api/config.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"TOKEN": "ODQwNjQ5NjU1MTAwMjQzOTY4.YJbSAA.jwzaw5N-tAUeiEdvE969wfBAU7o",
|
||||
"LavaLinkPassword": "SGWaldsolms9",
|
||||
"SpotifyClientId": "14b77fa47f2f492db58cbdca8f1e5d9c",
|
||||
"SpotifyClientSecret": "c247625f0cfe4b72a1faa01b7c5b8eea",
|
||||
"YoutubeApiKey": "AIzaSyBIcTl9JQ9jF412mX0Wfp_3Y-4a-V0SASQ"
|
||||
}
|
Reference in New Issue
Block a user