ApplicationHost.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. using MediaBrowser.Api;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Configuration;
  4. using MediaBrowser.Common.Events;
  5. using MediaBrowser.Common.Implementations;
  6. using MediaBrowser.Common.Implementations.ScheduledTasks;
  7. using MediaBrowser.Common.IO;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Common.Progress;
  10. using MediaBrowser.Controller;
  11. using MediaBrowser.Controller.Activity;
  12. using MediaBrowser.Controller.Channels;
  13. using MediaBrowser.Controller.Chapters;
  14. using MediaBrowser.Controller.Collections;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Connect;
  17. using MediaBrowser.Controller.Devices;
  18. using MediaBrowser.Controller.Dlna;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Controller.Dto;
  21. using MediaBrowser.Controller.Entities;
  22. using MediaBrowser.Controller.FileOrganization;
  23. using MediaBrowser.Controller.Library;
  24. using MediaBrowser.Controller.LiveTv;
  25. using MediaBrowser.Controller.Localization;
  26. using MediaBrowser.Controller.MediaEncoding;
  27. using MediaBrowser.Controller.Net;
  28. using MediaBrowser.Controller.News;
  29. using MediaBrowser.Controller.Notifications;
  30. using MediaBrowser.Controller.Persistence;
  31. using MediaBrowser.Controller.Playlists;
  32. using MediaBrowser.Controller.Plugins;
  33. using MediaBrowser.Controller.Providers;
  34. using MediaBrowser.Controller.Resolvers;
  35. using MediaBrowser.Controller.Security;
  36. using MediaBrowser.Controller.Session;
  37. using MediaBrowser.Controller.Sorting;
  38. using MediaBrowser.Controller.Subtitles;
  39. using MediaBrowser.Controller.Sync;
  40. using MediaBrowser.Controller.Themes;
  41. using MediaBrowser.Controller.TV;
  42. using MediaBrowser.Dlna;
  43. using MediaBrowser.Dlna.ConnectionManager;
  44. using MediaBrowser.Dlna.ContentDirectory;
  45. using MediaBrowser.Dlna.Main;
  46. using MediaBrowser.LocalMetadata.Providers;
  47. using MediaBrowser.MediaEncoding.BdInfo;
  48. using MediaBrowser.MediaEncoding.Encoder;
  49. using MediaBrowser.MediaEncoding.Subtitles;
  50. using MediaBrowser.Model.Logging;
  51. using MediaBrowser.Model.MediaInfo;
  52. using MediaBrowser.Model.System;
  53. using MediaBrowser.Model.Updates;
  54. using MediaBrowser.Providers.Chapters;
  55. using MediaBrowser.Providers.Manager;
  56. using MediaBrowser.Providers.Subtitles;
  57. using MediaBrowser.Server.Implementations;
  58. using MediaBrowser.Server.Implementations.Activity;
  59. using MediaBrowser.Server.Implementations.Channels;
  60. using MediaBrowser.Server.Implementations.Collections;
  61. using MediaBrowser.Server.Implementations.Configuration;
  62. using MediaBrowser.Server.Implementations.Connect;
  63. using MediaBrowser.Server.Implementations.Devices;
  64. using MediaBrowser.Server.Implementations.Drawing;
  65. using MediaBrowser.Server.Implementations.Dto;
  66. using MediaBrowser.Server.Implementations.EntryPoints;
  67. using MediaBrowser.Server.Implementations.FileOrganization;
  68. using MediaBrowser.Server.Implementations.HttpServer;
  69. using MediaBrowser.Server.Implementations.HttpServer.Security;
  70. using MediaBrowser.Server.Implementations.IO;
  71. using MediaBrowser.Server.Implementations.Library;
  72. using MediaBrowser.Server.Implementations.LiveTv;
  73. using MediaBrowser.Server.Implementations.Localization;
  74. using MediaBrowser.Server.Implementations.MediaEncoder;
  75. using MediaBrowser.Server.Implementations.Notifications;
  76. using MediaBrowser.Server.Implementations.Persistence;
  77. using MediaBrowser.Server.Implementations.Playlists;
  78. using MediaBrowser.Server.Implementations.Security;
  79. using MediaBrowser.Server.Implementations.ServerManager;
  80. using MediaBrowser.Server.Implementations.Session;
  81. using MediaBrowser.Server.Implementations.Sync;
  82. using MediaBrowser.Server.Implementations.Themes;
  83. using MediaBrowser.Server.Implementations.TV;
  84. using MediaBrowser.ServerApplication.FFMpeg;
  85. using MediaBrowser.ServerApplication.IO;
  86. using MediaBrowser.ServerApplication.Native;
  87. using MediaBrowser.ServerApplication.Networking;
  88. using MediaBrowser.WebDashboard.Api;
  89. using MediaBrowser.XbmcMetadata.Providers;
  90. using System;
  91. using System.Collections.Generic;
  92. using System.Globalization;
  93. using System.IO;
  94. using System.Linq;
  95. using System.Reflection;
  96. using System.Threading;
  97. using System.Threading.Tasks;
  98. namespace MediaBrowser.ServerApplication
  99. {
  100. /// <summary>
  101. /// Class CompositionRoot
  102. /// </summary>
  103. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  104. {
  105. /// <summary>
  106. /// Gets the server configuration manager.
  107. /// </summary>
  108. /// <value>The server configuration manager.</value>
  109. public IServerConfigurationManager ServerConfigurationManager
  110. {
  111. get { return (IServerConfigurationManager)ConfigurationManager; }
  112. }
  113. /// <summary>
  114. /// Gets the name of the web application that can be used for url building.
  115. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  116. /// </summary>
  117. /// <value>The name of the web application.</value>
  118. public string WebApplicationName
  119. {
  120. get { return "mediabrowser"; }
  121. }
  122. /// <summary>
  123. /// Gets the HTTP server URL prefix.
  124. /// </summary>
  125. /// <value>The HTTP server URL prefix.</value>
  126. private IEnumerable<string> HttpServerUrlPrefixes
  127. {
  128. get
  129. {
  130. var list = new List<string>
  131. {
  132. "http://+:" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/"
  133. };
  134. return list;
  135. }
  136. }
  137. /// <summary>
  138. /// Gets the configuration manager.
  139. /// </summary>
  140. /// <returns>IConfigurationManager.</returns>
  141. protected override IConfigurationManager GetConfigurationManager()
  142. {
  143. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer);
  144. }
  145. /// <summary>
  146. /// Gets or sets the server manager.
  147. /// </summary>
  148. /// <value>The server manager.</value>
  149. private IServerManager ServerManager { get; set; }
  150. /// <summary>
  151. /// Gets or sets the user manager.
  152. /// </summary>
  153. /// <value>The user manager.</value>
  154. public IUserManager UserManager { get; set; }
  155. /// <summary>
  156. /// Gets or sets the library manager.
  157. /// </summary>
  158. /// <value>The library manager.</value>
  159. internal ILibraryManager LibraryManager { get; set; }
  160. /// <summary>
  161. /// Gets or sets the directory watchers.
  162. /// </summary>
  163. /// <value>The directory watchers.</value>
  164. private ILibraryMonitor LibraryMonitor { get; set; }
  165. /// <summary>
  166. /// Gets or sets the provider manager.
  167. /// </summary>
  168. /// <value>The provider manager.</value>
  169. private IProviderManager ProviderManager { get; set; }
  170. /// <summary>
  171. /// Gets or sets the HTTP server.
  172. /// </summary>
  173. /// <value>The HTTP server.</value>
  174. private IHttpServer HttpServer { get; set; }
  175. private IDtoService DtoService { get; set; }
  176. private IImageProcessor ImageProcessor { get; set; }
  177. private ISeriesOrderManager SeriesOrderManager { get; set; }
  178. /// <summary>
  179. /// Gets or sets the media encoder.
  180. /// </summary>
  181. /// <value>The media encoder.</value>
  182. private IMediaEncoder MediaEncoder { get; set; }
  183. private IConnectManager ConnectManager { get; set; }
  184. private ISessionManager SessionManager { get; set; }
  185. private ILiveTvManager LiveTvManager { get; set; }
  186. internal ILocalizationManager LocalizationManager { get; set; }
  187. private IEncodingManager EncodingManager { get; set; }
  188. private IChannelManager ChannelManager { get; set; }
  189. private ISyncManager SyncManager { get; set; }
  190. /// <summary>
  191. /// Gets or sets the user data repository.
  192. /// </summary>
  193. /// <value>The user data repository.</value>
  194. private IUserDataManager UserDataManager { get; set; }
  195. private IUserRepository UserRepository { get; set; }
  196. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  197. internal IItemRepository ItemRepository { get; set; }
  198. private INotificationsRepository NotificationsRepository { get; set; }
  199. private IFileOrganizationRepository FileOrganizationRepository { get; set; }
  200. private IProviderRepository ProviderRepository { get; set; }
  201. private INotificationManager NotificationManager { get; set; }
  202. private ISubtitleManager SubtitleManager { get; set; }
  203. private IChapterManager ChapterManager { get; set; }
  204. private IDeviceManager DeviceManager { get; set; }
  205. internal IUserViewManager UserViewManager { get; set; }
  206. private IAuthenticationRepository AuthenticationRepository { get; set; }
  207. private ISyncRepository SyncRepository { get; set; }
  208. private ITVSeriesManager TVSeriesManager { get; set; }
  209. private ICollectionManager CollectionManager { get; set; }
  210. private readonly StartupOptions _startupOptions;
  211. private readonly string _remotePackageName;
  212. private readonly bool _supportsNativeWebSocket;
  213. /// <summary>
  214. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  215. /// </summary>
  216. /// <param name="applicationPaths">The application paths.</param>
  217. /// <param name="logManager">The log manager.</param>
  218. /// <param name="supportsRunningAsService">if set to <c>true</c> [supports running as service].</param>
  219. /// <param name="isRunningAsService">if set to <c>true</c> [is running as service].</param>
  220. /// <param name="options">The options.</param>
  221. /// <param name="fileSystem">The file system.</param>
  222. /// <param name="remotePackageName">Name of the remote package.</param>
  223. public ApplicationHost(ServerApplicationPaths applicationPaths,
  224. ILogManager logManager,
  225. bool supportsRunningAsService,
  226. bool isRunningAsService,
  227. StartupOptions options,
  228. IFileSystem fileSystem,
  229. string remotePackageName,
  230. bool supportsNativeWebSocket)
  231. : base(applicationPaths, logManager, fileSystem)
  232. {
  233. _startupOptions = options;
  234. _remotePackageName = remotePackageName;
  235. _supportsNativeWebSocket = supportsNativeWebSocket;
  236. _isRunningAsService = isRunningAsService;
  237. SupportsRunningAsService = supportsRunningAsService;
  238. }
  239. private readonly bool _isRunningAsService;
  240. public override bool IsRunningAsService
  241. {
  242. get { return _isRunningAsService; }
  243. }
  244. public bool SupportsRunningAsService { get; private set; }
  245. /// <summary>
  246. /// Gets the name.
  247. /// </summary>
  248. /// <value>The name.</value>
  249. public override string Name
  250. {
  251. get
  252. {
  253. return "Media Browser Server";
  254. }
  255. }
  256. /// <summary>
  257. /// Gets a value indicating whether this instance can self restart.
  258. /// </summary>
  259. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  260. public override bool CanSelfRestart
  261. {
  262. get { return NativeApp.CanSelfRestart; }
  263. }
  264. public bool SupportsAutoRunAtStartup
  265. {
  266. get { return NativeApp.SupportsAutoRunAtStartup; }
  267. }
  268. /// <summary>
  269. /// Runs the startup tasks.
  270. /// </summary>
  271. /// <returns>Task.</returns>
  272. public override async Task RunStartupTasks()
  273. {
  274. await base.RunStartupTasks().ConfigureAwait(false);
  275. Logger.Info("Core startup complete");
  276. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  277. {
  278. try
  279. {
  280. entryPoint.Run();
  281. }
  282. catch (Exception ex)
  283. {
  284. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  285. }
  286. });
  287. LogManager.RemoveConsoleOutput();
  288. }
  289. public override async Task Init(IProgress<double> progress)
  290. {
  291. PerformVersionMigration();
  292. await base.Init(progress).ConfigureAwait(false);
  293. }
  294. private void PerformVersionMigration()
  295. {
  296. DeleteDeprecatedModules();
  297. }
  298. private void DeleteDeprecatedModules()
  299. {
  300. try
  301. {
  302. MigrateUserFolders();
  303. }
  304. catch (IOException)
  305. {
  306. }
  307. try
  308. {
  309. File.Delete(Path.Combine(ApplicationPaths.PluginsPath, "MBPhoto.dll"));
  310. }
  311. catch (IOException)
  312. {
  313. // Not there, no big deal
  314. }
  315. try
  316. {
  317. File.Delete(Path.Combine(ApplicationPaths.PluginsPath, "MediaBrowser.Plugins.XbmcMetadata.dll"));
  318. }
  319. catch (IOException)
  320. {
  321. // Not there, no big deal
  322. }
  323. }
  324. private void MigrateUserFolders()
  325. {
  326. var rootPath = ApplicationPaths.RootFolderPath;
  327. var folders = new DirectoryInfo(rootPath).EnumerateDirectories("*", SearchOption.TopDirectoryOnly).Where(i => !string.Equals(i.Name, "default", StringComparison.OrdinalIgnoreCase))
  328. .ToList();
  329. foreach (var folder in folders)
  330. {
  331. Directory.Delete(folder.FullName, true);
  332. }
  333. }
  334. /// <summary>
  335. /// Registers resources that classes will depend on
  336. /// </summary>
  337. /// <returns>Task.</returns>
  338. protected override async Task RegisterResources(IProgress<double> progress)
  339. {
  340. await base.RegisterResources(progress).ConfigureAwait(false);
  341. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer));
  342. RegisterSingleInstance<IServerApplicationHost>(this);
  343. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  344. RegisterSingleInstance(ServerConfigurationManager);
  345. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer);
  346. RegisterSingleInstance(LocalizationManager);
  347. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  348. UserDataManager = new UserDataManager(LogManager);
  349. RegisterSingleInstance(UserDataManager);
  350. UserRepository = await GetUserRepository().ConfigureAwait(false);
  351. RegisterSingleInstance(UserRepository);
  352. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  353. RegisterSingleInstance(DisplayPreferencesRepository);
  354. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  355. RegisterSingleInstance(ItemRepository);
  356. ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
  357. RegisterSingleInstance(ProviderRepository);
  358. FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);
  359. RegisterSingleInstance(FileOrganizationRepository);
  360. AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);
  361. RegisterSingleInstance(AuthenticationRepository);
  362. //SyncRepository = await GetSyncRepository().ConfigureAwait(false);
  363. //RegisterSingleInstance(SyncRepository);
  364. UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService);
  365. RegisterSingleInstance(UserManager);
  366. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
  367. RegisterSingleInstance(LibraryManager);
  368. var musicManager = new MusicManager(LibraryManager);
  369. RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
  370. LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  371. RegisterSingleInstance(LibraryMonitor);
  372. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
  373. RegisterSingleInstance(ProviderManager);
  374. SeriesOrderManager = new SeriesOrderManager();
  375. RegisterSingleInstance(SeriesOrderManager);
  376. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
  377. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html", _supportsNativeWebSocket);
  378. RegisterSingleInstance(HttpServer, false);
  379. progress.Report(10);
  380. ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
  381. RegisterSingleInstance(ServerManager);
  382. var innerProgress = new ActionableProgress<double>();
  383. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  384. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  385. progress.Report(90);
  386. ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder);
  387. RegisterSingleInstance(ImageProcessor);
  388. SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"));
  389. RegisterSingleInstance(SyncManager);
  390. DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager);
  391. RegisterSingleInstance(DtoService);
  392. var encryptionManager = new EncryptionManager();
  393. RegisterSingleInstance<IEncryptionManager>(encryptionManager);
  394. ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager);
  395. RegisterSingleInstance(ConnectManager);
  396. DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer), UserManager, FileSystemManager, LibraryMonitor, ConfigurationManager, LogManager.GetLogger("DeviceManager"));
  397. RegisterSingleInstance(DeviceManager);
  398. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager);
  399. RegisterSingleInstance(SessionManager);
  400. var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  401. RegisterSingleInstance<INewsService>(newsService);
  402. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  403. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  404. progress.Report(15);
  405. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient);
  406. RegisterSingleInstance(ChannelManager);
  407. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager);
  408. RegisterSingleInstance(TVSeriesManager);
  409. var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);
  410. RegisterSingleInstance<IAppThemeManager>(appThemeManager);
  411. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer);
  412. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  413. var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient);
  414. RegisterSingleInstance<IConnectionManager>(connectionManager);
  415. CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"));
  416. RegisterSingleInstance(CollectionManager);
  417. var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager);
  418. RegisterSingleInstance<IPlaylistManager>(playlistManager);
  419. LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer);
  420. RegisterSingleInstance(LiveTvManager);
  421. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager);
  422. RegisterSingleInstance(UserViewManager);
  423. var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager);
  424. RegisterSingleInstance<IContentDirectory>(contentDirectory);
  425. NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
  426. RegisterSingleInstance(NotificationManager);
  427. SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository);
  428. RegisterSingleInstance(SubtitleManager);
  429. ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
  430. RegisterSingleInstance(ChapterManager);
  431. EncodingManager = new EncodingManager(FileSystemManager, Logger,
  432. MediaEncoder, ChapterManager);
  433. RegisterSingleInstance(EncodingManager);
  434. var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);
  435. RegisterSingleInstance(activityLogRepo);
  436. RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));
  437. var authContext = new AuthorizationContext();
  438. RegisterSingleInstance<IAuthorizationContext>(authContext);
  439. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  440. RegisterSingleInstance<IAuthService>(new AuthService(UserManager, SessionManager, authContext, ServerConfigurationManager));
  441. RegisterSingleInstance<ISubtitleEncoder>(new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer));
  442. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  443. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  444. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  445. await ConfigureNotificationsRepository().ConfigureAwait(false);
  446. progress.Report(92);
  447. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  448. progress.Report(100);
  449. SetStaticProperties();
  450. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  451. SetKernelProperties();
  452. }
  453. protected override INetworkManager CreateNetworkManager(ILogger logger)
  454. {
  455. return new NetworkManager(logger);
  456. }
  457. /// <summary>
  458. /// Registers the media encoder.
  459. /// </summary>
  460. /// <returns>Task.</returns>
  461. private async Task RegisterMediaEncoder(IProgress<double> progress)
  462. {
  463. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo(_startupOptions, progress).ConfigureAwait(false);
  464. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), JsonSerializer, info.EncoderPath, info.ProbePath, info.Version);
  465. RegisterSingleInstance(MediaEncoder);
  466. }
  467. /// <summary>
  468. /// Sets the kernel properties.
  469. /// </summary>
  470. private void SetKernelProperties()
  471. {
  472. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  473. }
  474. /// <summary>
  475. /// Gets the user repository.
  476. /// </summary>
  477. /// <returns>Task{IUserRepository}.</returns>
  478. private async Task<IUserRepository> GetUserRepository()
  479. {
  480. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  481. await repo.Initialize().ConfigureAwait(false);
  482. return repo;
  483. }
  484. /// <summary>
  485. /// Gets the file organization repository.
  486. /// </summary>
  487. /// <returns>Task{IUserRepository}.</returns>
  488. private async Task<IFileOrganizationRepository> GetFileOrganizationRepository()
  489. {
  490. var repo = new SqliteFileOrganizationRepository(LogManager, ServerConfigurationManager.ApplicationPaths);
  491. await repo.Initialize().ConfigureAwait(false);
  492. return repo;
  493. }
  494. private async Task<IAuthenticationRepository> GetAuthenticationRepository()
  495. {
  496. var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager.ApplicationPaths);
  497. await repo.Initialize().ConfigureAwait(false);
  498. return repo;
  499. }
  500. private async Task<IActivityRepository> GetActivityLogRepository()
  501. {
  502. var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths);
  503. await repo.Initialize().ConfigureAwait(false);
  504. return repo;
  505. }
  506. private async Task<ISyncRepository> GetSyncRepository()
  507. {
  508. var repo = new SyncRepository(LogManager.GetLogger("SyncRepository"), ServerConfigurationManager.ApplicationPaths);
  509. await repo.Initialize().ConfigureAwait(false);
  510. return repo;
  511. }
  512. /// <summary>
  513. /// Configures the repositories.
  514. /// </summary>
  515. /// <returns>Task.</returns>
  516. private async Task ConfigureNotificationsRepository()
  517. {
  518. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  519. await repo.Initialize().ConfigureAwait(false);
  520. NotificationsRepository = repo;
  521. RegisterSingleInstance(NotificationsRepository);
  522. }
  523. /// <summary>
  524. /// Configures the repositories.
  525. /// </summary>
  526. /// <returns>Task.</returns>
  527. private async Task ConfigureDisplayPreferencesRepositories()
  528. {
  529. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  530. }
  531. /// <summary>
  532. /// Configures the item repositories.
  533. /// </summary>
  534. /// <returns>Task.</returns>
  535. private async Task ConfigureItemRepositories()
  536. {
  537. await ItemRepository.Initialize().ConfigureAwait(false);
  538. await ProviderRepository.Initialize().ConfigureAwait(false);
  539. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  540. }
  541. /// <summary>
  542. /// Configures the user data repositories.
  543. /// </summary>
  544. /// <returns>Task.</returns>
  545. private async Task ConfigureUserDataRepositories()
  546. {
  547. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  548. await repo.Initialize().ConfigureAwait(false);
  549. ((UserDataManager)UserDataManager).Repository = repo;
  550. }
  551. /// <summary>
  552. /// Dirty hacks
  553. /// </summary>
  554. private void SetStaticProperties()
  555. {
  556. // For now there's no real way to inject these properly
  557. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  558. BaseItem.ConfigurationManager = ServerConfigurationManager;
  559. BaseItem.LibraryManager = LibraryManager;
  560. BaseItem.ProviderManager = ProviderManager;
  561. BaseItem.LocalizationManager = LocalizationManager;
  562. BaseItem.ItemRepository = ItemRepository;
  563. User.XmlSerializer = XmlSerializer;
  564. User.UserManager = UserManager;
  565. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  566. Folder.UserManager = UserManager;
  567. BaseItem.FileSystem = FileSystemManager;
  568. BaseItem.UserDataManager = UserDataManager;
  569. BaseItem.ChannelManager = ChannelManager;
  570. BaseItem.LiveTvManager = LiveTvManager;
  571. Folder.UserViewManager = UserViewManager;
  572. UserView.TVSeriesManager = TVSeriesManager;
  573. BaseItem.CollectionManager = CollectionManager;
  574. }
  575. /// <summary>
  576. /// Finds the parts.
  577. /// </summary>
  578. protected override void FindParts()
  579. {
  580. if (IsFirstRun)
  581. {
  582. RegisterServerWithAdministratorAccess();
  583. }
  584. base.FindParts();
  585. HttpServer.Init(GetExports<IRestfulService>(false));
  586. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  587. StartServer(true);
  588. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  589. GetExports<IVirtualFolderCreator>(),
  590. GetExports<IItemResolver>(),
  591. GetExports<IIntroProvider>(),
  592. GetExports<IBaseItemComparer>(),
  593. GetExports<ILibraryPostScanTask>());
  594. ProviderManager.AddParts(GetExports<IImageProvider>(),
  595. GetExports<IMetadataService>(),
  596. GetExports<IItemIdentityProvider>(),
  597. GetExports<IItemIdentityConverter>(),
  598. GetExports<IMetadataProvider>(),
  599. GetExports<IMetadataSaver>(),
  600. GetExports<IImageSaver>(),
  601. GetExports<IExternalId>());
  602. SeriesOrderManager.AddParts(GetExports<ISeriesOrderProvider>());
  603. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  604. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  605. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  606. ChapterManager.AddParts(GetExports<IChapterProvider>());
  607. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  608. ChannelManager.AddParts(GetExports<IChannel>(), GetExports<IChannelFactory>());
  609. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  610. SyncManager.AddParts(GetExports<ISyncProvider>());
  611. }
  612. /// <summary>
  613. /// Starts the server.
  614. /// </summary>
  615. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  616. private void StartServer(bool retryOnFailure)
  617. {
  618. try
  619. {
  620. ServerManager.Start(HttpServerUrlPrefixes);
  621. }
  622. catch (Exception ex)
  623. {
  624. Logger.ErrorException("Error starting http server", ex);
  625. if (retryOnFailure)
  626. {
  627. RegisterServerWithAdministratorAccess();
  628. StartServer(false);
  629. }
  630. else
  631. {
  632. throw;
  633. }
  634. }
  635. }
  636. /// <summary>
  637. /// Called when [configuration updated].
  638. /// </summary>
  639. /// <param name="sender">The sender.</param>
  640. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  641. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  642. {
  643. base.OnConfigurationUpdated(sender, e);
  644. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  645. {
  646. NotifyPendingRestart();
  647. }
  648. }
  649. /// <summary>
  650. /// Restarts this instance.
  651. /// </summary>
  652. public override async Task Restart()
  653. {
  654. if (!CanSelfRestart)
  655. {
  656. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  657. }
  658. try
  659. {
  660. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  661. }
  662. catch (Exception ex)
  663. {
  664. Logger.ErrorException("Error sending server restart notification", ex);
  665. }
  666. Logger.Debug("Calling NativeApp.Restart");
  667. NativeApp.Restart();
  668. }
  669. /// <summary>
  670. /// Gets or sets a value indicating whether this instance can self update.
  671. /// </summary>
  672. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  673. public override bool CanSelfUpdate
  674. {
  675. get
  676. {
  677. #if DEBUG
  678. return false;
  679. #endif
  680. #pragma warning disable 162
  681. return NativeApp.CanSelfUpdate;
  682. #pragma warning restore 162
  683. }
  684. }
  685. /// <summary>
  686. /// Gets the composable part assemblies.
  687. /// </summary>
  688. /// <returns>IEnumerable{Assembly}.</returns>
  689. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  690. {
  691. var list = GetPluginAssemblies()
  692. .ToList();
  693. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  694. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  695. // Include composable parts in the Api assembly
  696. list.Add(typeof(ApiEntryPoint).Assembly);
  697. // Include composable parts in the Dashboard assembly
  698. list.Add(typeof(DashboardService).Assembly);
  699. // Include composable parts in the Model assembly
  700. list.Add(typeof(SystemInfo).Assembly);
  701. // Include composable parts in the Common assembly
  702. list.Add(typeof(IApplicationHost).Assembly);
  703. // Include composable parts in the Controller assembly
  704. list.Add(typeof(IServerApplicationHost).Assembly);
  705. // Include composable parts in the Providers assembly
  706. list.Add(typeof(ProviderUtils).Assembly);
  707. // Common implementations
  708. list.Add(typeof(TaskManager).Assembly);
  709. // Server implementations
  710. list.Add(typeof(ServerApplicationPaths).Assembly);
  711. // MediaEncoding
  712. list.Add(typeof(MediaEncoder).Assembly);
  713. // Dlna
  714. list.Add(typeof(DlnaEntryPoint).Assembly);
  715. // Local metadata
  716. list.Add(typeof(AlbumXmlProvider).Assembly);
  717. // Xbmc
  718. list.Add(typeof(ArtistNfoProvider).Assembly);
  719. list.AddRange(Assemblies.GetAssembliesWithParts());
  720. // Include composable parts in the running assembly
  721. list.Add(GetType().Assembly);
  722. return list;
  723. }
  724. /// <summary>
  725. /// Gets the plugin assemblies.
  726. /// </summary>
  727. /// <returns>IEnumerable{Assembly}.</returns>
  728. private IEnumerable<Assembly> GetPluginAssemblies()
  729. {
  730. try
  731. {
  732. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  733. .Select(LoadAssembly)
  734. .Where(a => a != null)
  735. .ToList();
  736. }
  737. catch (DirectoryNotFoundException)
  738. {
  739. return new List<Assembly>();
  740. }
  741. }
  742. /// <summary>
  743. /// Gets the system status.
  744. /// </summary>
  745. /// <returns>SystemInfo.</returns>
  746. public virtual SystemInfo GetSystemInfo()
  747. {
  748. return new SystemInfo
  749. {
  750. HasPendingRestart = HasPendingRestart,
  751. Version = ApplicationVersion.ToString(),
  752. IsNetworkDeployed = CanSelfUpdate,
  753. WebSocketPortNumber = HttpServerPort,
  754. SupportsNativeWebSocket = true,
  755. FailedPluginAssemblies = FailedAssemblies.ToList(),
  756. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  757. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  758. Id = SystemId,
  759. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  760. LogPath = ApplicationPaths.LogDirectoryPath,
  761. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  762. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  763. CachePath = ApplicationPaths.CachePath,
  764. MacAddress = GetMacAddress(),
  765. HttpServerPortNumber = HttpServerPort,
  766. OperatingSystem = Environment.OSVersion.ToString(),
  767. CanSelfRestart = CanSelfRestart,
  768. CanSelfUpdate = CanSelfUpdate,
  769. WanAddress = ConnectManager.WanApiAddress,
  770. HasUpdateAvailable = HasUpdateAvailable,
  771. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  772. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  773. IsRunningAsService = IsRunningAsService,
  774. SupportsRunningAsService = SupportsRunningAsService,
  775. ServerName = FriendlyName,
  776. LocalAddress = GetLocalIpAddress()
  777. };
  778. }
  779. /// <summary>
  780. /// Gets the local ip address.
  781. /// </summary>
  782. /// <returns>System.String.</returns>
  783. private string GetLocalIpAddress()
  784. {
  785. // Return the first matched address, if found, or the first known local address
  786. var address = HttpServerIpAddresses.FirstOrDefault();
  787. if (!string.IsNullOrWhiteSpace(address))
  788. {
  789. address = string.Format("http://{0}:{1}",
  790. address,
  791. ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(CultureInfo.InvariantCulture));
  792. }
  793. return address;
  794. }
  795. public IEnumerable<string> HttpServerIpAddresses
  796. {
  797. get
  798. {
  799. var localAddresses = NetworkManager.GetLocalIpAddresses()
  800. .ToList();
  801. if (localAddresses.Count < 2)
  802. {
  803. return localAddresses;
  804. }
  805. var httpServerAddresses = HttpServer.LocalEndPoints
  806. .Select(i => i.Split(':').FirstOrDefault())
  807. .Where(i => !string.IsNullOrEmpty(i))
  808. .ToList();
  809. // Cross-check the local ip addresses with addresses that have been received on with the http server
  810. var matchedAddresses = httpServerAddresses
  811. .Where(i => localAddresses.Contains(i, StringComparer.OrdinalIgnoreCase))
  812. .ToList();
  813. if (matchedAddresses.Count == 0)
  814. {
  815. return localAddresses.Take(1);
  816. }
  817. return matchedAddresses;
  818. }
  819. }
  820. public string FriendlyName
  821. {
  822. get
  823. {
  824. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  825. ? Environment.MachineName
  826. : ServerConfigurationManager.Configuration.ServerName;
  827. }
  828. }
  829. public int HttpServerPort
  830. {
  831. get { return ServerConfigurationManager.Configuration.HttpServerPortNumber; }
  832. }
  833. /// <summary>
  834. /// Gets the mac address.
  835. /// </summary>
  836. /// <returns>System.String.</returns>
  837. private string GetMacAddress()
  838. {
  839. try
  840. {
  841. return NetworkManager.GetMacAddress();
  842. }
  843. catch (Exception ex)
  844. {
  845. Logger.ErrorException("Error getting mac address", ex);
  846. return null;
  847. }
  848. }
  849. /// <summary>
  850. /// Shuts down.
  851. /// </summary>
  852. public override async Task Shutdown()
  853. {
  854. try
  855. {
  856. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  857. }
  858. catch (Exception ex)
  859. {
  860. Logger.ErrorException("Error sending server shutdown notification", ex);
  861. }
  862. NativeApp.Shutdown();
  863. }
  864. /// <summary>
  865. /// Registers the server with administrator access.
  866. /// </summary>
  867. private void RegisterServerWithAdministratorAccess()
  868. {
  869. Logger.Info("Requesting administrative access to authorize http server");
  870. try
  871. {
  872. ServerAuthorization.AuthorizeServer(
  873. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  874. HttpServerUrlPrefixes.First(),
  875. UdpServerEntryPoint.PortNumber,
  876. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  877. }
  878. catch (Exception ex)
  879. {
  880. Logger.ErrorException("Error authorizing server", ex);
  881. }
  882. }
  883. public event EventHandler HasUpdateAvailableChanged;
  884. private bool _hasUpdateAvailable;
  885. public bool HasUpdateAvailable
  886. {
  887. get { return _hasUpdateAvailable; }
  888. set
  889. {
  890. var fireEvent = value && !_hasUpdateAvailable;
  891. _hasUpdateAvailable = value;
  892. if (fireEvent)
  893. {
  894. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  895. }
  896. }
  897. }
  898. /// <summary>
  899. /// Checks for update.
  900. /// </summary>
  901. /// <param name="cancellationToken">The cancellation token.</param>
  902. /// <param name="progress">The progress.</param>
  903. /// <returns>Task{CheckForUpdateResult}.</returns>
  904. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  905. {
  906. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  907. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, _remotePackageName, null, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  908. var versionObject = version == null || string.IsNullOrWhiteSpace(version.versionStr) ? null : new Version(version.versionStr);
  909. var isUpdateAvailable = versionObject != null && versionObject > ApplicationVersion;
  910. var result = versionObject != null ?
  911. new CheckForUpdateResult { AvailableVersion = versionObject.ToString(), IsUpdateAvailable = isUpdateAvailable, Package = version } :
  912. new CheckForUpdateResult { AvailableVersion = ApplicationVersion.ToString(), IsUpdateAvailable = false };
  913. HasUpdateAvailable = result.IsUpdateAvailable;
  914. if (result.IsUpdateAvailable)
  915. {
  916. Logger.Info("New application version is available: {0}", result.AvailableVersion);
  917. }
  918. return result;
  919. }
  920. /// <summary>
  921. /// Updates the application.
  922. /// </summary>
  923. /// <param name="package">The package that contains the update</param>
  924. /// <param name="cancellationToken">The cancellation token.</param>
  925. /// <param name="progress">The progress.</param>
  926. /// <returns>Task.</returns>
  927. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  928. {
  929. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  930. HasUpdateAvailable = false;
  931. OnApplicationUpdated(package);
  932. }
  933. /// <summary>
  934. /// Configures the automatic run at startup.
  935. /// </summary>
  936. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  937. protected override void ConfigureAutoRunAtStartup(bool autorun)
  938. {
  939. if (SupportsAutoRunAtStartup)
  940. {
  941. Autorun.Configure(autorun);
  942. }
  943. }
  944. }
  945. }