Program2.cs 31 KB

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