ApplicationHost.cs 41 KB

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