Program2.cs 29 KB

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