1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
|
using MediaBrowser.Model.Logging;
using MediaBrowser.Server.Startup.Common;
using MediaBrowser.Server.Startup.Common.IO;
using MediaBrowser.Server.Implementations;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.ObjCRuntime;
using Emby.Server.Core;
using Emby.Server.Implementations;
using Emby.Common.Implementations.Logging;
using Emby.Server.Implementations.Logging;
using Emby.Common.Implementations.EnvironmentInfo;
using Emby.Server.Mac.Native;
using Emby.Server.Implementations.IO;
using Emby.Common.Implementations.Networking;
using Emby.Common.Implementations.Security;
using Mono.Unix.Native;
using MediaBrowser.Model.System;
using MediaBrowser.Model.IO;
using Emby.Server.Core.Logging;
namespace MediaBrowser.Server.Mac
{
class MainClass
{
internal static MacAppHost AppHost;
private static ILogger _logger;
private static IFileSystem _fileSystem;
static void Main (string[] args)
{
SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
var applicationPath = Assembly.GetEntryAssembly().Location;
var options = new StartupOptions(Environment.GetCommandLineArgs());
// Allow this to be specified on the command line.
var customProgramDataPath = options.GetOption("-programdata");
var appFolderPath = Path.GetDirectoryName(applicationPath);
var appPaths = CreateApplicationPaths(appFolderPath, customProgramDataPath);
var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
logManager.ReloadLogger(LogSeverity.Info);
logManager.AddConsoleOutput();
var logger = _logger = logManager.GetLogger("Main");
ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
StartApplication(appPaths, logManager, options);
NSApplication.Init ();
NSApplication.Main (args);
}
private static ServerApplicationPaths CreateApplicationPaths(string appFolderPath, string programDataPath)
{
if (string.IsNullOrEmpty(programDataPath))
{
// TODO: Use CommonApplicationData? Will we always have write access?
programDataPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "mediabrowser-server");
if (!Directory.Exists (programDataPath)) {
programDataPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "emby-server");
}
}
// Within the mac bundle, go uo two levels then down into Resources folder
var resourcesPath = Path.Combine(Path.GetDirectoryName(appFolderPath), "Resources");
Action<string> createDirectoryFn = (string obj) => Directory.CreateDirectory(obj);
return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath, createDirectoryFn);
}
/// <summary>
/// Runs the application.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="logManager">The log manager.</param>
/// <param name="options">The options.</param>
private static void StartApplication(ServerApplicationPaths appPaths,
ILogManager logManager,
StartupOptions options)
{
// Allow all https requests
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
var fileSystem = new MonoFileSystem(logManager.GetLogger("FileSystem"), false, false, appPaths.TempDirectory);
fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
_fileSystem = fileSystem;
var environmentInfo = GetEnvironmentInfo();
var imageEncoder = ImageEncoderHelper.GetImageEncoder(_logger,
logManager,
fileSystem,
options,
() => AppHost.HttpClient,
appPaths);
AppHost = new MacAppHost(appPaths,
logManager,
options,
fileSystem,
new PowerManagement(),
"Emby.Server.Mac.pkg",
environmentInfo,
imageEncoder,
new Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")),
new MemoryStreamProvider(),
new NetworkManager(logManager.GetLogger("NetworkManager")),
GenerateCertificate,
() => Environment.UserName);
if (options.ContainsOption("-v")) {
Console.WriteLine (AppHost.ApplicationVersion.ToString());
return;
}
Console.WriteLine ("appHost.Init");
Task.Run (() => StartServer(CancellationToken.None));
}
private static void GenerateCertificate(string certPath, string certHost)
{
CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger);
}
private static EnvironmentInfo GetEnvironmentInfo()
{
var info = new EnvironmentInfo()
{
CustomOperatingSystem = MediaBrowser.Model.System.OperatingSystem.OSX
};
var uname = GetUnixName();
var sysName = uname.sysname ?? string.Empty;
if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
{
//info.OperatingSystem = Startup.Common.OperatingSystem.Osx;
}
else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
{
//info.OperatingSystem = Startup.Common.OperatingSystem.Linux;
}
else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
{
//info.OperatingSystem = Startup.Common.OperatingSystem.Bsd;
//info.IsBsd = true;
}
var archX86 = new Regex("(i|I)[3-6]86");
if (archX86.IsMatch(uname.machine))
{
info.CustomArchitecture = Architecture.X86;
}
else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
{
info.CustomArchitecture = Architecture.X64;
}
else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
{
info.CustomArchitecture = Architecture.Arm;
}
else if (System.Environment.Is64BitOperatingSystem)
{
info.CustomArchitecture = Architecture.X64;
}
else
{
info.CustomArchitecture = Architecture.X86;
}
return info;
}
private static Uname _unixName;
private static Uname GetUnixName()
{
if (_unixName == null)
{
var uname = new Uname();
try
{
Utsname utsname;
var callResult = Syscall.uname(out utsname);
if (callResult == 0)
{
uname.sysname = utsname.sysname ?? string.Empty;
uname.machine = utsname.machine ?? string.Empty;
}
}
catch (Exception ex)
{
_logger.ErrorException("Error getting unix name", ex);
}
_unixName = uname;
}
return _unixName;
}
public class Uname
{
public string sysname = string.Empty;
public string machine = string.Empty;
}
private static async void StartServer(CancellationToken cancellationToken)
{
var initProgress = new Progress<double>();
await AppHost.Init (initProgress).ConfigureAwait (false);
await AppHost.RunStartupTasks ().ConfigureAwait (false);
if (MenuBarIcon.Instance != null)
{
MenuBarIcon.Instance.Localize ();
}
}
public static void Shutdown()
{
ShutdownApp();
}
private static void ShutdownApp()
{
_logger.Info ("Calling ApplicationHost.Dispose");
AppHost.Dispose ();
_logger.Info("AppController.Terminate");
MenuBarIcon.Instance.Terminate ();
}
public static void Restart()
{
_logger.Info("Disposing app host");
AppHost.Dispose();
_logger.Info("Starting new instance");
var args = Environment.GetCommandLineArgs()
.Skip(1)
.Select(NormalizeCommandLineArgument);
var commandLineArgsString = string.Join(" ", args.ToArray());
var module = Environment.GetCommandLineArgs().First();
_logger.Info ("Executable: {0}", module);
_logger.Info ("Arguments: {0}", commandLineArgsString);
Process.Start(module, commandLineArgsString);
_logger.Info("AppController.Terminate");
MenuBarIcon.Instance.Terminate();
}
private static string NormalizeCommandLineArgument(string arg)
{
if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
{
return arg;
}
return "\"" + arg + "\"";
}
/// <summary>
/// Handles the UnhandledException event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = (Exception)e.ExceptionObject;
var consoleLogger = new ConsoleLogger();
new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager, _fileSystem, consoleLogger).Log(exception);
if (!Debugger.IsAttached)
{
Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
}
}
}
class NoCheckCertificatePolicy : ICertificatePolicy
{
public bool CheckValidationResult (ServicePoint srvPoint,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
WebRequest request,
int certificateProblem)
{
return true;
}
}
}
|