Program2.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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))
  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("<ul>");
  198. foreach (var library in Libraries.OrderBy(p => p.Key))
  199. {
  200. sb.Append("<li>");
  201. sb.Append($"<a href='/list/{library.Key.FuckVlcAndEscape()}/'>{library.Value.Name}</a>");
  202. sb.Append($"<br/>&nbsp;&nbsp;&nbsp; Number of disc: {library.Value.Discs.Count}");
  203. sb.Append("</li>");
  204. }
  205. sb.Append("</ul>");
  206. sb.Append("<a href=/scan/>Reload</a>");
  207. context.Response.WriteText(sb.ToString());
  208. }
  209. else if (pathParts.Count == 2 && pathParts[0] == "list")
  210. {
  211. var libName = pathParts[1];
  212. if (Libraries.TryGetValue(libName, out var l))
  213. {
  214. var sb = new StringBuilder();
  215. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  216. sb.Append($"<title> Discs of {l.Name} - {ConfigFile.Instance.Title} </title>");
  217. sb.Append(
  218. "<style>" +
  219. "a:link{ text-decoration: none; }" +
  220. "div.item{" +
  221. " vertical-align:top;" +
  222. " margin-bottom:1vh;" +
  223. " padding:0.5vh;" +
  224. " border:solid 1px;" +
  225. " border-radius:0.5vh;" +
  226. " font-size:2.2vh;" +
  227. "}" +
  228. "div.item::-webkit-scrollbar{" +
  229. " display: none;" +
  230. "}" +
  231. "img.cover{" +
  232. " float:left;" +
  233. " width:50vw;" +
  234. "}" +
  235. "div.disc_name{" +
  236. "}" +
  237. "div.links{" +
  238. " clear:both;" +
  239. "}" +
  240. "a.button{" +
  241. " margin-left:4vw;" +
  242. "}" +
  243. "</style>");
  244. sb.Append($"<body bgColor=skyBlue>");
  245. if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
  246. sb.Append($"<h1>Discs of {l.Name}</h1>");
  247. sb.Append("<div><a href=/>Back to home</a></div>");
  248. //Cover list
  249. foreach (var a in l.Discs.OrderByDescending(p => p.Key))
  250. {
  251. sb.Append("<div class=item>");
  252. sb.Append($"<div>");
  253. sb.Append($"<img class=cover src=\"/cover/{libName}/{a.Key}/cover.jpg\" />");
  254. sb.Append($"<div class=disc_name>{a.Value.Name}</div>");
  255. sb.Append($"</div>");
  256. sb.Append("<div class=links>");
  257. sb.Append("<div>");
  258. sb.Append($"Number of track: {a.Value.MainTracks.Count} <a href=\"/list/{libName}/{a.Key}/tracks/\">[TRACKERS]</a>");
  259. if (a.Value.Bks?.Count > 0) sb.Append($"<a class=button href=\"/list/{libName}/{a.Key}/bk/\">[BK]</a>");
  260. sb.Append("</div>");
  261. var totalDur = a.Value.MainTracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{p.Key}", true)?.Duration ?? 0);
  262. var totalLen = a.Value.MainTracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{p.Key}", true)?.Length ?? 0);
  263. sb.Append($"{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/list/{libName}/{a.Key.FuckVlcAndEscape()}/playlist.m3u8\">M3U8_MAIN</a>");
  264. if (a.Value.SubTracks.Count > 0)
  265. {
  266. foreach (var subTrack in a.Value.SubTracks)
  267. {
  268. totalDur = subTrack.Value.Tracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{subTrack.Key}/{p.Key}", true)?.Duration ?? 0);
  269. totalLen = subTrack.Value.Tracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{subTrack.Key}/{p.Key}", true)?.Length ?? 0);
  270. sb.Append($"<br/>{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/list/{libName}/{a.Key.FuckVlcAndEscape()}/{subTrack.Key.FuckVlcAndEscape()}/playlist.m3u8\">{subTrack.Value.Name}</a>");
  271. }
  272. }
  273. sb.Append("</div>");
  274. sb.Append("</div>");
  275. }
  276. context.Response.ContentType = "text/html";
  277. context.Response.ContentEncoding = Encoding.UTF8;
  278. context.Response.WriteText(sb.ToString());
  279. }
  280. else
  281. {
  282. context.Response.StatusCode = 404;
  283. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  284. }
  285. }
  286. else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "tracks")
  287. {
  288. var libName = pathParts[1];
  289. var albPath = pathParts[2];
  290. if (Libraries.TryGetValue(libName, out var l) && l.Discs.TryGetValue(albPath, out var alb))
  291. {
  292. var sb = new StringBuilder();
  293. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  294. sb.Append($"<body bgColor=skyBlue style=font-size:2vh>");
  295. if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
  296. sb.Append($"<h2>Tracks of</h2><h1>{alb.Name}</h1>");
  297. sb.Append($"<div><a href='/list/{libName.FuckVlcAndEscape()}/'>Back to library</a></div>");
  298. var durTotal = 0;
  299. var sizeTotal = 0L;
  300. var sbm = new StringBuilder();
  301. foreach (var kvpTrack in alb.MainTracks.OrderBy(p => p.Key))
  302. {
  303. sbm.Append($"<li>");
  304. sbm.Append($"<a href=\"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{kvpTrack.Key.FuckVlcAndEscape()}\" >{kvpTrack.Value}</a>");
  305. var tag = GetTag($"/media/{libName}/{albPath}/{kvpTrack.Key}");
  306. durTotal += tag.Duration;
  307. sizeTotal += tag.Length;
  308. sbm.Append($"<br> &nbsp; &nbsp; &nbsp; {tag.Duration.FormatDuration()} {tag.Length.FormatFileSize()}");
  309. sbm.Append($"</li>");
  310. }
  311. sb.Append($"<h2>Main ({durTotal.FormatDuration()}) {sizeTotal.FormatFileSize()}</h2>");
  312. sb.Append(sbm);
  313. foreach (var kvpSubSet in alb.SubTracks.OrderBy(p => p.Key))
  314. {
  315. durTotal = 0;
  316. sizeTotal = 0L;
  317. sbm.Clear();
  318. foreach (var kvpTrack in kvpSubSet.Value.Tracks.OrderBy(p => p.Key))
  319. {
  320. sbm.Append($"<li>");
  321. sbm.Append($"<a href=\"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{kvpSubSet.Key.FuckVlcAndEscape()}/{kvpTrack.Key.FuckVlcAndEscape()}\" >{kvpTrack.Value}</a>");
  322. var tag = GetTag($"/media/{libName}/{albPath}/{kvpSubSet.Key}/{kvpTrack.Key}");
  323. durTotal += tag.Duration;
  324. sizeTotal += tag.Length;
  325. sbm.Append($"<br/> &nbsp; &nbsp; &nbsp; {tag.Duration.FormatDuration()} {tag.Length.FormatFileSize()}");
  326. sbm.Append($"</li>");
  327. }
  328. sb.Append($"<h2>{kvpSubSet.Value.Name} ({durTotal.FormatDuration()}) {sizeTotal.FormatFileSize()}</h2>");
  329. sb.Append(sbm);
  330. }
  331. context.Response.ContentType = "text/html";
  332. context.Response.ContentEncoding = Encoding.UTF8;
  333. context.Response.WriteText(sb.ToString());
  334. }
  335. else
  336. {
  337. context.Response.StatusCode = 404;
  338. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  339. }
  340. }
  341. else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "bk")
  342. {
  343. var libName = pathParts[1];
  344. var albPath = pathParts[2];
  345. if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(albPath, out var alb))
  346. {
  347. var sb = new StringBuilder();
  348. sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
  349. sb.Append($"<body bgColor=skyBlue style=font-size:2vh>");
  350. if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
  351. sb.Append($"<h2>BK of </h2><h1>{alb.Name}</h1>");
  352. sb.Append($"<div><a href='/list/{libName.FuckVlcAndEscape()}/'>Back to library</a></div>");
  353. foreach (var albBk in alb.Bks.OrderBy(p => p.Key))
  354. {
  355. //TODO: auto gen thumbnail 512x512 jpg 80
  356. 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; />");
  357. }
  358. context.Response.ContentType = "text/html";
  359. context.Response.ContentEncoding = Encoding.UTF8;
  360. context.Response.WriteText(sb.ToString());
  361. }
  362. else
  363. {
  364. context.Response.StatusCode = 404;
  365. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  366. }
  367. }
  368. else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "playlist.m3u8")
  369. {
  370. var libName = pathParts[1];
  371. var albPath = pathParts[2];
  372. if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(albPath, out var alb))
  373. {
  374. // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
  375. var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
  376. var sb = new StringBuilder();
  377. sb.AppendLine("#EXTM3U");
  378. foreach (var track in alb.MainTracks.OrderBy(p => p.Key))
  379. {
  380. var mediaTag = GetTag($"/media/{libName}/{albPath}/{track.Key}");
  381. if (mediaTag != null)
  382. {
  383. var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/cover.jpg";
  384. sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
  385. }
  386. var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
  387. sb.AppendLine(prefix + mediaPath);
  388. }
  389. context.Response.ContentType = "audio/mpegurl";
  390. context.Response.ContentEncoding = Encoding.UTF8;
  391. context.Response.WriteText(sb.ToString());
  392. }
  393. else
  394. {
  395. context.Response.StatusCode = 404;
  396. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  397. }
  398. }
  399. else if (pathParts.Count == 5 && pathParts[0] == "list" && pathParts[4] == "playlist.m3u8")
  400. {
  401. var libName = pathParts[1];
  402. var albPath = pathParts[2];
  403. var subSetPath = pathParts[3];
  404. if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(albPath, out var alb))
  405. {
  406. // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
  407. var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
  408. if (false == alb.SubTracks.TryGetValue(subSetPath, out var trackSet))
  409. {
  410. context.Response.StatusCode = 404;
  411. }
  412. else
  413. {
  414. var sb = new StringBuilder();
  415. sb.AppendLine("#EXTM3U");
  416. foreach (var track in trackSet.Tracks.OrderBy(p => p.Key))
  417. {
  418. var mediaTag = GetTag($"/media/{libName}/{albPath}/{subSetPath}/{track.Key}");
  419. if (mediaTag != null)
  420. {
  421. var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/cover.jpg";
  422. sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
  423. }
  424. var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{subSetPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
  425. sb.AppendLine(prefix + mediaPath);
  426. }
  427. context.Response.ContentType = "audio/mpegurl";
  428. context.Response.ContentEncoding = Encoding.UTF8;
  429. context.Response.WriteText(sb.ToString());
  430. }
  431. }
  432. else
  433. {
  434. context.Response.StatusCode = 404;
  435. //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
  436. }
  437. }
  438. else if (PathMapping.TryGetValue(requestPath, out var realPath))
  439. {
  440. switch (pathParts.FirstOrDefault())
  441. {
  442. default: context.Response.ContentType = "video/mp4"; break;
  443. //case "media":
  444. // context.Response.ContentType = $"audio/{requestPath?.Split('.').LastOrDefault() ?? "flac"}";
  445. // break;
  446. case "cover":
  447. case "bk":
  448. context.Response.ContentType = $"image/{requestPath?.Split('.').LastOrDefault() ?? "jpg"}";
  449. break;
  450. }
  451. var range = request.Headers.GetValues("Range");
  452. FileStream fs = null;
  453. try
  454. {
  455. fs = File.OpenRead(realPath);
  456. if (range is { Length: > 0 })
  457. {
  458. var rngParts = range[0].Split(new[] { "bytes=", "-" }, StringSplitOptions.RemoveEmptyEntries);
  459. if (rngParts.Length >= 1 && long.TryParse(rngParts[0], out var start))
  460. {
  461. fs.Position = start;
  462. context.Response.StatusCode = 206;
  463. context.Response.Headers.Add("Accept-Ranges", "bytes");
  464. context.Response.Headers.Add("Content-Range", $"bytes {start}-{fs.Length - 1}/{fs.Length}");
  465. context.Response.ContentLength64 = fs.Length - start;
  466. fs.CopyTo(context.Response.OutputStream);
  467. }
  468. }
  469. else
  470. {
  471. context.Response.ContentLength64 = fs.Length;
  472. fs.CopyTo(context.Response.OutputStream);
  473. }
  474. }
  475. catch (Exception e)
  476. {
  477. Console.WriteLine(e);
  478. }
  479. finally
  480. {
  481. fs?.Close();
  482. }
  483. }
  484. else
  485. {
  486. context.Response.StatusCode = 404;
  487. }
  488. }
  489. catch (Exception e)
  490. {
  491. Console.WriteLine(e);
  492. try
  493. {
  494. context.Response.StatusCode = 500;
  495. }
  496. catch (Exception exception)
  497. {
  498. Console.WriteLine(exception);
  499. }
  500. }
  501. finally
  502. {
  503. try
  504. {
  505. context.Response.Close();
  506. }
  507. catch (Exception e)
  508. {
  509. Console.WriteLine(e);
  510. }
  511. }
  512. }
  513. private static string FormatDuration(this int second)
  514. {
  515. var sbd = new StringBuilder();
  516. var ts = TimeSpan.FromSeconds(second);
  517. if (ts.TotalHours > 1) sbd.Append($"{ts.TotalHours:00}:");
  518. sbd.Append($"{ts.Minutes:00}:{ts.Seconds:00}");
  519. return sbd.ToString();
  520. }
  521. private static string FormatFileSize(this long length)
  522. {
  523. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  524. double len = length;
  525. int order = 0;
  526. while (len >= 1024 && order < sizes.Length - 1)
  527. {
  528. order++;
  529. len = len / 1024;
  530. }
  531. // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
  532. // show a single decimal place, and no space.
  533. string result = $"{len:000.00} {sizes[order]}";
  534. return result;
  535. }
  536. private static void WriteText(this HttpListenerResponse response, string content)
  537. {
  538. var bytes = Encoding.UTF8.GetBytes(content);
  539. response.OutputStream.Write(bytes);
  540. }
  541. private static string FuckVlcAndEscape(this string input)
  542. {
  543. if (input == null) return null;
  544. return input
  545. .Replace("[", "%5B")
  546. .Replace("]", "%5D")
  547. .Replace("'", "%27")
  548. ;
  549. }
  550. private static MediaTag2 GetTag(string internalPath, bool peek = false)
  551. {
  552. if (peek)
  553. {
  554. if (MediaTags.TryGetValue(internalPath, out var mediaTag))
  555. {
  556. return mediaTag;
  557. }
  558. return null;
  559. }
  560. else
  561. {
  562. if (false == MediaTags.TryGetValue(internalPath, out var mediaTag) && PathMapping.TryGetValue(internalPath, out var mediaFilePath))
  563. {
  564. var fi = new FileInfo(mediaFilePath);
  565. using var tagLib = TagLib.File.Create(mediaFilePath);
  566. mediaTag = MediaTags[internalPath] = new MediaTag2(
  567. $"{string.Join(";", tagLib.Tag.Performers)} - {tagLib.Tag.Title}",
  568. (int)tagLib.Properties.Duration.TotalSeconds,
  569. fi.Length
  570. );
  571. }
  572. return mediaTag;
  573. }
  574. }
  575. }
  576. }