aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Mono/Program.cs
blob: 057a2456f5de9c6acc8961450a5b59598c59d280 (plain)
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
using MediaBrowser.Common.Constants;
using MediaBrowser.Common.Implementations.Logging;
using MediaBrowser.Common.Implementations.Updates;
using MediaBrowser.Model.Logging;
using MediaBrowser.Server.Implementations;
using MediaBrowser.ServerApplication;
using MediaBrowser.ServerApplication.Native;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Gtk;
using Gdk;
using System.Threading.Tasks;
using System.Reflection;

namespace MediaBrowser.Server.Mono
{
	public class MainClass
	{
		private static ApplicationHost _appHost;

		private static ILogger _logger;

		private static MainWindow _mainWindow;

		// The tray Icon
		private static StatusIcon trayIcon;

		public static void Main (string[] args)
		{
			Application.Init ();

			var appPaths = CreateApplicationPaths();

			var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
			logManager.ReloadLogger(LogSeverity.Info);

			var logger = _logger = logManager.GetLogger("Main");

			BeginLog(logger);

			AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

			if (PerformUpdateIfNeeded(appPaths, logger))
			{
				logger.Info("Exiting to perform application update.");
				return;
			}

			try
			{
				RunApplication(appPaths, logManager);
			}
			finally
			{
				logger.Info("Shutting down");

				_appHost.Dispose();
			}
		}

		private static ServerApplicationPaths CreateApplicationPaths()
		{
			return new ServerApplicationPaths();
		}

		/// <summary>
		/// Determines whether this instance [can self restart].
		/// </summary>
		/// <returns><c>true</c> if this instance [can self restart]; otherwise, <c>false</c>.</returns>
		public static bool CanSelfRestart
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this instance can self update.
		/// </summary>
		/// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
		public static bool CanSelfUpdate
		{
			get
			{
				return false;
			}
		}

		private static RemoteCertificateValidationCallback _ignoreCertificates = new RemoteCertificateValidationCallback(delegate { return true; });

		private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager)
		{
			// TODO: Show splash here

			SystemEvents.SessionEnding += SystemEvents_SessionEnding;

			// Allow all https requests
			ServicePointManager.ServerCertificateValidationCallback = _ignoreCertificates;

			_appHost = new ApplicationHost(appPaths, logManager);

			var task = _appHost.Init();
			Task.WaitAll (task);

			task = _appHost.RunStartupTasks();
			Task.WaitAll (task);

			// TODO: Hide splash here
			_mainWindow = new MainWindow ();

			// Creation of the Icon
			// Creation of the Icon
			trayIcon = new StatusIcon(new Pixbuf ("tray.png"));
			trayIcon.Visible = true;

			// When the TrayIcon has been clicked.
			trayIcon.Activate += delegate { };
			// Show a pop up menu when the icon has been right clicked.
			trayIcon.PopupMenu += OnTrayIconPopup;

			// A Tooltip for the Icon
			trayIcon.Tooltip = "Media Browser Server";

			_mainWindow.ShowAll ();
			_mainWindow.Visible = false;

			Application.Run ();
		}

		// Create the popup menu, on right click.
		static void OnTrayIconPopup (object o, EventArgs args) {

			Menu popupMenu = new Menu();

			var menuItemBrowse = new ImageMenuItem ("Browse Library");
			menuItemBrowse.Image = new Gtk.Image(Stock.MediaPlay, IconSize.Menu);
			popupMenu.Add(menuItemBrowse);
			menuItemBrowse.Activated += delegate { 
				BrowserLauncher.OpenWebClient(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
			};

			var menuItemConfigure = new ImageMenuItem ("Configure Media Browser");
			menuItemConfigure.Image = new Gtk.Image(Stock.Edit, IconSize.Menu);
			popupMenu.Add(menuItemConfigure);
			menuItemConfigure.Activated += delegate { 
				BrowserLauncher.OpenDashboard(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
			};

			var menuItemApi = new ImageMenuItem ("View Api Docs");
			menuItemApi.Image = new Gtk.Image(Stock.Network, IconSize.Menu);
			popupMenu.Add(menuItemApi);
			menuItemApi.Activated += delegate { 
				BrowserLauncher.OpenSwagger(_appHost.ServerConfigurationManager, _appHost, _logger);
			};

			var menuItemCommunity = new ImageMenuItem ("Visit Community");
			menuItemCommunity.Image = new Gtk.Image(Stock.Help, IconSize.Menu);
			popupMenu.Add(menuItemCommunity);
			menuItemCommunity.Activated += delegate { BrowserLauncher.OpenCommunity(_logger); };

			var menuItemGithub = new ImageMenuItem ("Visit Github");
			menuItemGithub.Image = new Gtk.Image(Stock.Network, IconSize.Menu);
			popupMenu.Add(menuItemGithub);
			menuItemGithub.Activated += delegate { BrowserLauncher.OpenGithub(_logger); };

			var menuItemQuit = new ImageMenuItem ("Exit");
			menuItemQuit.Image = new Gtk.Image(Stock.Quit, IconSize.Menu);
			popupMenu.Add(menuItemQuit);
			menuItemQuit.Activated += delegate { Shutdown(); };

			popupMenu.ShowAll();
			popupMenu.Popup();
		}

		/// <summary>
		/// Handles the SessionEnding event of the SystemEvents control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
		static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
		{
			if (e.Reason == SessionEndReasons.SystemShutdown)
			{
				Shutdown();
			}
		}

		/// <summary>
		/// Begins the log.
		/// </summary>
		/// <param name="logger">The logger.</param>
		private static void BeginLog(ILogger logger)
		{
			logger.Info("Media Browser Server started");
			logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));

			logger.Info("Server: {0}", Environment.MachineName);
			logger.Info("Operating system: {0}", Environment.OSVersion.ToString());

			MonoBug11817WorkAround.Apply ();
		}

		/// <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;

			LogUnhandledException(exception);

			if (!Debugger.IsAttached)
			{
				Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
			}
		}

		private static void LogUnhandledException(Exception ex)
		{
			_logger.ErrorException("UnhandledException", ex);

			_appHost.LogManager.Flush ();

			var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "crash_" + Guid.NewGuid() + ".txt");

			var builder = LogHelper.GetLogMessage(ex);

			File.WriteAllText(path, builder.ToString());
		}

		/// <summary>
		/// Performs the update if needed.
		/// </summary>
		/// <param name="appPaths">The app paths.</param>
		/// <param name="logger">The logger.</param>
		/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
		private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
		{
			return false;
		}

		public static void Shutdown()
		{
			if (trayIcon != null) {
				trayIcon.Visible = false;
				trayIcon.Dispose ();
				trayIcon = null;
			}

			if (_mainWindow != null) {
				_mainWindow.HideAll ();
				_mainWindow.Dispose ();
				_mainWindow = null;
			}

			Application.Quit ();
		}

		public static void Restart()
		{
			// Second instance will start first, so dispose so that the http ports will be available to the new instance
			_appHost.Dispose();

			// Right now this method will just shutdown, but not restart
			Shutdown ();
		}
	}

	class NoCheckCertificatePolicy : ICertificatePolicy
	{
		public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
		{
			return true;
		}
	}

	public class MonoBug11817WorkAround
	{
		public static void Apply()
		{
			var property = typeof(TimeZoneInfo).GetProperty("TimeZoneDirectory", BindingFlags.Static | BindingFlags.NonPublic);

			if (property == null) return;

			var zoneInfo = FindZoneInfoFolder();
			property.SetValue(null, zoneInfo, new object[0]);
		}

		public static string FindZoneInfoFolder()
		{
			var current = new DirectoryInfo(Directory.GetCurrentDirectory());

			while(current != null)
			{
				var zoneinfoTestPath = Path.Combine(current.FullName, "zoneinfo");

				if (Directory.Exists(zoneinfoTestPath))
					return zoneinfoTestPath;

				current = current.Parent;
			}

			return null;
		}
	}
}