Program2.cs 38 KB

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