From e14c3a3f075e810c1c739f95da7f5ae2c01ebba8 Mon Sep 17 00:00:00 2001 From: jxpxxzj Date: Thu, 3 Oct 2019 16:51:44 +0800 Subject: [PATCH] initial commit --- .gitignore | 437 ++++++++++++++++++ PrivateCloudMusic.sln | 17 + PrivateCloudMusic/Entities/Music.cs | 25 + PrivateCloudMusic/Entities/Playlist.cs | 18 + PrivateCloudMusic/Handlers/AlbumHandler.cs | 19 + PrivateCloudMusic/Handlers/DefaultHandler.cs | 14 + PrivateCloudMusic/Handlers/FolderHandler.cs | 7 + PrivateCloudMusic/Handlers/MusicHandler.cs | 49 ++ PrivateCloudMusic/Handlers/PlaylistHandler.cs | 44 ++ PrivateCloudMusic/PrivateCloudMusic.csproj | 32 ++ PrivateCloudMusic/Program.cs | 30 ++ .../Properties/launchSettings.json | 27 ++ PrivateCloudMusic/Proto/api.proto | 111 +++++ PrivateCloudMusic/Proxy/Context.cs | 19 + PrivateCloudMusic/Proxy/Endpoint.cs | 7 + PrivateCloudMusic/Proxy/MessageHandler.cs | 168 +++++++ .../Proxy/Middlewares/BaseMiddleware.cs | 7 + .../Proxy/Middlewares/Logging.cs | 50 ++ PrivateCloudMusic/Proxy/Middlewares/Preset.cs | 46 ++ PrivateCloudMusic/Proxy/Parser.cs | 76 +++ PrivateCloudMusic/Proxy/Router.cs | 49 ++ PrivateCloudMusic/Services/MusicService.cs | 95 ++++ PrivateCloudMusic/Startup.cs | 65 +++ PrivateCloudMusic/Utils/ConfigManager.cs | 14 + PrivateCloudMusic/Utils/DbManager.cs | 16 + PrivateCloudMusic/Utils/LogManager.cs | 29 ++ .../appsettings.Development.json | 9 + PrivateCloudMusic/appsettings.json | 10 + 28 files changed, 1490 insertions(+) create mode 100644 .gitignore create mode 100644 PrivateCloudMusic.sln create mode 100644 PrivateCloudMusic/Entities/Music.cs create mode 100644 PrivateCloudMusic/Entities/Playlist.cs create mode 100644 PrivateCloudMusic/Handlers/AlbumHandler.cs create mode 100644 PrivateCloudMusic/Handlers/DefaultHandler.cs create mode 100644 PrivateCloudMusic/Handlers/FolderHandler.cs create mode 100644 PrivateCloudMusic/Handlers/MusicHandler.cs create mode 100644 PrivateCloudMusic/Handlers/PlaylistHandler.cs create mode 100644 PrivateCloudMusic/PrivateCloudMusic.csproj create mode 100644 PrivateCloudMusic/Program.cs create mode 100644 PrivateCloudMusic/Properties/launchSettings.json create mode 100644 PrivateCloudMusic/Proto/api.proto create mode 100644 PrivateCloudMusic/Proxy/Context.cs create mode 100644 PrivateCloudMusic/Proxy/Endpoint.cs create mode 100644 PrivateCloudMusic/Proxy/MessageHandler.cs create mode 100644 PrivateCloudMusic/Proxy/Middlewares/BaseMiddleware.cs create mode 100644 PrivateCloudMusic/Proxy/Middlewares/Logging.cs create mode 100644 PrivateCloudMusic/Proxy/Middlewares/Preset.cs create mode 100644 PrivateCloudMusic/Proxy/Parser.cs create mode 100644 PrivateCloudMusic/Proxy/Router.cs create mode 100644 PrivateCloudMusic/Services/MusicService.cs create mode 100644 PrivateCloudMusic/Startup.cs create mode 100644 PrivateCloudMusic/Utils/ConfigManager.cs create mode 100644 PrivateCloudMusic/Utils/DbManager.cs create mode 100644 PrivateCloudMusic/Utils/LogManager.cs create mode 100644 PrivateCloudMusic/appsettings.Development.json create mode 100644 PrivateCloudMusic/appsettings.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0756dd2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,437 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- Backup*.rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# JetBrains Rider +.idea/ +*.sln.iml + +## +## Visual Studio Code +## +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +*.litedb + +.vscode/ \ No newline at end of file diff --git a/PrivateCloudMusic.sln b/PrivateCloudMusic.sln new file mode 100644 index 0000000..0de7ae0 --- /dev/null +++ b/PrivateCloudMusic.sln @@ -0,0 +1,17 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrivateCloudMusic", "PrivateCloudMusic\PrivateCloudMusic.csproj", "{5FD280B3-FA56-411F-9540-9A2BAF730AE1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5FD280B3-FA56-411F-9540-9A2BAF730AE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5FD280B3-FA56-411F-9540-9A2BAF730AE1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5FD280B3-FA56-411F-9540-9A2BAF730AE1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5FD280B3-FA56-411F-9540-9A2BAF730AE1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/PrivateCloudMusic/Entities/Music.cs b/PrivateCloudMusic/Entities/Music.cs new file mode 100644 index 0000000..d0fb883 --- /dev/null +++ b/PrivateCloudMusic/Entities/Music.cs @@ -0,0 +1,25 @@ +using System.IO; +using LiteDB; + +namespace Pcm.Entities +{ + public class Music + { + [BsonId] + public ObjectId MusicId { get; set; } + + public string Title { get; set; } + public string Album { get; set; } + public string[] Genres { get; set; } + public string[] Performers { get; set; } + + public uint Track { get; set; } + public uint TrackCount { get; set; } + + public string FileName => Path.GetFileName(FilePath); + public string FilePath { get; set; } + public int PlayCount { get; set; } + public string MimeType { get; set; } + public long Length { get; set; } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Entities/Playlist.cs b/PrivateCloudMusic/Entities/Playlist.cs new file mode 100644 index 0000000..42876d5 --- /dev/null +++ b/PrivateCloudMusic/Entities/Playlist.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using LiteDB; + +namespace Pcm.Entities +{ + public class Playlist + { + public ObjectId Id { get; set; } + + public string Name { get; set; } + + [BsonRef("music")] + public List Musics { get; set; } + + public DateTime CreatedAt { get; set; } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Handlers/AlbumHandler.cs b/PrivateCloudMusic/Handlers/AlbumHandler.cs new file mode 100644 index 0000000..dac8870 --- /dev/null +++ b/PrivateCloudMusic/Handlers/AlbumHandler.cs @@ -0,0 +1,19 @@ +using System.Threading.Tasks; +using Pcm.Proto; +using Pcm.Proxy; + +namespace Pcm.Handlers +{ + public class AlbumHandler + { + public async Task Get(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task List(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Handlers/DefaultHandler.cs b/PrivateCloudMusic/Handlers/DefaultHandler.cs new file mode 100644 index 0000000..4af032b --- /dev/null +++ b/PrivateCloudMusic/Handlers/DefaultHandler.cs @@ -0,0 +1,14 @@ +using System.Threading.Tasks; +using Pcm.Proto; +using Pcm.Proxy; + +namespace Pcm.Handlers +{ + public class DefaultHandler + { + public async Task Default(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Handlers/FolderHandler.cs b/PrivateCloudMusic/Handlers/FolderHandler.cs new file mode 100644 index 0000000..c03f8d2 --- /dev/null +++ b/PrivateCloudMusic/Handlers/FolderHandler.cs @@ -0,0 +1,7 @@ +namespace Pcm.Handlers +{ + public class FolderHandler + { + + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Handlers/MusicHandler.cs b/PrivateCloudMusic/Handlers/MusicHandler.cs new file mode 100644 index 0000000..82a549d --- /dev/null +++ b/PrivateCloudMusic/Handlers/MusicHandler.cs @@ -0,0 +1,49 @@ +using System.Threading.Tasks; +using Pcm.Proto; +using Pcm.Proxy; +using Pcm.Services; + +namespace Pcm.Handlers +{ + public class MusicHandler + { + public async Task Get(Context ctx, Request req, Response resp) + { + var music = MusicService.Instance.Get(req.Body.GetMusicBody.Id); + if (music != null) + { + resp.Body.GetMusicBody = new GetMusicResponseBody() + { + Title = music.Title, + Album = music.Album, + Genres = { music.Genres }, + Performers = { music.Performers }, + Track = music.Track, + TrackCount = music.TrackCount, + FileName = music.FileName, + PlayCount = music.PlayCount, + Length = music.Length, + MimeType = music.MimeType, + CreatedAt = music.MusicId.Timestamp + }; + } + + return await Task.FromResult(StatusCode.Ok); + } + + public async Task List(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Delete(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Modify(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Handlers/PlaylistHandler.cs b/PrivateCloudMusic/Handlers/PlaylistHandler.cs new file mode 100644 index 0000000..d3c7be7 --- /dev/null +++ b/PrivateCloudMusic/Handlers/PlaylistHandler.cs @@ -0,0 +1,44 @@ +using System.Threading.Tasks; +using Pcm.Proto; +using Pcm.Proxy; + +namespace Pcm.Handlers +{ + public class PlaylistHandler + { + public async Task List(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Get(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Create(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Rename(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Add(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Remove(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + + public async Task Delete(Context ctx, Request req, Response resp) + { + return await Task.FromResult(StatusCode.Ok); + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/PrivateCloudMusic.csproj b/PrivateCloudMusic/PrivateCloudMusic.csproj new file mode 100644 index 0000000..3e1a266 --- /dev/null +++ b/PrivateCloudMusic/PrivateCloudMusic.csproj @@ -0,0 +1,32 @@ + + + + netcoreapp3.0 + Pcm + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PrivateCloudMusic/Program.cs b/PrivateCloudMusic/Program.cs new file mode 100644 index 0000000..de84b0b --- /dev/null +++ b/PrivateCloudMusic/Program.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Pcm.Services; +using Pcm.Utils; + +namespace Pcm +{ + public class Program + { + public static void Main(string[] args) + { + ConfigManager.Config = new ConfigurationBuilder() + .AddJsonFile("config.json", optional: true) //this is not needed, but could be useful + .AddEnvironmentVariables() + .AddCommandLine(args) + .Build(); + + var m = MusicService.Instance.Add(@"/Users/xiaozijin/Downloads/03.オードリー.mp3"); + + + + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); + } +} diff --git a/PrivateCloudMusic/Properties/launchSettings.json b/PrivateCloudMusic/Properties/launchSettings.json new file mode 100644 index 0000000..2d0fcd4 --- /dev/null +++ b/PrivateCloudMusic/Properties/launchSettings.json @@ -0,0 +1,27 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:27108", + "sslPort": 44345 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "PrivateCloudMusic": { + "commandName": "Project", + "launchBrowser": false, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/PrivateCloudMusic/Proto/api.proto b/PrivateCloudMusic/Proto/api.proto new file mode 100644 index 0000000..fb0ad34 --- /dev/null +++ b/PrivateCloudMusic/Proto/api.proto @@ -0,0 +1,111 @@ +syntax = "proto3"; +package pcm; + +option csharp_namespace = "Pcm.Proto"; + +// request + +message GetMusicRequestBody { + string id = 1; +} + +message GetMusicResponseBody { + string title = 1; + string album = 2; + repeated string genres = 3; + repeated string performers = 4; + uint32 track = 5; + uint32 track_count = 6; + string file_name = 7; + int32 play_count = 8; + int64 length = 9; + string mime_type = 10; + int64 created_at = 11; +} + +// response + +// base + +message Request { + int32 cmd = 1; // refer to enum CMD + int64 sequence_id = 2; + string sdk_version = 3; + string token = 4; + Refer refer = 5; + RequestBody body = 6; + map headers = 7; +} + +message RequestBody { + GetMusicRequestBody get_music_body = 100; +} + +enum CMD { + CMD_NOT_USED = 0; + + GET_MUSIC = 100; + + LIST_MUSIC = 200; + LIST_PLAYLIST = 201; + LIST_ALBUM = 202; + LIST_ARTIST = 203; + LIST_TYPE = 204; + LIST_FOLDER_TREE = 205; + + GET_PLAYLIST = 300; + GET_ALBUM = 301; + GET_ARTIST = 302; + GET_TYPE = 303; + GET_FOLDER = 304; + + ACTION_RESCAN_MUSIC = 400; + ACTION_MODIFY_MUSIC_EXT = 401; + ACTION_ADD_MUSIC = 402; + ACTION_DELETE_MUSIC = 403; + ACTION_CREATE_PLAYLIST = 404; + ACTION_RENAME_PLAYLIST = 405; + ACTION_ADD_MUSIC_TO_PLAYLIST = 406; + ACTION_REMOVE_MUSIC_FROM_PLAYLIST = 407; + ACTION_DELETE_PLAYLIST = 408; + + REPORT_PLAYER_START = 500; + REPORT_MUSIC_STOP = 503; +} + +enum Refer { + REFER_NOT_USED = 0; + ANDROID = 1; + IOS = 2; + PC = 3; + SERVER = 4; +} + +message Response { + int32 cmd = 1; + int64 sequence_id = 2; //Same as request + int32 status_code = 3; //refer to enum StatusCode + string error_desc = 4; + ResponseBody body = 6; + string log_id = 7; + map extra = 8; +} + +message ResponseBody { + GetMusicResponseBody get_music_body = 100; +} + +enum StatusCode { + OK = 0; + INVALID_TOKEN = 1; + EXPIRED_TOKEN = 2; + + INVALID_REQUEST = 3; + INVALID_CMD = 4; + SERVER_ERR = 5; +} + +service Pcm { + rpc SendRequest(Request) returns (Response); +} + diff --git a/PrivateCloudMusic/Proxy/Context.cs b/PrivateCloudMusic/Proxy/Context.cs new file mode 100644 index 0000000..ff4590d --- /dev/null +++ b/PrivateCloudMusic/Proxy/Context.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System.Net.WebSockets; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Pcm.Utils; + +namespace Pcm.Proxy +{ + public class Context + { + public byte[] RawData { get; set; } + public PayloadType PayloadType { get; set; } + public HttpContext HttpContext { get; set; } + public WebSocket WebSocket { get; set; } + public Dictionary Items { get; protected set; } = new Dictionary(); + + public ILogger Logger { get; protected set; } = LogManager.CreateLogger(); + } +} diff --git a/PrivateCloudMusic/Proxy/Endpoint.cs b/PrivateCloudMusic/Proxy/Endpoint.cs new file mode 100644 index 0000000..e7633fc --- /dev/null +++ b/PrivateCloudMusic/Proxy/Endpoint.cs @@ -0,0 +1,7 @@ +using System.Threading.Tasks; +using Pcm.Proto; + +namespace Pcm.Proxy +{ + public delegate Task Endpoint(Context ctx, Request req, Response resp); +} \ No newline at end of file diff --git a/PrivateCloudMusic/Proxy/MessageHandler.cs b/PrivateCloudMusic/Proxy/MessageHandler.cs new file mode 100644 index 0000000..6aa041f --- /dev/null +++ b/PrivateCloudMusic/Proxy/MessageHandler.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using System.Buffers; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using Google.Protobuf; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.FileProviders; +using Microsoft.Net.Http.Headers; +using Pcm.Proto; +using Pcm.Proxy.Middlewares; +using Pcm.Services; + +namespace Pcm.Proxy +{ + public class MessageHandler + { + private readonly Dictionary _webSockets = new Dictionary(); + + private readonly List _middlewares = new List(); + + private readonly Dictionary _parsers = new Dictionary(); + + private readonly Router _router = new Router(); + + public MessageHandler() + { + addMiddlewares(); + addParser(); + + // reverse to make sure the req is passed in order + _middlewares.Reverse(); + } + + private void addMiddlewares() + { + _middlewares.Add(new Logging()); + _middlewares.Add(new Preset()); + } + + private void addParser() + { + _parsers.Add(PayloadType.Json, new JsonParser()); + _parsers.Add(PayloadType.Protobuf, new ProtobufParser()); + } + + public async Task HandleWs(HttpContext context, WebSocket webSocket) + { + var guid = new Guid().ToString(); + _webSockets.Add(guid, webSocket); + try + { + var buffer = new byte[1024 * 8]; + while (!webSocket.CloseStatus.HasValue) + { + var result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); + if (!result.EndOfMessage) + { + throw new Exception("payload too large"); + } + + var ctx = new Context() + { + HttpContext = context, + WebSocket = webSocket + }; + var resp = await handle(ctx, buffer); + await webSocket.SendAsync(new ArraySegment(resp), WebSocketMessageType.Binary, true, CancellationToken.None); + } + } + finally + { + _webSockets.Remove(guid); + await webSocket.CloseAsync(WebSocketCloseStatus.Empty, webSocket.CloseStatusDescription, CancellationToken.None); + } + } + + public async Task HandleHttp(HttpContext context) + { + var ctx = new Context() + { + HttpContext = context + }; + + var buffer = new byte[1024 * 8]; + var count = await context.Request.Body.ReadAsync(buffer); + var resp = await handle(ctx, buffer.Take(count).ToArray()); + await context.Response.BodyWriter.WriteAsync(resp); + + } + + private async Task handle(Context ctx, byte[] data) + { + ctx.RawData = data; + + var (req, type) = parseBody(ctx); + ctx.PayloadType = type; + var resp = new Response(); + + var endpoint = _router.Process(ctx, req, resp); + endpoint = _middlewares.Aggregate(endpoint, (current, middleware) => middleware.Create(current)); + await endpoint.Invoke(ctx, req, resp); + + var memBuffer = new MemoryStream(); + await memBuffer.WriteAsync(writeBody(resp, type)); + var buffer = memBuffer.ToArray(); + + return buffer; + } + + private async Task wsBroadcast(Response resp) + { + var memBuffer = new MemoryStream(); + resp.WriteTo(memBuffer); + var buffer = memBuffer.ToArray(); + foreach (var ws in _webSockets.Select(kv => kv.Value).Where(ws => !ws.CloseStatus.HasValue)) + { + await ws.SendAsync(new ArraySegment(buffer), WebSocketMessageType.Binary, true, CancellationToken.None); + } + } + + private Encoding payloadEncoding = Encoding.UTF8; + + private (Request, PayloadType) parseBody(Context ctx) + { + foreach (var parser in _parsers) + { + var (req, type) = parser.Value.From(ctx.RawData, payloadEncoding); + if (req != null) + { + return (req, type); + } + } + + throw new NotImplementedException(); + } + + private byte[] writeBody(Response resp, PayloadType type) + { + var parser = _parsers[type]; + return parser.To(resp, payloadEncoding); + } + + public async Task HandleMusic(HttpContext ctx) + { + var id = ctx.GetRouteValue("id").ToString(); + + var music = MusicService.Instance.Get(id); + if (music == null) + { + throw new FileNotFoundException(); + } + + var dir = Path.GetDirectoryName(music.FilePath); + var fi = new PhysicalFileProvider(dir).GetFileInfo(music.FileName); + ctx.Response.Headers[HeaderNames.ContentDisposition] = "attachment; filename=" + WebUtility.UrlEncode(music.FileName); + + await ctx.Response.SendFileAsync(fi); + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Proxy/Middlewares/BaseMiddleware.cs b/PrivateCloudMusic/Proxy/Middlewares/BaseMiddleware.cs new file mode 100644 index 0000000..bad750d --- /dev/null +++ b/PrivateCloudMusic/Proxy/Middlewares/BaseMiddleware.cs @@ -0,0 +1,7 @@ +namespace Pcm.Proxy.Middlewares +{ + public abstract class BaseMiddleware + { + public abstract Endpoint Create(Endpoint func); + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Proxy/Middlewares/Logging.cs b/PrivateCloudMusic/Proxy/Middlewares/Logging.cs new file mode 100644 index 0000000..a96e60f --- /dev/null +++ b/PrivateCloudMusic/Proxy/Middlewares/Logging.cs @@ -0,0 +1,50 @@ +using System; +using Google.Protobuf; +using Microsoft.Extensions.Logging; +using Pcm.Proto; + +namespace Pcm.Proxy.Middlewares +{ + public class Logging : BaseMiddleware + { + public static readonly string K_LOGID = "logid"; + + public override Endpoint Create(Endpoint func) + { + return async (ctx, req, resp) => + { + var logid = Guid.NewGuid(); + ctx.Items.Add(K_LOGID, logid); + resp.LogId = logid.ToString(); + + Exception err = null; + var code = StatusCode.Ok; + + try + { + code = await func(ctx, req, resp); + } + catch (Exception ex) + { + err = ex; + } + + + + var jsonReq = JsonFormatter.Default.Format(req); + var jsonResp = JsonFormatter.Default.Format(resp); + + if (err != null) + { + ctx.Logger.LogError("err={0}, req={1}, resp={2}", jsonReq, jsonResp); + } + else + { + ctx.Logger.LogInformation("req={0}, resp={1}", jsonReq, jsonResp); + } + + return code; + }; + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Proxy/Middlewares/Preset.cs b/PrivateCloudMusic/Proxy/Middlewares/Preset.cs new file mode 100644 index 0000000..2f41f4d --- /dev/null +++ b/PrivateCloudMusic/Proxy/Middlewares/Preset.cs @@ -0,0 +1,46 @@ +using System; +using Pcm.Proto; + +namespace Pcm.Proxy.Middlewares +{ + public class Preset : BaseMiddleware + { + public override Endpoint Create(Endpoint func) + { + return async (ctx, req, resp) => + { + resp.Cmd = req.Cmd; + resp.SequenceId = req.SequenceId; + resp.Body = new ResponseBody(); + + var code = StatusCode.Ok; + + try + { + code = await func(ctx, req, resp); + } + catch (Exception ex) + { + resp.StatusCode = (int) code; + resp.ErrorDesc = ex.Message; + throw; + } + + resp.StatusCode = (int)code; + resp.ErrorDesc = "OK"; + + if (ctx.WebSocket == null) + { + ctx.HttpContext.Response.ContentType = ctx.PayloadType switch + { + PayloadType.Json => "application/json", + PayloadType.Protobuf => "application/x-protobuf", + _ => ctx.HttpContext.Response.ContentType + }; + } + + return code; + }; + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Proxy/Parser.cs b/PrivateCloudMusic/Proxy/Parser.cs new file mode 100644 index 0000000..00a53bb --- /dev/null +++ b/PrivateCloudMusic/Proxy/Parser.cs @@ -0,0 +1,76 @@ +using System; +using System.Text; +using Google.Protobuf; +using Pcm.Proto; + +namespace Pcm.Proxy +{ + public enum PayloadType + { + Unknown, + Protobuf, + Json + } + + public abstract class Parser + { + public abstract (Request, PayloadType) From(byte[] data, Encoding encoding = null); + public abstract byte[] To(Response resp, Encoding encoding = null); + } + + public class JsonParser : Parser + { + public override (Request, PayloadType) From(byte[] data, Encoding encoding = null) + { + if (encoding == null) + { + throw new NotImplementedException(); + } + + try + { + var str = encoding.GetString(data); + var req = Request.Parser.ParseJson(str); + return (req, PayloadType.Json); + } + catch + { + return (null, PayloadType.Unknown); + } + } + + public override byte[] To(Response resp, Encoding encoding = null) + { + if (encoding == null) + { + throw new NotImplementedException(); + } + + var str = JsonFormatter.Default.Format(resp); + var bytes = encoding.GetBytes(str); + return bytes; + } + } + + public class ProtobufParser : Parser + { + public override (Request, PayloadType) From(byte[] data, Encoding encoding = null) + { + try + { + var resp = Request.Parser.ParseFrom(data); + return (resp, PayloadType.Protobuf); + } + catch + { + return (null, PayloadType.Unknown); + } + } + + public override byte[] To(Response resp, Encoding encoding = null) + { + var data = resp.ToByteArray(); + return data; + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Proxy/Router.cs b/PrivateCloudMusic/Proxy/Router.cs new file mode 100644 index 0000000..0dc4e7b --- /dev/null +++ b/PrivateCloudMusic/Proxy/Router.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using Pcm.Handlers; +using Pcm.Proto; + +namespace Pcm.Proxy +{ + public class Router + { + private Dictionary _mapping = new Dictionary(); + + public Router() + { + initRouter(); + } + + private void initRouter() + { + var defaultHandler = new DefaultHandler(); + var music = new MusicHandler(); + var album = new AlbumHandler(); + var playlist = new PlaylistHandler(); + + register(CMD.NotUsed, defaultHandler.Default); // 0 + register(CMD.GetMusic, music.Get); // 100 + + register(CMD.GetPlaylist, playlist.Get); // 200 + register(CMD.GetAlbum, album.Get); // 201 + + register(CMD.ListPlaylist, playlist.List); // 301 + register(CMD.ListAlbum, album.List); // 302 + + register(CMD.ActionCreatePlaylist, playlist.Create); // 404 + register(CMD.ActionRenamePlaylist, playlist.Rename); // 405 + register(CMD.ActionAddMusicToPlaylist, playlist.Add); // 406 + register(CMD.ActionRemoveMusicFromPlaylist, playlist.Remove); // 407 + register(CMD.ActionDeletePlaylist, playlist.Delete); // 408 + } + + private void register(CMD code, Endpoint handler) + { + _mapping.Add((int)code, handler); + } + + public Endpoint Process(Context ctx, Request req, Response resp) + { + return _mapping.ContainsKey(req.Cmd) ? _mapping[req.Cmd] : new DefaultHandler().Default; + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Services/MusicService.cs b/PrivateCloudMusic/Services/MusicService.cs new file mode 100644 index 0000000..9021efb --- /dev/null +++ b/PrivateCloudMusic/Services/MusicService.cs @@ -0,0 +1,95 @@ +using System; +using System.IO; +using LiteDB; +using Pcm.Entities; +using Pcm.Utils; + +namespace Pcm.Services +{ + public class MusicService + { + static readonly Lazy lazy = new Lazy(() => new MusicService()); + public static MusicService Instance => lazy.Value; + + private FileSystemWatcher fsw; + + private MusicService() + { + Collection = DbManager.DB.GetCollection("music"); + var musicPath = ConfigManager.Get("musicPath", "music"); + + var dir = Directory.Exists(musicPath) ? new DirectoryInfo(musicPath) : Directory.CreateDirectory(musicPath); + + fsw = new FileSystemWatcher() + { + Path = dir.FullName, + IncludeSubdirectories = true + }; + fsw.Created += FswOnCreated; + fsw.Changed += FswOnChanged; + fsw.Deleted += FswOnDeleted; + } + + private void FswOnDeleted(object sender, FileSystemEventArgs e) + { + throw new NotImplementedException(); + } + + private void FswOnChanged(object sender, FileSystemEventArgs e) + { + throw new NotImplementedException(); + } + + private void FswOnCreated(object sender, FileSystemEventArgs e) + { + throw new NotImplementedException(); + } + + public LiteCollection Collection { get; protected set; } + + public bool EnableWatcher + { + get => fsw.EnableRaisingEvents; + set => fsw.EnableRaisingEvents = value; + } + + public Music Get(string id) + { + var oid = new ObjectId(id); + return Collection.FindById(oid); + } + + public Music Add(string filePath) + { + var exist = Collection.FindOne(t => t.FilePath == filePath); + if (exist != null) + { + return exist; + } + + var tfile = TagLib.File.Create(filePath); + + var id = ObjectId.NewObjectId(); + + var music = new Music + { + MusicId = id, + Title = tfile.Tag.Title, + Album = tfile.Tag.Album, + Genres = tfile.Tag.Genres, + Performers = tfile.Tag.Performers, + Track = tfile.Tag.Track, + TrackCount = tfile.Tag.TrackCount, + Length = (int)tfile.Properties.Duration.TotalSeconds, + MimeType = tfile.MimeType, + FilePath = filePath, + PlayCount = 0, + }; + + var bsonId = Collection.Insert(music); + + return Get(id.ToString()); + } + + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Startup.cs b/PrivateCloudMusic/Startup.cs new file mode 100644 index 0000000..54c474a --- /dev/null +++ b/PrivateCloudMusic/Startup.cs @@ -0,0 +1,65 @@ +using System; +using Anemonis.AspNetCore.RequestDecompression; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Pcm.Proxy; + +namespace Pcm +{ + public class Startup + { + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) + { + services.AddRequestDecompression(o => + { + o.Providers.Add(); + o.Providers.Add(); + o.Providers.Add(); + }); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + var handler = new MessageHandler(); + + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + app.UseWebSockets(); + + app.UseEndpoints(endpoints => + { + endpoints.MapPost("/http", async context => await handler.HandleHttp(context)); + endpoints.MapGet("/music/{id}", async context => await handler.HandleMusic(context)); + }); + + app.Use(async (context, next) => + { + if (context.Request.Path == "/ws") + { + if (context.WebSockets.IsWebSocketRequest) + { + var webSocket = await context.WebSockets.AcceptWebSocketAsync(); + await handler.HandleWs(context, webSocket); + } + else + { + context.Response.StatusCode = 400; + } + } + else + { + await next(); + } + }); + } + } +} diff --git a/PrivateCloudMusic/Utils/ConfigManager.cs b/PrivateCloudMusic/Utils/ConfigManager.cs new file mode 100644 index 0000000..2df52c2 --- /dev/null +++ b/PrivateCloudMusic/Utils/ConfigManager.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.Configuration; + +namespace Pcm.Utils +{ + public class ConfigManager + { + public static IConfiguration Config; + + public static string Get(string key, string defaultVal = "") + { + return Config[key] ?? defaultVal; + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Utils/DbManager.cs b/PrivateCloudMusic/Utils/DbManager.cs new file mode 100644 index 0000000..e314341 --- /dev/null +++ b/PrivateCloudMusic/Utils/DbManager.cs @@ -0,0 +1,16 @@ +using LiteDB; + +namespace Pcm.Utils +{ + public class DbManager + { + public readonly static LiteDatabase DB; + + static DbManager() + { + var dbfile = ConfigManager.Get("dbFile", "db.litedb"); + + DB = new LiteDatabase(dbfile); + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/Utils/LogManager.cs b/PrivateCloudMusic/Utils/LogManager.cs new file mode 100644 index 0000000..fa8413e --- /dev/null +++ b/PrivateCloudMusic/Utils/LogManager.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.Extensions.Logging; + +namespace Pcm.Utils +{ + public static class LogManager + { + private static readonly ILoggerFactory _loggerFactory = LoggerFactory.Create(builder => + { + builder.AddConsole() + .AddDebug(); + }); + + public static ILogger CreateLogger() + { + return _loggerFactory.CreateLogger(); + } + + public static ILogger CreateLogger(Type type) + { + return _loggerFactory.CreateLogger(type); + } + + public static ILogger CreateLogger(string msg) + { + return _loggerFactory.CreateLogger(typeof(T).FullName + msg); + } + } +} \ No newline at end of file diff --git a/PrivateCloudMusic/appsettings.Development.json b/PrivateCloudMusic/appsettings.Development.json new file mode 100644 index 0000000..a2880cb --- /dev/null +++ b/PrivateCloudMusic/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/PrivateCloudMusic/appsettings.json b/PrivateCloudMusic/appsettings.json new file mode 100644 index 0000000..81ff877 --- /dev/null +++ b/PrivateCloudMusic/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +}