ApplicationHost.cs 46 KB

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