123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698 |
- using Microsoft.VisualBasic.FileIO;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using SearchOption = Microsoft.VisualBasic.FileIO.SearchOption;
- namespace FNZCM.ConHost.Ver2
- {
- internal static class Program2
- {
- //0. start http server
- //1. scan libraries and fill data struct
- // libs
- // albums
- // Tracks(FLAC / AAC_*)
- // Meta(title(artist) / duration)
- // FSI ( size )
- // TODO: Generate thumbnail of BKS
- private static readonly ConcurrentDictionary<string, Library2> Libraries = new();
- private static readonly ConcurrentDictionary<string, string> PathMapping = new();
- private static readonly ConcurrentDictionary<string, MediaTag2> MediaTags = new();
- private static bool _isRunning;
- private static bool _isLoading;
- private static DateTime _lastRequestAccepted;
- private static void Main()
- {
- Console.WriteLine("Starting...");
- var tWorker = new Thread(Working);
- _isRunning = true;
- tWorker.Start();
- Task.Run(ScanLibrary);
- Console.WriteLine("Press ENTER to Stop.");
- Console.ReadLine();
- Console.WriteLine("Shutting down...");
- _isRunning = false;
- tWorker.Join();
- Console.WriteLine("Stopped.");
- Console.WriteLine();
- Console.Write("Press ENTER to Exit.");
- Console.ReadLine();
- }
- private static void ScanLibrary()
- {
- if (_isLoading) return;
- _isLoading = true;
- try
- {
- ConfigFile.Reload();
- Console.WriteLine("Scanning libraries...");
- MediaTags.Clear();
- PathMapping.Clear();
- Libraries.Clear();
- foreach (var kvpLib in ConfigFile.Instance.Libraries)
- {
- if (_isRunning == false) throw new OperationCanceledException();
- Console.WriteLine($"Library {kvpLib.Key} - {kvpLib.Value}");
- var libPath = kvpLib.Key.ToLower();
- var lib = Libraries[libPath] = new Library2(kvpLib.Key);
- var albDirArray = Directory.GetDirectories(kvpLib.Value);
- foreach (var albDir in albDirArray)
- {
- if (_isRunning == false) throw new OperationCanceledException();
- Console.WriteLine($" Disc {albDir}");
- var albName = Path.GetFileName(albDir);
- var albPath = albName.ToLower();
- var alb = lib.Discs[albPath] = new Disc(albName);
- var coverFilePath = Path.Combine(albDir, "cover.jpg");
- if (File.Exists(coverFilePath)) PathMapping[$"/cover/{libPath}/{albPath}/cover.jpg"] = coverFilePath;
- var bkDir = Path.Combine(albDir, "bk");
- if (Directory.Exists(bkDir))
- {
- var bkFiles = FileSystem.GetFiles(bkDir, SearchOption.SearchTopLevelOnly, ConfigFile.Instance.BkFilePattern);
- foreach (var file in bkFiles)
- {
- var bkName = Path.GetFileName(file);
- var bkPath = bkName.ToLower();
- alb.Bks[bkPath] = bkName;
- PathMapping[$"/bk/{libPath}/{albPath}/{bkPath}"] = file;
- }
- }
- var mainTrackFiles = FileSystem.GetFiles(albDir, SearchOption.SearchTopLevelOnly, ConfigFile.Instance.MediaFilePattern);
- foreach (var mainTrackFile in mainTrackFiles)
- {
- var trackName = Path.GetFileName(mainTrackFile);
- var trackPath = trackName.ToLower();
- alb.MainTracks[trackPath] = trackName;
- PathMapping[$"/media/{libPath}/{albPath}/{trackPath}"] = mainTrackFile;
- }
- var aacTrackDirArray = Directory.GetDirectories(albDir, "AAC_Q*");
- foreach (var aacTrackDir in aacTrackDirArray)
- {
- var aacTrackSetName = Path.GetFileName(aacTrackDir);
- var aacTrackSetPath = aacTrackSetName.ToLower();
- var aacTrackSet = alb.SubTracks[aacTrackSetPath] = new TrackSet(aacTrackSetName);
- foreach (var file in Directory.GetFiles(aacTrackDir,"*.m4a"))
- {
- var aacTrackName = Path.GetFileName(file);
- var aacTrackPath = aacTrackName.ToLower();
- aacTrackSet.Tracks[aacTrackPath] = aacTrackName;
- PathMapping[$"/media/{libPath}/{albPath}/{aacTrackSetPath}/{aacTrackPath}"] = file;
- }
- }
- }
- }
- Console.WriteLine("Looking tags...");
- Parallel.ForEach(PathMapping.Keys.Where(p => p.StartsWith("/media/")), k => GetTag(k));
- Console.WriteLine("Looking tags...Done");
- }
- catch (Exception e)
- {
- Console.WriteLine($"Load error: {e}");
- }
- _isLoading = false;
- }
- private static void Working()
- {
- var listener = new HttpListener();
- listener.Prefixes.Add(ConfigFile.Instance.ListenPrefix);
- listener.Start();
- var upTime = DateTime.Now;
- Console.WriteLine($"HTTP Server started, listening on {ConfigFile.Instance.ListenPrefix}");
- listener.BeginGetContext(ContextGet, listener);
- _lastRequestAccepted = DateTime.Now;
- while (_isRunning)
- {
- var timeSpan = DateTime.Now - _lastRequestAccepted;
- var up = DateTime.Now - upTime;
- Console.Title =
- "FNZCM"
- + $" UP {up.Days:00}D {up.Hours:00}H {up.Minutes:00}M {up.Seconds:00}S {up.Milliseconds:000}"
- + $" / "
- + $" LA {timeSpan.Days:00}D {timeSpan.Hours:00}H {timeSpan.Minutes:00}M {timeSpan.Seconds:00}S {timeSpan.Milliseconds:000}"
- ;
- Thread.Sleep(1000);
- }
- listener.Close();
- Thread.Sleep(1000);
- }
- private static void ContextGet(IAsyncResult ar)
- {
- var listener = (HttpListener)ar.AsyncState;
- HttpListenerContext context;
- try
- {
- // ReSharper disable once PossibleNullReferenceException
- context = listener.EndGetContext(ar);
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- return;
- }
- if (_isRunning) listener.BeginGetContext(ContextGet, listener);
- ProcessRequest(context);
- }
- private static void ProcessRequest(HttpListenerContext context)
- {
- _lastRequestAccepted = DateTime.Now;
- var request = context.Request;
- Console.WriteLine($"Request from {request.RemoteEndPoint} {request.HttpMethod} {request.RawUrl}");
- // GET / show all libraries
- // foo=library bar=album
- // GET /list/foo/ show all album and cover with name, provide m3u path
- // GET /list/foo/bar/bk/ list all picture as grid
- // GET /list/foo/bar/tracks/ list all tracks as text list
- // GET /list/foo/bar/playlist.m3u8 auto gen
- // GET /list/foo/bar/aac_q1.00/playlist.m3u8 auto gen
- // media streaming HTTP Partial RANGE SUPPORT
- // GET /cover/foo/bar/cover.jpg image/<ext>
- // GET /media/foo/bar/01.%20foobar.flac audio/<ext>
- // GET /media/foo/bar/aac_q1.00/01.%20foobar.m4a audio/<ext>
- // GET /bk/foo/bar/foobar.jpg image/<ext>
- try
- {
- // ReSharper disable once PossibleNullReferenceException
- var requestPath = request.Url.LocalPath.ToLower();
- var pathParts = (IReadOnlyList<string>)requestPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
- if (requestPath == "/scan/")
- {
- Task.Run(ScanLibrary);
- context.Response.Redirect("/");
- }
- else if (requestPath == "/")
- {
- var sb = new StringBuilder();
- sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
- sb.Append($"<title> Libraries - {ConfigFile.Instance.Title} </title>");
- sb.Append("<body bgColor=skyBlue style=font-size:3vh>");
- if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
- sb.Append($"<h2>{ConfigFile.Instance.Title}</h2>");
- sb.Append($"<h3>Libraries</h3>");
- sb.Append($"<h4>(Total number of disc: {Libraries.Sum(p=>p.Value.Discs.Count)})</h4>");
- sb.Append("<ul>");
- foreach (var library in Libraries.OrderBy(p => p.Key))
- {
- sb.Append("<li>");
- sb.Append($"<a href='/list/{library.Key.FuckVlcAndEscape()}/'>{library.Value.Name}</a>");
- sb.Append($"<br/> Number of disc: {library.Value.Discs.Count}");
- sb.Append("</li>");
- }
- sb.Append("</ul>");
- sb.Append("<a href=/scan/>Reload</a>");
- sb.Append($"<div>Your IP: {context?.Request?.RemoteEndPoint?.Address.ToString() ?? "Unknown"}</div>");
- context.Response.WriteText(sb.ToString());
- }
- else if (pathParts.Count == 2 && pathParts[0] == "list")
- {
- var libName = pathParts[1];
- if (Libraries.TryGetValue(libName, out var l))
- {
- var sb = new StringBuilder();
- sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
- sb.Append($"<title> Discs of {l.Name} - {ConfigFile.Instance.Title} </title>");
- sb.Append(
- "<style>" +
- "a:link{ text-decoration: none; }" +
- "div.item{" +
- " vertical-align:top;" +
- " margin-bottom:1vh;" +
- " padding:0.5vh;" +
- " border:solid 1px;" +
- " border-radius:0.5vh;" +
- " font-size:2.2vh;" +
- "}" +
- "div.item::-webkit-scrollbar{" +
- " display: none;" +
- "}" +
- "img.cover{" +
- " float:left;" +
- " width:45vw;" +
- "}" +
- "div.disc_name{" +
- "}" +
- "div.links{" +
- " clear:both;" +
- "}" +
- "a.button{" +
- " margin-left:4vw;" +
- "}" +
- "</style>");
- sb.Append($"<body bgColor=skyBlue>");
- if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
- sb.Append($"<h1>Discs of {l.Name}</h1>");
- sb.Append("<div><a href=/>Back to home</a></div>");
- //Cover list
- foreach (var a in l.Discs.OrderByDescending(p => p.Key))
- {
- sb.Append("<div class=item>");
- sb.Append($"<div>");
- sb.Append($"<img class=cover src=\"/cover/{libName}/{a.Key}/cover.jpg\" />");
- sb.Append($"<div class=disc_name>{a.Value.Name}</div>");
- sb.Append($"</div>");
- sb.Append("<div class=links>");
- sb.Append("<div>");
- sb.Append($"Number of track: {a.Value.MainTracks.Count} <a href=\"/list/{libName}/{a.Key}/tracks/\">[TRACKERS]</a>");
- if (a.Value.Bks?.Count > 0) sb.Append($"<a class=button href=\"/list/{libName}/{a.Key}/bk/\">[BK]</a>");
- sb.Append("</div>");
- var totalDur = a.Value.MainTracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{p.Key}", true)?.Duration ?? 0);
- var totalLen = a.Value.MainTracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{p.Key}", true)?.Length ?? 0);
- sb.Append($"{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/list/{libName}/{a.Key.FuckVlcAndEscape()}/playlist.m3u8\">M3U8_MAIN</a>");
- if (a.Value.SubTracks.Count > 0)
- {
- foreach (var subTrack in a.Value.SubTracks)
- {
- totalDur = subTrack.Value.Tracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{subTrack.Key}/{p.Key}", true)?.Duration ?? 0);
- totalLen = subTrack.Value.Tracks.Sum(p => GetTag($"/media/{libName}/{a.Key}/{subTrack.Key}/{p.Key}", true)?.Length ?? 0);
- sb.Append($"<br/>{totalDur.FormatDuration()} {totalLen.FormatFileSize()} <a href=\"/list/{libName}/{a.Key.FuckVlcAndEscape()}/{subTrack.Key.FuckVlcAndEscape()}/playlist.m3u8\">{subTrack.Value.Name}</a>");
- }
- }
- sb.Append("</div>");
- sb.Append("</div>");
- }
- context.Response.ContentType = "text/html";
- context.Response.ContentEncoding = Encoding.UTF8;
- context.Response.WriteText(sb.ToString());
- }
- else
- {
- context.Response.StatusCode = 404;
- //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
- }
- }
- else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "tracks")
- {
- var libName = pathParts[1];
- var albPath = pathParts[2];
- if (Libraries.TryGetValue(libName, out var l) && l.Discs.TryGetValue(albPath, out var alb))
- {
- var sb = new StringBuilder();
- sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
- sb.Append($"<body bgColor=skyBlue style=font-size:2vh>");
- if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
- sb.Append($"<h2>Tracks of</h2><h1>{alb.Name}</h1>");
- sb.Append($"<div><a href='/list/{libName.FuckVlcAndEscape()}/'>Back to library</a></div>");
- var durTotal = 0;
- var sizeTotal = 0L;
- var sbm = new StringBuilder();
- foreach (var kvpTrack in alb.MainTracks.OrderBy(p => p.Key))
- {
- sbm.Append($"<li>");
- sbm.Append($"<a href=\"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{kvpTrack.Key.FuckVlcAndEscape()}\" >{kvpTrack.Value}</a>");
- var tag = GetTag($"/media/{libName}/{albPath}/{kvpTrack.Key}");
- durTotal += tag.Duration;
- sizeTotal += tag.Length;
- sbm.Append($"<br> {tag.Duration.FormatDuration()} {tag.Length.FormatFileSize()}");
- sbm.Append($"</li>");
- }
- sb.Append($"<h2>Main ({durTotal.FormatDuration()}) {sizeTotal.FormatFileSize()}</h2>");
- sb.Append(sbm);
- foreach (var kvpSubSet in alb.SubTracks.OrderBy(p => p.Key))
- {
- durTotal = 0;
- sizeTotal = 0L;
- sbm.Clear();
- foreach (var kvpTrack in kvpSubSet.Value.Tracks.OrderBy(p => p.Key))
- {
- sbm.Append($"<li>");
- sbm.Append($"<a href=\"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{kvpSubSet.Key.FuckVlcAndEscape()}/{kvpTrack.Key.FuckVlcAndEscape()}\" >{kvpTrack.Value}</a>");
- var tag = GetTag($"/media/{libName}/{albPath}/{kvpSubSet.Key}/{kvpTrack.Key}");
- durTotal += tag.Duration;
- sizeTotal += tag.Length;
- sbm.Append($"<br/> {tag.Duration.FormatDuration()} {tag.Length.FormatFileSize()}");
- sbm.Append($"</li>");
- }
- sb.Append($"<h2>{kvpSubSet.Value.Name} ({durTotal.FormatDuration()}) {sizeTotal.FormatFileSize()}</h2>");
- sb.Append(sbm);
- }
- context.Response.ContentType = "text/html";
- context.Response.ContentEncoding = Encoding.UTF8;
- context.Response.WriteText(sb.ToString());
- }
- else
- {
- context.Response.StatusCode = 404;
- //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
- }
- }
- else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "bk")
- {
- var libName = pathParts[1];
- var albPath = pathParts[2];
- if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(albPath, out var alb))
- {
- var sb = new StringBuilder();
- sb.Append("<!DOCTYPE html><html lang=\"zh-cn\"><meta charset=\"UTF-8\">");
- sb.Append($"<body bgColor=skyBlue style=font-size:2vh>");
- if (_isLoading) sb.Append("<h4 style=position:fixed;right:0px;top:0px;margin:0>Still Loading...</h4>");
- sb.Append($"<h2>BK of </h2><h1>{alb.Name}</h1>");
- sb.Append($"<div><a href='/list/{libName.FuckVlcAndEscape()}/'>Back to library</a></div>");
- foreach (var albBk in alb.Bks.OrderBy(p => p.Key))
- {
- //TODO: auto gen thumbnail 512x512 jpg 80
- 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; />");
- }
- context.Response.ContentType = "text/html";
- context.Response.ContentEncoding = Encoding.UTF8;
- context.Response.WriteText(sb.ToString());
- }
- else
- {
- context.Response.StatusCode = 404;
- //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
- }
- }
- else if (pathParts.Count == 4 && pathParts[0] == "list" && pathParts[3] == "playlist.m3u8")
- {
- var libName = pathParts[1];
- var albPath = pathParts[2];
- if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(albPath, out var alb))
- {
- // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
- var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
- var sb = new StringBuilder();
- sb.AppendLine("#EXTM3U");
- foreach (var track in alb.MainTracks.OrderBy(p => p.Key))
- {
- var mediaTag = GetTag($"/media/{libName}/{albPath}/{track.Key}");
- if (mediaTag != null)
- {
- var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/cover.jpg";
- sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
- }
- var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
- sb.AppendLine(prefix + mediaPath);
- }
- context.Response.ContentType = "audio/mpegurl";
- context.Response.ContentEncoding = Encoding.UTF8;
- context.Response.WriteText(sb.ToString());
- }
- else
- {
- context.Response.StatusCode = 404;
- //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
- }
- }
- else if (pathParts.Count == 5 && pathParts[0] == "list" && pathParts[4] == "playlist.m3u8")
- {
- var libName = pathParts[1];
- var albPath = pathParts[2];
- var subSetPath = pathParts[3];
- if (Libraries.TryGetValue(libName, out var lib) && lib.Discs.TryGetValue(albPath, out var alb))
- {
- // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
- var prefix = $"{request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority)}";
- if (false == alb.SubTracks.TryGetValue(subSetPath, out var trackSet))
- {
- context.Response.StatusCode = 404;
- }
- else
- {
- var sb = new StringBuilder();
- sb.AppendLine("#EXTM3U");
- foreach (var track in trackSet.Tracks.OrderBy(p => p.Key))
- {
- var mediaTag = GetTag($"/media/{libName}/{albPath}/{subSetPath}/{track.Key}");
- if (mediaTag != null)
- {
- var coverPath = $"/cover/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/cover.jpg";
- sb.AppendLine($"#EXTINF:{mediaTag.Duration} tvg-logo=\"{prefix + coverPath}\",{mediaTag.Title}");
- }
- var mediaPath = $"/media/{libName.FuckVlcAndEscape()}/{albPath.FuckVlcAndEscape()}/{subSetPath.FuckVlcAndEscape()}/{track.Key.FuckVlcAndEscape()}";
- sb.AppendLine(prefix + mediaPath);
- }
- context.Response.ContentType = "audio/mpegurl";
- context.Response.ContentEncoding = Encoding.UTF8;
- context.Response.WriteText(sb.ToString());
- }
- }
- else
- {
- context.Response.StatusCode = 404;
- //context.Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
- }
- }
- else if (PathMapping.TryGetValue(requestPath, out var realPath))
- {
- var ext = requestPath.Split('.').LastOrDefault()?.ToLower();
- switch (ext)
- {
- case "flac": context.Response.ContentType = "audio/flac"; break;
- case "m4a": context.Response.ContentType = "audio/mp4"; break;
- case "mp3": context.Response.ContentType = "audio/mpeg"; break;
- case "aac": context.Response.ContentType = "audio/aac"; break;
- case "mp4": context.Response.ContentType = "video/mp4"; break;
- case "mkv": context.Response.ContentType = $"video/webm"; break;
- case "jpg":
- case "jpeg": context.Response.ContentType = $"image/jpeg"; break;
- case "png": context.Response.ContentType = $"image/png"; break;
- case "bmp": context.Response.ContentType = $"image/bmp"; break;
- default:
- var firstParts = requestPath.Split('/').FirstOrDefault();
- switch (firstParts)
- {
- case "media": context.Response.ContentType = "audio/" + ext; break;
- case "bk":
- case "cover": context.Response.ContentType = "image/" + ext; break;
- }
- break;
- }
- var range = request.Headers.GetValues("Range");
- FileStream fs = null;
- try
- {
- fs = File.OpenRead(realPath);
- if (range is { Length: > 0 })
- {
- var rngParts = range[0].Split(new[] { "bytes=", "-" }, StringSplitOptions.RemoveEmptyEntries);
- if (rngParts.Length >= 1 && long.TryParse(rngParts[0], out var start))
- {
- fs.Position = start;
- context.Response.StatusCode = 206;
- context.Response.Headers.Add("Accept-Ranges", "bytes");
- context.Response.Headers.Add("Content-Range", $"bytes {start}-{fs.Length - 1}/{fs.Length}");
- context.Response.ContentLength64 = fs.Length - start;
- fs.CopyTo(context.Response.OutputStream);
- }
- }
- else
- {
- context.Response.ContentLength64 = fs.Length;
- fs.CopyTo(context.Response.OutputStream);
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- }
- finally
- {
- fs?.Close();
- }
- }
- else
- {
- context.Response.StatusCode = 404;
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- try
- {
- context.Response.StatusCode = 500;
- }
- catch (Exception exception)
- {
- Console.WriteLine(exception);
- }
- }
- finally
- {
- try
- {
- context.Response.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- }
- }
- }
- private static string FormatDuration(this int second)
- {
- var sbd = new StringBuilder();
- var ts = TimeSpan.FromSeconds(second);
- if (ts.TotalHours > 1) sbd.Append($"{ts.TotalHours:00}:");
- sbd.Append($"{ts.Minutes:00}:{ts.Seconds:00}");
- return sbd.ToString();
- }
- private static string FormatFileSize(this long length)
- {
- string[] sizes = { "B", "KB", "MB", "GB", "TB" };
- double len = length;
- int order = 0;
- while (len >= 1024 && order < sizes.Length - 1)
- {
- order++;
- len = len / 1024;
- }
- // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
- // show a single decimal place, and no space.
- string result = $"{len:000.00} {sizes[order]}";
- return result;
- }
- private static void WriteText(this HttpListenerResponse response, string content)
- {
- var bytes = Encoding.UTF8.GetBytes(content);
- response.OutputStream.Write(bytes);
- }
- private static string FuckVlcAndEscape(this string input)
- {
- if (input == null) return null;
- return input
- .Replace("[", "%5B")
- .Replace("]", "%5D")
- .Replace("'", "%27")
- ;
- }
- private static MediaTag2 GetTag(string internalPath, bool peek = false)
- {
- if (peek)
- {
- if (MediaTags.TryGetValue(internalPath, out var mediaTag))
- {
- return mediaTag;
- }
- return null;
- }
- else
- {
- if (false == MediaTags.TryGetValue(internalPath, out var mediaTag) && PathMapping.TryGetValue(internalPath, out var mediaFilePath))
- {
- var fi = new FileInfo(mediaFilePath);
- using var tagLib = TagLib.File.Create(mediaFilePath);
- mediaTag = MediaTags[internalPath] = new MediaTag2(
- $"{string.Join(";", tagLib.Tag.Performers)} - {tagLib.Tag.Title}",
- (int)tagLib.Properties.Duration.TotalSeconds,
- fi.Length
- );
- }
- return mediaTag;
- }
- }
- }
- }
|