OperatingSystem.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Runtime.InteropServices;
  5. using System.Threading;
  6. using MediaBrowser.Model.System;
  7. namespace MediaBrowser.Common.System
  8. {
  9. public static class OperatingSystem
  10. {
  11. // We can't use Interlocked.CompareExchange for enums
  12. private static int _id = int.MaxValue;
  13. public static OperatingSystemId Id
  14. {
  15. get
  16. {
  17. if (_id == int.MaxValue)
  18. {
  19. Interlocked.CompareExchange(ref _id, (int)GetId(), int.MaxValue);
  20. }
  21. return (OperatingSystemId)_id;
  22. }
  23. }
  24. public static string Name
  25. {
  26. get
  27. {
  28. switch (Id)
  29. {
  30. case OperatingSystemId.BSD: return "BSD";
  31. case OperatingSystemId.Linux: return "Linux";
  32. case OperatingSystemId.Darwin: return "macOS";
  33. case OperatingSystemId.Windows: return "Windows";
  34. default: throw new Exception($"Unknown OS {Id}");
  35. }
  36. }
  37. }
  38. private static OperatingSystemId GetId()
  39. {
  40. switch (Environment.OSVersion.Platform)
  41. {
  42. // On .NET Core `MacOSX` got replaced by `Unix`, this case should never be hit.
  43. case PlatformID.MacOSX:
  44. return OperatingSystemId.Darwin;
  45. case PlatformID.Win32NT:
  46. return OperatingSystemId.Windows;
  47. case PlatformID.Unix:
  48. default:
  49. {
  50. string osDescription = RuntimeInformation.OSDescription;
  51. if (osDescription.IndexOf("linux", StringComparison.OrdinalIgnoreCase) != -1)
  52. {
  53. return OperatingSystemId.Linux;
  54. }
  55. else if (osDescription.IndexOf("darwin", StringComparison.OrdinalIgnoreCase) != -1)
  56. {
  57. return OperatingSystemId.Darwin;
  58. }
  59. else if (osDescription.IndexOf("bsd", StringComparison.OrdinalIgnoreCase) != -1)
  60. {
  61. return OperatingSystemId.BSD;
  62. }
  63. throw new Exception($"Can't resolve OS with description: '{osDescription}'");
  64. }
  65. }
  66. }
  67. }
  68. }