ExtensionMethods.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Net;
  5. using System.Text;
  6. namespace FNZCM.ConHost.Ver2
  7. {
  8. internal static class ExtensionMethods
  9. {
  10. public static string SecondsToHumanRead(this int seconds)
  11. {
  12. var s = TimeSpan.FromSeconds(seconds);
  13. if (s.TotalHours < 1) return $"{ Math.Floor(s.TotalMinutes):00}:{s.Seconds:00}";
  14. return $"{ Math.Floor(s.TotalHours):00}:{ s.Minutes:00}:{s.Seconds:00}";
  15. }
  16. public static void WriteM3U8Header(this StringBuilder me)
  17. {
  18. me.AppendLine("#EXTM3U");
  19. me.AppendLine("#EXTENC: UTF-8");
  20. }
  21. public static string UrlEscape(this string input)
  22. {
  23. if (input == null) return null;
  24. return input
  25. .Replace("[", "%5B")
  26. .Replace("]", "%5D")
  27. .Replace("'", "%27")
  28. .Replace(" ", "%20")
  29. .Replace("#", "%23")
  30. ;
  31. }
  32. public static string FormatDuration(this int second)
  33. {
  34. var sbd = new StringBuilder();
  35. var ts = TimeSpan.FromSeconds(second);
  36. if (ts.TotalHours > 1) sbd.Append($"{ts.TotalHours:00}:");
  37. sbd.Append($"{ts.Minutes:00}:{ts.Seconds:00}");
  38. return sbd.ToString();
  39. }
  40. public static string FormatFileSize(this long length)
  41. {
  42. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  43. double len = length;
  44. int order = 0;
  45. while (len >= 1024 && order < sizes.Length - 1)
  46. {
  47. order++;
  48. len = len / 1024;
  49. }
  50. // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
  51. // show a single decimal place, and no space.
  52. string result = $"{len:000.00} {sizes[order]}";
  53. return result;
  54. }
  55. public static void WriteTextUtf8(this HttpListenerContext context, string content, string contentType = Const.TextHtml)
  56. {
  57. var bytes = Encoding.UTF8.GetBytes(content);
  58. context.Response.ContentEncoding = Encoding.UTF8;
  59. context.Response.ContentType = contentType;
  60. if (true == context.Request.Headers["Accept-Encoding"]?.Contains("gzip"))
  61. {
  62. context.Response.AddHeader("Content-Encoding", "gzip");
  63. var memoryStream = new MemoryStream(bytes);
  64. var gZipStream = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, false);
  65. memoryStream.CopyTo(gZipStream);
  66. gZipStream.Flush();
  67. }
  68. else
  69. {
  70. context.Response.OutputStream.Write(bytes);
  71. }
  72. }
  73. }
  74. }