2
0

ApplicationHost.cs 45 KB

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