ApplicationHost.cs 46 KB

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