Program2.cs 30 KB

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