ApplicationHost.cs 41 KB

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