Program2.cs 39 KB

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