Program2.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. //" height:20vh;" +
  221. //" overflow:scroll;" +
  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. " max-width:50vw;" +
  234. " max-height:30vh" +
  235. "}" +
  236. "div.disc_name{" +
  237. //" float:right;" +
  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("<h2 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h2>");
  248. sb.Append($"<h1>Albums of {l.Name}</h1>");
  249. sb.Append("<div><a href=/>Back to home</a></div>");
  250. //Cover list
  251. foreach (var a in l.Albums.OrderBy(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($"<a class=button 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.Albums.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("<h2 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h2>");
  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($" ({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($" ({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.Albums.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("<h2 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h2>");
  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.Albums.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.Albums.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. switch (pathParts.FirstOrDefault())
  443. {
  444. default: context.Response.ContentType = "video/mp4"; break;
  445. case "media":
  446. context.Response.ContentType = $"audio/{requestPath?.Split('.').LastOrDefault() ?? "flac"}";
  447. break;
  448. case "cover":
  449. case "bk":
  450. context.Response.ContentType = $"image/{requestPath?.Split('.').LastOrDefault() ?? "jpg"}";
  451. break;
  452. }
  453. var range = request.Headers.GetValues("Range");
  454. FileStream fs = null;
  455. try
  456. {
  457. fs = File.OpenRead(realPath);
  458. if (range is { Length: > 0 })
  459. {
  460. var rngParts = range[0].Split(new[] { "bytes=", "-" }, StringSplitOptions.RemoveEmptyEntries);
  461. if (rngParts.Length >= 1 && long.TryParse(rngParts[0], out var start))
  462. {
  463. fs.Position = start;
  464. context.Response.StatusCode = 206;
  465. context.Response.Headers.Add("Accept-Ranges", "bytes");
  466. context.Response.Headers.Add("Content-Range", $"bytes {start}-{fs.Length - 1}/{fs.Length}");
  467. context.Response.ContentLength64 = fs.Length - start;
  468. fs.CopyTo(context.Response.OutputStream);
  469. }
  470. }
  471. else
  472. {
  473. context.Response.ContentLength64 = fs.Length;
  474. fs.CopyTo(context.Response.OutputStream);
  475. }
  476. }
  477. catch (Exception e)
  478. {
  479. Console.WriteLine(e);
  480. }
  481. finally
  482. {
  483. fs?.Close();
  484. }
  485. }
  486. else
  487. {
  488. context.Response.StatusCode = 404;
  489. }
  490. }
  491. catch (Exception e)
  492. {
  493. Console.WriteLine(e);
  494. try
  495. {
  496. context.Response.StatusCode = 500;
  497. }
  498. catch (Exception exception)
  499. {
  500. Console.WriteLine(exception);
  501. }
  502. }
  503. finally
  504. {
  505. try
  506. {
  507. context.Response.Close();
  508. }
  509. catch (Exception e)
  510. {
  511. Console.WriteLine(e);
  512. }
  513. }
  514. }
  515. private static string FormatDuration(this int second)
  516. {
  517. var sbd = new StringBuilder();
  518. var ts = TimeSpan.FromSeconds(second);
  519. if (ts.TotalHours > 1) sbd.Append($"{ts.TotalHours:00}:");
  520. sbd.Append($"{ts.Minutes:00}:{ts.Seconds:00}");
  521. return sbd.ToString();
  522. }
  523. private static string FormatFileSize(this long length)
  524. {
  525. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  526. double len = length;
  527. int order = 0;
  528. while (len >= 1024 && order < sizes.Length - 1)
  529. {
  530. order++;
  531. len = len / 1024;
  532. }
  533. // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
  534. // show a single decimal place, and no space.
  535. string result = $"{len:000.00} {sizes[order]}";
  536. return result;
  537. }
  538. private static void WriteText(this HttpListenerResponse response, string content)
  539. {
  540. var bytes = Encoding.UTF8.GetBytes(content);
  541. response.OutputStream.Write(bytes);
  542. }
  543. private static string FuckVlcAndEscape(this string input)
  544. {
  545. if (input == null) return null;
  546. return input
  547. .Replace("[", "%5B")
  548. .Replace("]", "%5D")
  549. .Replace("'", "%27")
  550. ;
  551. }
  552. private static MediaTag2 GetTag(string internalPath, bool peek = false)
  553. {
  554. if (peek)
  555. {
  556. if (MediaTags.TryGetValue(internalPath, out var mediaTag))
  557. {
  558. return mediaTag;
  559. }
  560. return null;
  561. }
  562. else
  563. {
  564. if (false == MediaTags.TryGetValue(internalPath, out var mediaTag) && PathMapping.TryGetValue(internalPath, out var mediaFilePath))
  565. {
  566. var fi = new FileInfo(mediaFilePath);
  567. using var tagLib = TagLib.File.Create(mediaFilePath);
  568. mediaTag = MediaTags[internalPath] = new MediaTag2(
  569. $"{string.Join(";", tagLib.Tag.Performers)} - {tagLib.Tag.Title}",
  570. (int)tagLib.Properties.Duration.TotalSeconds,
  571. fi.Length
  572. );
  573. }
  574. return mediaTag;
  575. }
  576. }
  577. }
  578. }