ApplicationHost.cs 41 KB

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