OperatingSystem.cs 2.4 KB

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