Program2.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. using FNZCM.Core;
  2. using Microsoft.VisualBasic.FileIO;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using SearchOption = Microsoft.VisualBasic.FileIO.SearchOption;
  13. namespace FNZCM.ConHost.Ver2
  14. {
  15. internal static class Program2
  16. {
  17. //0. start http server
  18. //1. scan libraries and fill data struct
  19. // libs
  20. // disc
  21. // Tracks(FLAC / AAC_*)
  22. // Meta(title(artist) / duration)
  23. // FSI ( size )
  24. // TODO: Generate thumbnail of BKS
  25. private static readonly ConcurrentDictionary<string, Library2> Libraries = new();
  26. private static readonly ConcurrentDictionary<string, string> PathMapping = new();
  27. private static readonly ConcurrentDictionary<string, MediaTag2> MediaTags = new();
  28. private static bool _isRunning;
  29. private static bool _isLoading;
  30. private static DateTime _lastRequestAccepted;
  31. private static void Main()
  32. {
  33. Console.WriteLine("Starting...");
  34. var tWorker = new Thread(Working);
  35. _isRunning = true;
  36. tWorker.Start();
  37. Task.Run(ScanLibrary);
  38. Console.WriteLine("Press ENTER to Stop.");
  39. Console.ReadLine();
  40. Console.WriteLine("Shutting down...");
  41. _isRunning = false;
  42. tWorker.Join();
  43. Console.WriteLine("Stopped.");
  44. Console.WriteLine();
  45. Console.Write("Press ENTER to Exit.");
  46. Console.ReadLine();
  47. }
  48. private static void ScanLibrary()
  49. {
  50. if (_isLoading)
  51. {
  52. Console.WriteLine("Still scanning, SKIP");
  53. return;
  54. }
  55. _isLoading = true;
  56. try
  57. {
  58. ConfigFile.Reload();
  59. Console.WriteLine("Scanning libraries...");
  60. MediaTags.Clear();
  61. PathMapping.Clear();
  62. Libraries.Clear();
  63. foreach (var kvpLib in ConfigFile.Instance.Libraries)
  64. {
  65. if (_isRunning == false) throw new OperationCanceledException();
  66. Console.WriteLine($"Library {kvpLib.Key} - {kvpLib.Value}");
  67. var libPath = kvpLib.Key.ToLower();
  68. var lib = Libraries[libPath] = new Library2(kvpLib.Key);
  69. var discDirArray = Directory.GetDirectories(kvpLib.Value);
  70. foreach (var discDir in discDirArray)
  71. {
  72. if (_isRunning == false) throw new OperationCanceledException();
  73. Console.WriteLine($" Disc {discDir}");
  74. var discName = Path.GetFileName(discDir);
  75. var discPath = discName.ToLower();
  76. try
  77. {
  78. var disc = new Disc(discName);
  79. var bkDir = Path.Combine(discDir, "bk");
  80. var mainTrackFiles = FileSystem.GetFiles(discDir, SearchOption.SearchTopLevelOnly, ConfigFile.Instance.MediaFilePattern);
  81. foreach (var mainTrackFile in mainTrackFiles)
  82. {
  83. var trackName = Path.GetFileName(mainTrackFile);
  84. var trackPath = trackName.ToLower();
  85. disc.MainTracks[trackPath] = trackName;
  86. PathMapping[$"/media/{libPath}/{discPath}/{trackPath}"] = mainTrackFile;
  87. }
  88. if (Directory.Exists(bkDir))
  89. {
  90. var bkFiles = FileSystem.GetFiles(bkDir, SearchOption.SearchTopLevelOnly, ConfigFile.Instance.BkFilePattern);
  91. foreach (var file in bkFiles)
  92. {
  93. var bkName = Path.GetFileName(file);
  94. var bkPath = bkName.ToLower();
  95. disc.Bks[bkPath] = bkName;
  96. PathMapping[$"/bk/{libPath}/{discPath}/{bkPath}"] = file;
  97. }
  98. }
  99. var aacTrackDirArray = Directory.GetDirectories(discDir, "AAC_Q*");
  100. foreach (var aacTrackDir in aacTrackDirArray)
  101. {
  102. var aacTrackSetName = Path.GetFileName(aacTrackDir);
  103. var aacTrackSetPath = aacTrackSetName.ToLower();
  104. var aacTrackSet = disc.SubTracks[aacTrackSetPath] = new TrackSet(aacTrackSetName);
  105. foreach (var file in Directory.GetFiles(aacTrackDir, "*.m4a"))
  106. {
  107. var aacTrackName = Path.GetFileName(file);
  108. var aacTrackPath = aacTrackName.ToLower();
  109. aacTrackSet.Tracks[aacTrackPath] = aacTrackName;
  110. PathMapping[$"/media/{libPath}/{discPath}/{aacTrackSetPath}/{aacTrackPath}"] = file;
  111. }
  112. }
  113. var coverFilePath = Path.Combine(discDir, "cover.jpg");
  114. if (File.Exists(coverFilePath)) PathMapping[$"/cover/{libPath}/{discPath}/cover.jpg"] = coverFilePath;
  115. lib.Discs[discPath] = disc;
  116. }
  117. catch (Exception ex)
  118. {
  119. Console.WriteLine(ex);
  120. }
  121. }
  122. }
  123. Console.WriteLine("Looking tags...");
  124. Parallel.ForEach(PathMapping.Keys.Where(p => p.StartsWith("/media/")), k => GetTag(k));
  125. Console.WriteLine("Looking tags...Done");
  126. }
  127. catch (Exception e)
  128. {
  129. Console.WriteLine($"Load error: {e}");
  130. }
  131. _isLoading = false;
  132. }
  133. private static void Working()
  134. {
  135. var listener = new HttpListener();
  136. listener.Prefixes.Add(ConfigFile.Instance.ListenPrefix);
  137. listener.Start();
  138. var upTime = DateTime.Now;
  139. Console.WriteLine($"HTTP Server started, listening on {ConfigFile.Instance.ListenPrefix}");
  140. listener.BeginGetContext(ContextGet, listener);
  141. _lastRequestAccepted = DateTime.Now;
  142. while (_isRunning)
  143. {
  144. var timeSpan = DateTime.Now - _lastRequestAccepted;
  145. var up = DateTime.Now - upTime;
  146. Console.Title =
  147. "FNZCM"
  148. + $" UP {up.Days:00}D {up.Hours:00}H {up.Minutes:00}M {up.Seconds:00}S {up.Milliseconds:000}"
  149. + $" / "
  150. + $" LA {timeSpan.Days:00}D {timeSpan.Hours:00}H {timeSpan.Minutes:00}M {timeSpan.Seconds:00}S {timeSpan.Milliseconds:000}"
  151. ;
  152. Thread.Sleep(1000);
  153. }
  154. listener.Close();
  155. Thread.Sleep(1000);
  156. }
  157. private static void ContextGet(IAsyncResult ar)
  158. {
  159. var listener = (HttpListener)ar.AsyncState;
  160. HttpListenerContext context;
  161. try
  162. {
  163. // ReSharper disable once PossibleNullReferenceException
  164. context = listener.EndGetContext(ar);
  165. }
  166. catch (Exception e)
  167. {
  168. Console.WriteLine(e);
  169. return;
  170. }
  171. if (_isRunning) listener.BeginGetContext(ContextGet, listener);
  172. ProcessRequest(context);
  173. }
  174. private static void ProcessRequest(HttpListenerContext context)
  175. {
  176. _lastRequestAccepted = DateTime.Now;
  177. var request = context.Request;
  178. Console.WriteLine($"Request from {request.RemoteEndPoint} {request.HttpMethod} {request.RawUrl}");
  179. // GET / show all libraries
  180. // foo=library bar=disc
  181. // GET /list/foo/ show all disc and cover with name, provide m3u path
  182. // GET /list/foo/bar/bk/ list all picture as grid
  183. // GET /list/foo/bar/tracks/ list all tracks as text list
  184. // GET /lib_list/foo/playlist.m3u8 auto gen
  185. // GET /lib_list/foo/aac_q1.00/playlist.m3u8 auto gen
  186. // GET /list/foo/bar/playlist.m3u8 auto gen
  187. // GET /list/foo/bar/aac_q1.00/playlist.m3u8 auto gen
  188. // media streaming HTTP Partial RANGE SUPPORT
  189. // GET /cover/foo/bar/cover.jpg image/<ext>
  190. // GET /media/foo/bar/01.%20foobar.flac audio/<ext>
  191. // GET /media/foo/bar/aac_q1.00/01.%20foobar.m4a audio/<ext>
  192. // GET /bk/foo/bar/foobar.jpg image/<ext>
  193. try
  194. {
  195. // ReSharper disable once PossibleNullReferenceException
  196. var requestPath = request.Url.LocalPath.ToLower();
  197. var pathParts = (IReadOnlyList<string>)requestPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  198. if (requestPath == "/admin/" && false == request.QueryString.AllKeys.Contains("action"))
  199. {
  200. var sb = new StringBuilder();
  201. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  202. sb.Append($"<title> Libraries - {ConfigFile.Instance.Title} </title>");
  203. sb.Append("<body bgColor=skyBlue>");
  204. sb.Append($"<h3>Admin</h3>");
  205. sb.Append("<div><a href=/>Back to home</a></div>");
  206. sb.Append($"<form method=GET>");
  207. sb.Append($"Password: <input type=password name=pass />");
  208. sb.Append($"<br/>");
  209. sb.Append($"Operation: <input type=submit name=action value=Scan />");
  210. sb.Append($"</form>");
  211. context.Response.WriteText(sb.ToString());
  212. }
  213. else if (requestPath == "/admin/" && request.QueryString["action"] == "Scan" && request.QueryString["pass"] == ConfigFile.Instance.AdminPassword)
  214. {
  215. Task.Run(ScanLibrary);
  216. context.Response.Redirect("/");
  217. }
  218. else if (requestPath == "/admin/")
  219. {
  220. context.Response.Redirect("/");
  221. }
  222. else if (requestPath == "/")
  223. {
  224. var sb = new StringBuilder();
  225. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  226. sb.Append($"<title> Libraries - {ConfigFile.Instance.Title} </title>");
  227. sb.Append("<body bgColor=skyBlue style=font-size:3vh>");
  228. if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
  229. sb.Append($"<h2>{ConfigFile.Instance.Title}</h2>");
  230. sb.Append($"<h3>Libraries</h3>");
  231. sb.Append($"<h4>(Total number of disc: {Libraries.Sum(p => p.Value.Discs.Count)})</h4>");
  232. sb.Append("<ul>");
  233. foreach (var library in Libraries.OrderBy(p => p.Key))
  234. {
  235. sb.Append("<li>");
  236. sb.Append($"<a href='/list/{library.Key.FuckVlcAndEscape()}/'>{library.Value.Name}</a>");
  237. sb.Append($"<br/>&nbsp;&nbsp;&nbsp; Number of disc: {library.Value.Discs.Count}");
  238. sb.Append("</li>");
  239. }
  240. sb.Append("</ul>");
  241. sb.Append($"<hr/>");
  242. sb.Append($"<div>Your IP: {context?.Request?.RemoteEndPoint?.Address.ToString() ?? "Unknown"}</div>");
  243. sb.Append($"<div><a href=/admin/>Admin</a></div>");
  244. sb.Append($"<div>-</div>");
  245. sb.Append($"<div>Author: Coder (V)</div>");
  246. sb.Append($"<div>Blog: <a target=_blank href=https://topcl.net/myapps/private-colud-music.html>https://topcl.net/myapps/private-colud-music.html</a></div>");
  247. sb.Append($"<div>Source Repo: <a target=_blank href=https://topcl.net/gogs/coder/CloudMusic/>https://topcl.net/gogs/coder/CloudMusic/</a></div>");
  248. context.Response.WriteText(sb.ToString());
  249. }
  250. else if (pathParts.Count == 2 && pathParts[0] == "list")
  251. {
  252. var libName = pathParts[1];
  253. if (Libraries.TryGetValue(libName, out var lib))
  254. {
  255. var sb = new StringBuilder();
  256. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  257. sb.Append($"<title> Discs of {lib.Name} - {ConfigFile.Instance.Title} </title>");
  258. sb.Append(
  259. "<style>" +
  260. "a:link{ text-decoration: none; }" +
  261. "div.item{" +
  262. " vertical-align:top;" +
  263. " margin-bottom:1vh;" +
  264. " padding:0.5vh;" +
  265. " border:solid 1px;" +
  266. " border-radius:0.5vh;" +
  267. " font-size:2.2vh;" +
  268. "}" +
  269. "div.item::-webkit-scrollbar{" +
  270. " display: none;" +
  271. "}" +
  272. "img.cover{" +
  273. " float:left;" +
  274. " width:45vw;" +
  275. "}" +
  276. "div.disc_name{" +
  277. "}" +
  278. "div.links{" +
  279. " clear:both;" +
  280. "}" +
  281. "a.button{" +
  282. " margin-left:4vw;" +
  283. "}" +
  284. "</style>");
  285. sb.Append($"<body bgColor=skyBlue>");
  286. if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
  287. sb.Append($"<h1>Discs of {lib.Name}</h1>");
  288. sb.Append("<div><a href=/>Back to home</a></div>");
  289. if (!_isLoading)
  290. {
  291. sb.Append("<div style=margin-top:1vh;margin-bottom:1vh;>");
  292. //big m3u8
  293. var trackKeys = lib.Discs.SelectMany(p => p.Value.MainTracks.Keys.Select(q => new { DiscName = p.Key, TrackName = q })).ToArray();
  294. var totalDur = trackKeys.Sum(p => GetTag($"/media/{libName}/{p.DiscName}/{p.TrackName}", true)?.Duration ?? 0);
  295. var totalLen = trackKeys.Sum(p => GetTag($"/media/{libName}/{p.DiscName}/{p.TrackName}", true)?.Length ?? 0);
  296. sb.Append($"Number of track: {trackKeys.Length}");
  297. sb.Append($"<br/>{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/lib_list/{libName}/playlist.m3u8\">ALL_M3U8_MAIN</a>");
  298. var subTrackSetNames = lib.Discs.SelectMany(p => p.Value.SubTracks.Keys).Distinct().ToArray();
  299. foreach (var setName in subTrackSetNames)
  300. {
  301. trackKeys = lib.Discs.SelectMany(p =>
  302. {
  303. if (p.Value.SubTracks.TryGetValue(setName, out var tSet))
  304. {
  305. return tSet.Tracks.Select(q => new { DiscName = p.Key, TrackName = q.Key });
  306. }
  307. return new string[0].Select(q => new { DiscName = p.Key, TrackName = q });
  308. }).ToArray();
  309. totalDur = trackKeys.Sum(p => GetTag($"/media/{libName}/{p.DiscName}/{setName}/{p.TrackName}", true)?.Duration ?? 0);
  310. totalLen = trackKeys.Sum(p => GetTag($"/media/{libName}/{p.DiscName}/{setName}/{p.TrackName}", true)?.Length ?? 0);
  311. sb.Append($"<br/>{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/lib_list/{libName}/{setName}/playlist.m3u8\">ALL_M3U8_{setName.ToUpper()}</a>");
  312. }
  313. sb.Append("</div>");
  314. }
  315. //Cover list
  316. foreach (var disc in lib.Discs.OrderByDescending(p => p.Key))
  317. {
  318. sb.Append("<div class=item>");
  319. sb.Append($"<div>");
  320. sb.Append($"<img class=cover src=\"/cover/{libName}/{disc.Key}/cover.jpg\" />");
  321. sb.Append($"<div class=disc_name>{disc.Value.Name}</div>");
  322. sb.Append($"</div>");
  323. sb.Append("<div class=links>");
  324. sb.Append("<div>");
  325. sb.Append($"Number of track: {disc.Value.MainTracks.Count} <a href=\"/list/{libName}/{disc.Key}/tracks/\">[TRACKERS]</a>");
  326. if (disc.Value.Bks?.Count > 0) sb.Append($"<a class=button href=\"/list/{libName}/{disc.Key}/bk/\">[BK]</a>");
  327. sb.Append("</div>");
  328. var totalDur = disc.Value.MainTracks.Sum(p => GetTag($"/media/{libName}/{disc.Key}/{p.Key}", true)?.Duration ?? 0);
  329. var totalLen = disc.Value.MainTracks.Sum(p => GetTag($"/media/{libName}/{disc.Key}/{p.Key}", true)?.Length ?? 0);
  330. sb.Append($"{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/list/{libName}/{disc.Key.FuckVlcAndEscape()}/playlist.m3u8\">M3U8_MAIN</a>");
  331. if (disc.Value.SubTracks.Count > 0)
  332. {
  333. foreach (var subTrack in disc.Value.SubTracks)
  334. {
  335. totalDur = subTrack.Value.Tracks.Sum(p => GetTag($"/media/{libName}/{disc.Key}/{subTrack.Key}/{p.Key}", true)?.Duration ?? 0);
  336. totalLen = subTrack.Value.Tracks.Sum(p => GetTag($"/media/{libName}/{disc.Key}/{subTrack.Key}/{p.Key}", true)?.Length ?? 0);
  337. sb.Append($"<br/>{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/list/{libName}/{disc.Key.FuckVlcAndEscape()}/{subTrack.Key.FuckVlcAndEscape()}/playlist.m3u8\">{subTrack.Value.Name}</a>");
  338. }
  339. }
  340. sb.Append("</div>");
  341. sb.Append("</div>");
  342. }
  343. context.Response.ContentType = "text/html";
  344. context.Response.ContentEncoding = Encoding.UTF8;
  345. context.Response.WriteText(sb.ToString());
  346. }
  347. else
  348. {
  349. context.Response.StatusCode = 404;
  350. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  351. }
  352. }
  353. else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "tracks")
  354. {
  355. var libName = pathParts[1];
  356. var discPath = pathParts[2];
  357. if (Libraries.TryGetValue(libName, out var l) && l.Discs.TryGetValue(discPath, out var disc))
  358. {
  359. var sb = new StringBuilder();
  360. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  361. sb.Append($"<body bgColor=skyBlue style=font-size:2vh>");
  362. if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
  363. sb.Append($"<h2>Tracks of</h2><h1>{disc.Name}</h1>");
  364. sb.Append($"<div><a href='/list/{libName.FuckVlcAndEscape()}/'>Back to library</a></div>");
  365. sb.Append($"<img style=float:left;max-width:50vw src=\"/cover/{libName}/{discPath}/cover.jpg\" />");
  366. var durTotal = 0;
  367. var sizeTotal = 0L;
  368. var sbm = new StringBuilder();
  369. foreach (var kvpTrack in disc.MainTracks.OrderBy(p => p.Key))
  370. {
  371. sbm.Append($"<li>");
  372. sbm.Append($"<a href=\"/media/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/{kvpTrack.Key.FuckVlcAndEscape()}\" >{kvpTrack.Value}</a>");
  373. var tag = GetTag($"/media/{libName}/{discPath}/{kvpTrack.Key}");
  374. durTotal += tag.Duration;
  375. sizeTotal += tag.Length;
  376. sbm.Append($"<br> &nbsp; &nbsp; &nbsp; {tag.Duration.FormatDuration()} {tag.Length.FormatFileSize()}");
  377. sbm.Append($"</li>");
  378. }
  379. sb.Append($"<h2>Main ({durTotal.FormatDuration()}) {sizeTotal.FormatFileSize()}</h2>");
  380. sb.Append(sbm);
  381. foreach (var kvpSubSet in disc.SubTracks.OrderBy(p => p.Key))
  382. {
  383. durTotal = 0;
  384. sizeTotal = 0L;
  385. sbm.Clear();
  386. foreach (var kvpTrack in kvpSubSet.Value.Tracks.OrderBy(p => p.Key))
  387. {
  388. sbm.Append($"<li>");
  389. sbm.Append($"<a href=\"/media/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/{kvpSubSet.Key.FuckVlcAndEscape()}/{kvpTrack.Key.FuckVlcAndEscape()}\" >{kvpTrack.Value}</a>");
  390. var tag = GetTag($"/media/{libName}/{discPath}/{kvpSubSet.Key}/{kvpTrack.Key}");
  391. durTotal += tag.Duration;
  392. sizeTotal += tag.Length;
  393. sbm.Append($"<br/> &nbsp; &nbsp; &nbsp; {tag.Duration.FormatDuration()} {tag.Length.FormatFileSize()}");
  394. sbm.Append($"</li>");
  395. }
  396. sb.Append($"<h2>{kvpSubSet.Value.Name} ({durTotal.FormatDuration()}) {sizeTotal.FormatFileSize()}</h2>");
  397. sb.Append(sbm);
  398. }
  399. context.Response.ContentType = "text/html";
  400. context.Response.ContentEncoding = Encoding.UTF8;
  401. context.Response.WriteText(sb.ToString());
  402. }
  403. else
  404. {
  405. context.Response.StatusCode = 404;
  406. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  407. }
  408. }
  409. else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "bk")
  410. {
  411. var libName = pathParts[1];
  412. var discPath = pathParts[2];
  413. if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(discPath, out var disc))
  414. {
  415. var sb = new StringBuilder();
  416. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  417. sb.Append($"<body bgColor=skyBlue style=font-size:2vh>");
  418. if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
  419. sb.Append($"<h2>BK of </h2><h1>{disc.Name}</h1>");
  420. sb.Append($"<div><a href='/list/{libName.FuckVlcAndEscape()}/'>Back to library</a></div>");
  421. foreach (var discBk in disc.Bks.OrderBy(p => p.Key))
  422. {
  423. //TODO: auto gen thumbnail 512x512 jpg 80
  424. sb.Append($"<img src='/bk/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/{discBk.Key.FuckVlcAndEscape()}' style=max-width:24vw;max-height:24vw;margin-right:1vw;margin-bottom:1vh; />");
  425. }
  426. context.Response.ContentType = "text/html";
  427. context.Response.ContentEncoding = Encoding.UTF8;
  428. context.Response.WriteText(sb.ToString());
  429. }
  430. else
  431. {
  432. context.Response.StatusCode = 404;
  433. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  434. }
  435. }
  436. else if (pathParts.Count == 3 && pathParts[0] == "lib_list" && pathParts[2] == "playlist.m3u8")
  437. {
  438. var libName = pathParts[1];
  439. if (Libraries.TryGetValue(libName, out var lib))
  440. {
  441. var sb = new StringBuilder();
  442. sb.AppendLine("#EXTM3U");
  443. var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
  444. foreach (var discKvp in lib.Discs.OrderByDescending(p => p.Key))
  445. {
  446. var disc = discKvp.Value;
  447. var discPath = discKvp.Key;
  448. var tracks = disc.MainTracks;
  449. foreach (var track in tracks.OrderBy(p => p.Key))
  450. {
  451. var mediaTag = GetTag($"/media/{libName}/{discPath}/{track.Key}");
  452. if (mediaTag != null)
  453. {
  454. var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/cover.jpg";
  455. sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
  456. }
  457. var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
  458. sb.AppendLine(prefix + mediaPath);
  459. }
  460. }
  461. context.Response.ContentType = "audio/mpegurl";
  462. context.Response.ContentEncoding = Encoding.UTF8;
  463. context.Response.WriteText(sb.ToString());
  464. }
  465. else
  466. {
  467. context.Response.StatusCode = 404;
  468. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  469. }
  470. }
  471. else if (pathParts.Count == 4 && pathParts[0] == "lib_list" && pathParts[3] == "playlist.m3u8")
  472. {
  473. var libName = pathParts[1];
  474. var trackSetName = pathParts[2];
  475. if (Libraries.TryGetValue(libName, out var lib))
  476. {
  477. var sb = new StringBuilder();
  478. sb.AppendLine("#EXTM3U");
  479. var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
  480. foreach (var discKvp in lib.Discs.OrderByDescending(p => p.Key))
  481. {
  482. var disc = discKvp.Value;
  483. var discPath = discKvp.Key;
  484. if (disc.SubTracks.TryGetValue(trackSetName, out var tracksSet))
  485. {
  486. var tracks = tracksSet.Tracks;
  487. foreach (var track in tracks.OrderBy(p => p.Key))
  488. {
  489. var mediaTag = GetTag($"/media/{libName}/{discPath}/{trackSetName}/{track.Key}");
  490. if (mediaTag != null)
  491. {
  492. var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/cover.jpg";
  493. sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
  494. }
  495. var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
  496. sb.AppendLine(prefix + mediaPath);
  497. }
  498. }
  499. }
  500. context.Response.ContentType = "audio/mpegurl";
  501. context.Response.ContentEncoding = Encoding.UTF8;
  502. context.Response.WriteText(sb.ToString());
  503. }
  504. else
  505. {
  506. context.Response.StatusCode = 404;
  507. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  508. }
  509. }
  510. else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "playlist.m3u8")
  511. {
  512. var libName = pathParts[1];
  513. var discPath = pathParts[2];
  514. if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(discPath, out var disc))
  515. {
  516. // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
  517. var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
  518. var sb = new StringBuilder();
  519. sb.AppendLine("#EXTM3U");
  520. foreach (var track in disc.MainTracks.OrderBy(p => p.Key))
  521. {
  522. var mediaTag = GetTag($"/media/{libName}/{discPath}/{track.Key}");
  523. if (mediaTag != null)
  524. {
  525. var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/cover.jpg";
  526. sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
  527. }
  528. var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
  529. sb.AppendLine(prefix + mediaPath);
  530. }
  531. context.Response.ContentType = "audio/mpegurl";
  532. context.Response.ContentEncoding = Encoding.UTF8;
  533. context.Response.WriteText(sb.ToString());
  534. }
  535. else
  536. {
  537. context.Response.StatusCode = 404;
  538. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  539. }
  540. }
  541. else if (pathParts.Count == 5 && pathParts[0] == "list" && pathParts[4] == "playlist.m3u8")
  542. {
  543. var libName = pathParts[1];
  544. var discPath = pathParts[2];
  545. var subSetPath = pathParts[3];
  546. if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(discPath, out var disc))
  547. {
  548. // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
  549. var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
  550. if (false == disc.SubTracks.TryGetValue(subSetPath, out var trackSet))
  551. {
  552. context.Response.StatusCode = 404;
  553. }
  554. else
  555. {
  556. var sb = new StringBuilder();
  557. sb.AppendLine("#EXTM3U");
  558. foreach (var track in trackSet.Tracks.OrderBy(p => p.Key))
  559. {
  560. var mediaTag = GetTag($"/media/{libName}/{discPath}/{subSetPath}/{track.Key}");
  561. if (mediaTag != null)
  562. {
  563. var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/cover.jpg";
  564. sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
  565. }
  566. var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{discPath.FuckVlcAndEscape()}/{subSetPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
  567. sb.AppendLine(prefix + mediaPath);
  568. }
  569. context.Response.ContentType = "audio/mpegurl";
  570. context.Response.ContentEncoding = Encoding.UTF8;
  571. context.Response.WriteText(sb.ToString());
  572. }
  573. }
  574. else
  575. {
  576. context.Response.StatusCode = 404;
  577. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  578. }
  579. }
  580. else if (PathMapping.TryGetValue(requestPath, out var realPath))
  581. {
  582. var ext = requestPath.Split('.').LastOrDefault()?.ToLower();
  583. switch (ext)
  584. {
  585. case "flac": context.Response.ContentType = "audio/flac"; break;
  586. case "m4a": context.Response.ContentType = "audio/mp4"; break;
  587. case "mp3": context.Response.ContentType = "audio/mpeg"; break;
  588. case "aac": context.Response.ContentType = "audio/aac"; break;
  589. case "mp4": context.Response.ContentType = "video/mp4"; break;
  590. case "mkv": context.Response.ContentType = $"video/webm"; break;
  591. case "jpg":
  592. case "jpeg": context.Response.ContentType = $"image/jpeg"; break;
  593. case "png": context.Response.ContentType = $"image/png"; break;
  594. case "bmp": context.Response.ContentType = $"image/bmp"; break;
  595. default:
  596. var firstParts = requestPath.Split('/').FirstOrDefault();
  597. switch (firstParts)
  598. {
  599. case "media": context.Response.ContentType = "audio/" + ext; break;
  600. case "bk":
  601. case "cover": context.Response.ContentType = "image/" + ext; break;
  602. }
  603. break;
  604. }
  605. var range = request.Headers.GetValues("Range");
  606. FileStream fs = null;
  607. try
  608. {
  609. fs = File.OpenRead(realPath);
  610. if (range is { Length: > 0 })
  611. {
  612. var rngParts = range[0].Split(new[] { "bytes=", "-" }, StringSplitOptions.RemoveEmptyEntries);
  613. if (rngParts.Length >= 1 && long.TryParse(rngParts[0], out var start))
  614. {
  615. fs.Position = start;
  616. context.Response.StatusCode = 206;
  617. context.Response.Headers.Add("Accept-Ranges", "bytes");
  618. context.Response.Headers.Add("Content-Range", $"bytes {start}-{fs.Length - 1}/{fs.Length}");
  619. context.Response.ContentLength64 = fs.Length - start;
  620. fs.CopyTo(context.Response.OutputStream);
  621. }
  622. }
  623. else
  624. {
  625. context.Response.ContentLength64 = fs.Length;
  626. fs.CopyTo(context.Response.OutputStream);
  627. }
  628. }
  629. catch (Exception e)
  630. {
  631. Console.WriteLine(e);
  632. }
  633. finally
  634. {
  635. fs?.Close();
  636. }
  637. }
  638. else
  639. {
  640. context.Response.StatusCode = 404;
  641. }
  642. }
  643. catch (Exception e)
  644. {
  645. Console.WriteLine(e);
  646. try
  647. {
  648. context.Response.StatusCode = 500;
  649. }
  650. catch (Exception exception)
  651. {
  652. Console.WriteLine(exception);
  653. }
  654. }
  655. finally
  656. {
  657. try
  658. {
  659. context.Response.Close();
  660. }
  661. catch (Exception e)
  662. {
  663. Console.WriteLine(e);
  664. }
  665. }
  666. }
  667. private static string FormatDuration(this int second)
  668. {
  669. var sbd = new StringBuilder();
  670. var ts = TimeSpan.FromSeconds(second);
  671. if (ts.TotalHours > 1) sbd.Append($"{ts.TotalHours:00}:");
  672. sbd.Append($"{ts.Minutes:00}:{ts.Seconds:00}");
  673. return sbd.ToString();
  674. }
  675. private static string FormatFileSize(this long length)
  676. {
  677. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  678. double len = length;
  679. int order = 0;
  680. while (len >= 1024 && order < sizes.Length - 1)
  681. {
  682. order++;
  683. len = len / 1024;
  684. }
  685. // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
  686. // show a single decimal place, and no space.
  687. string result = $"{len:000.00} {sizes[order]}";
  688. return result;
  689. }
  690. private static void WriteText(this HttpListenerResponse response, string content)
  691. {
  692. var bytes = Encoding.UTF8.GetBytes(content);
  693. response.OutputStream.Write(bytes);
  694. }
  695. private static string FuckVlcAndEscape(this string input)
  696. {
  697. if (input == null) return null;
  698. return input
  699. .Replace("[", "%5B")
  700. .Replace("]", "%5D")
  701. .Replace("'", "%27")
  702. ;
  703. }
  704. private static MediaTag2 GetTag(string internalPath, bool peek = false)
  705. {
  706. if (peek)
  707. {
  708. if (MediaTags.TryGetValue(internalPath, out var mediaTag))
  709. {
  710. return mediaTag;
  711. }
  712. return null;
  713. }
  714. else
  715. {
  716. if (false == MediaTags.TryGetValue(internalPath, out var mediaTag) && PathMapping.TryGetValue(internalPath, out var mediaFilePath))
  717. {
  718. try
  719. {
  720. var fi = new FileInfo(mediaFilePath);
  721. using var tagLib = TagLib.File.Create(mediaFilePath);
  722. mediaTag = MediaTags[internalPath] = new MediaTag2(
  723. $"{string.Join(";", tagLib.Tag.Performers)} - {tagLib.Tag.Title}",
  724. (int)tagLib.Properties.Duration.TotalSeconds,
  725. fi.Length
  726. );
  727. }
  728. catch (Exception e)
  729. {
  730. Console.WriteLine($"ERROR on lookup tags: {mediaFilePath}{Environment.NewLine} {e.Message}");
  731. return null;
  732. }
  733. }
  734. return mediaTag;
  735. }
  736. }
  737. }
  738. }