ApplicationHost.cs 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547
  1. using Emby.Common.Implementations.Serialization;
  2. using Emby.Drawing;
  3. using Emby.Photos;
  4. using Emby.Dlna;
  5. using Emby.Dlna.Main;
  6. using Emby.Dlna.Ssdp;
  7. using Emby.Server.Implementations.Activity;
  8. using Emby.Server.Implementations.Archiving;
  9. using Emby.Server.Implementations.Channels;
  10. using Emby.Server.Implementations.Collections;
  11. using Emby.Server.Implementations.Configuration;
  12. using Emby.Server.Implementations.Cryptography;
  13. using Emby.Server.Implementations.Data;
  14. using Emby.Server.Implementations.Devices;
  15. using Emby.Server.Implementations.Diagnostics;
  16. using Emby.Server.Implementations.Dto;
  17. using Emby.Server.Implementations.FFMpeg;
  18. using Emby.Server.Implementations.HttpServer;
  19. using Emby.Server.Implementations.HttpServer.Security;
  20. using Emby.Server.Implementations.IO;
  21. using Emby.Server.Implementations.Library;
  22. using Emby.Server.Implementations.LiveTv;
  23. using Emby.Server.Implementations.Localization;
  24. using Emby.Server.Implementations.Net;
  25. using Emby.Notifications;
  26. using Emby.Server.Implementations.Playlists;
  27. using Emby.Server.Implementations.Reflection;
  28. using Emby.Server.Implementations.ScheduledTasks;
  29. using Emby.Server.Implementations.Security;
  30. using Emby.Server.Implementations.Serialization;
  31. using Emby.Server.Implementations.Session;
  32. using Emby.Server.Implementations.Threading;
  33. using Emby.Server.Implementations.TV;
  34. using Emby.Server.Implementations.Updates;
  35. using Emby.Server.Implementations.Xml;
  36. using MediaBrowser.Api;
  37. using MediaBrowser.Common;
  38. using MediaBrowser.Common.Configuration;
  39. using MediaBrowser.Common.Events;
  40. using MediaBrowser.Common.Extensions;
  41. using MediaBrowser.Common.Net;
  42. using MediaBrowser.Common.Plugins;
  43. using MediaBrowser.Model.Extensions;
  44. using MediaBrowser.Common.Security;
  45. using MediaBrowser.Common.Updates;
  46. using MediaBrowser.Controller;
  47. using MediaBrowser.Controller.Channels;
  48. using MediaBrowser.Controller.Chapters;
  49. using MediaBrowser.Controller.Collections;
  50. using MediaBrowser.Controller.Configuration;
  51. using MediaBrowser.Controller.Devices;
  52. using MediaBrowser.Controller.Dlna;
  53. using MediaBrowser.Controller.Drawing;
  54. using MediaBrowser.Controller.Dto;
  55. using MediaBrowser.Controller.Entities;
  56. using MediaBrowser.Controller.Library;
  57. using MediaBrowser.Controller.LiveTv;
  58. using MediaBrowser.Controller.MediaEncoding;
  59. using MediaBrowser.Controller.Net;
  60. using MediaBrowser.Controller.Notifications;
  61. using MediaBrowser.Controller.Persistence;
  62. using MediaBrowser.Controller.Playlists;
  63. using MediaBrowser.Controller.Plugins;
  64. using MediaBrowser.Controller.Providers;
  65. using MediaBrowser.Controller.Resolvers;
  66. using MediaBrowser.Controller.Security;
  67. using MediaBrowser.Controller.Session;
  68. using MediaBrowser.Controller.Sorting;
  69. using MediaBrowser.Controller.Subtitles;
  70. using MediaBrowser.Controller.TV;
  71. using MediaBrowser.LocalMetadata.Savers;
  72. using MediaBrowser.MediaEncoding.BdInfo;
  73. using MediaBrowser.Model.Activity;
  74. using MediaBrowser.Model.Configuration;
  75. using MediaBrowser.Model.Cryptography;
  76. using MediaBrowser.Model.Diagnostics;
  77. using MediaBrowser.Model.Dlna;
  78. using MediaBrowser.Model.Events;
  79. using MediaBrowser.Model.Globalization;
  80. using MediaBrowser.Model.IO;
  81. using MediaBrowser.Model.MediaInfo;
  82. using MediaBrowser.Model.Net;
  83. using MediaBrowser.Model.News;
  84. using MediaBrowser.Model.Reflection;
  85. using MediaBrowser.Model.Serialization;
  86. using MediaBrowser.Model.Services;
  87. using MediaBrowser.Model.System;
  88. using MediaBrowser.Model.Tasks;
  89. using MediaBrowser.Model.Text;
  90. using MediaBrowser.Model.Threading;
  91. using MediaBrowser.Model.Updates;
  92. using MediaBrowser.Model.Xml;
  93. using MediaBrowser.Providers.Chapters;
  94. using MediaBrowser.Providers.Manager;
  95. using MediaBrowser.Providers.Subtitles;
  96. using MediaBrowser.WebDashboard.Api;
  97. using MediaBrowser.XbmcMetadata.Providers;
  98. using ServiceStack;
  99. using System;
  100. using System.Collections.Concurrent;
  101. using System.Collections.Generic;
  102. using System.Globalization;
  103. using System.IO;
  104. using System.Linq;
  105. using System.Net;
  106. using System.Reflection;
  107. using System.Runtime.InteropServices;
  108. using System.Security.Cryptography.X509Certificates;
  109. using System.Text;
  110. using System.Threading;
  111. using System.Threading.Tasks;
  112. using StringExtensions = MediaBrowser.Controller.Extensions.StringExtensions;
  113. using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
  114. using MediaBrowser.Controller.Authentication;
  115. using System.Diagnostics;
  116. using ServiceStack.Text.Jsv;
  117. using Microsoft.Extensions.Logging;
  118. namespace Emby.Server.Implementations
  119. {
  120. /// <summary>
  121. /// Class CompositionRoot
  122. /// </summary>
  123. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  124. {
  125. /// <summary>
  126. /// Gets a value indicating whether this instance can self restart.
  127. /// </summary>
  128. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  129. public abstract bool CanSelfRestart { get; }
  130. /// <summary>
  131. /// Gets or sets a value indicating whether this instance can self update.
  132. /// </summary>
  133. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  134. public virtual bool CanSelfUpdate
  135. {
  136. get
  137. {
  138. return false;
  139. }
  140. }
  141. public virtual bool CanLaunchWebBrowser
  142. {
  143. get
  144. {
  145. if (!Environment.UserInteractive)
  146. {
  147. return false;
  148. }
  149. if (StartupOptions.ContainsOption("-service"))
  150. {
  151. return false;
  152. }
  153. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  154. {
  155. return true;
  156. }
  157. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
  158. {
  159. return true;
  160. }
  161. return false;
  162. }
  163. }
  164. /// <summary>
  165. /// Occurs when [has pending restart changed].
  166. /// </summary>
  167. public event EventHandler HasPendingRestartChanged;
  168. /// <summary>
  169. /// Occurs when [application updated].
  170. /// </summary>
  171. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  172. /// <summary>
  173. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  174. /// </summary>
  175. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  176. public bool HasPendingRestart { get; private set; }
  177. public bool IsShuttingDown { get; private set; }
  178. /// <summary>
  179. /// Gets or sets the logger.
  180. /// </summary>
  181. /// <value>The logger.</value>
  182. protected ILogger Logger { get; set; }
  183. /// <summary>
  184. /// Gets or sets the plugins.
  185. /// </summary>
  186. /// <value>The plugins.</value>
  187. public IPlugin[] Plugins { get; protected set; }
  188. /// <summary>
  189. /// Gets or sets the logger factory.
  190. /// </summary>
  191. /// <value>The logger factory.</value>
  192. public ILoggerFactory LoggerFactory { get; protected set; }
  193. /// <summary>
  194. /// Gets the application paths.
  195. /// </summary>
  196. /// <value>The application paths.</value>
  197. protected ServerApplicationPaths ApplicationPaths { get; set; }
  198. /// <summary>
  199. /// Gets all concrete types.
  200. /// </summary>
  201. /// <value>All concrete types.</value>
  202. public Tuple<Type, string>[] AllConcreteTypes { get; protected set; }
  203. /// <summary>
  204. /// The disposable parts
  205. /// </summary>
  206. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  207. /// <summary>
  208. /// Gets the configuration manager.
  209. /// </summary>
  210. /// <value>The configuration manager.</value>
  211. protected IConfigurationManager ConfigurationManager { get; set; }
  212. public IFileSystem FileSystemManager { get; set; }
  213. protected IEnvironmentInfo EnvironmentInfo { get; set; }
  214. private IBlurayExaminer BlurayExaminer { get; set; }
  215. public PackageVersionClass SystemUpdateLevel
  216. {
  217. get
  218. {
  219. #if BETA
  220. return PackageVersionClass.Beta;
  221. #endif
  222. return PackageVersionClass.Release;
  223. }
  224. }
  225. public virtual string OperatingSystemDisplayName
  226. {
  227. get { return EnvironmentInfo.OperatingSystemName; }
  228. }
  229. /// <summary>
  230. /// The container
  231. /// </summary>
  232. protected readonly SimpleInjector.Container Container = new SimpleInjector.Container();
  233. protected ISystemEvents SystemEvents { get; set; }
  234. /// <summary>
  235. /// Gets the server configuration manager.
  236. /// </summary>
  237. /// <value>The server configuration manager.</value>
  238. public IServerConfigurationManager ServerConfigurationManager
  239. {
  240. get { return (IServerConfigurationManager)ConfigurationManager; }
  241. }
  242. /// <summary>
  243. /// Gets the configuration manager.
  244. /// </summary>
  245. /// <returns>IConfigurationManager.</returns>
  246. protected IConfigurationManager GetConfigurationManager()
  247. {
  248. return new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  249. }
  250. protected virtual IResourceFileManager CreateResourceFileManager()
  251. {
  252. return new ResourceFileManager(HttpResultFactory, LoggerFactory.CreateLogger("ResourceManager"), FileSystemManager);
  253. }
  254. /// <summary>
  255. /// Gets or sets the user manager.
  256. /// </summary>
  257. /// <value>The user manager.</value>
  258. public IUserManager UserManager { get; set; }
  259. /// <summary>
  260. /// Gets or sets the library manager.
  261. /// </summary>
  262. /// <value>The library manager.</value>
  263. internal ILibraryManager LibraryManager { get; set; }
  264. /// <summary>
  265. /// Gets or sets the directory watchers.
  266. /// </summary>
  267. /// <value>The directory watchers.</value>
  268. private ILibraryMonitor LibraryMonitor { get; set; }
  269. /// <summary>
  270. /// Gets or sets the provider manager.
  271. /// </summary>
  272. /// <value>The provider manager.</value>
  273. private IProviderManager ProviderManager { get; set; }
  274. /// <summary>
  275. /// Gets or sets the HTTP server.
  276. /// </summary>
  277. /// <value>The HTTP server.</value>
  278. private IHttpServer HttpServer { get; set; }
  279. private IDtoService DtoService { get; set; }
  280. public IImageProcessor ImageProcessor { get; set; }
  281. /// <summary>
  282. /// Gets or sets the media encoder.
  283. /// </summary>
  284. /// <value>The media encoder.</value>
  285. private IMediaEncoder MediaEncoder { get; set; }
  286. private ISubtitleEncoder SubtitleEncoder { get; set; }
  287. private ISessionManager SessionManager { get; set; }
  288. private ILiveTvManager LiveTvManager { get; set; }
  289. public ILocalizationManager LocalizationManager { get; set; }
  290. private IEncodingManager EncodingManager { get; set; }
  291. private IChannelManager ChannelManager { get; set; }
  292. protected ITextEncoding TextEncoding { get; private set; }
  293. /// <summary>
  294. /// Gets or sets the user data repository.
  295. /// </summary>
  296. /// <value>The user data repository.</value>
  297. private IUserDataManager UserDataManager { get; set; }
  298. private IUserRepository UserRepository { get; set; }
  299. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  300. internal IItemRepository ItemRepository { get; set; }
  301. private INotificationManager NotificationManager { get; set; }
  302. private ISubtitleManager SubtitleManager { get; set; }
  303. private IChapterManager ChapterManager { get; set; }
  304. private IDeviceManager DeviceManager { get; set; }
  305. internal IUserViewManager UserViewManager { get; set; }
  306. private IAuthenticationRepository AuthenticationRepository { get; set; }
  307. private ITVSeriesManager TVSeriesManager { get; set; }
  308. private ICollectionManager CollectionManager { get; set; }
  309. private IMediaSourceManager MediaSourceManager { get; set; }
  310. private IPlaylistManager PlaylistManager { get; set; }
  311. /// <summary>
  312. /// Gets or sets the installation manager.
  313. /// </summary>
  314. /// <value>The installation manager.</value>
  315. protected IInstallationManager InstallationManager { get; private set; }
  316. /// <summary>
  317. /// Gets the security manager.
  318. /// </summary>
  319. /// <value>The security manager.</value>
  320. protected ISecurityManager SecurityManager { get; private set; }
  321. /// <summary>
  322. /// Gets or sets the zip client.
  323. /// </summary>
  324. /// <value>The zip client.</value>
  325. protected IZipClient ZipClient { get; private set; }
  326. protected IHttpResultFactory HttpResultFactory { get; private set; }
  327. protected IAuthService AuthService { get; private set; }
  328. public StartupOptions StartupOptions { get; private set; }
  329. protected readonly string ReleaseAssetFilename;
  330. internal IPowerManagement PowerManagement { get; private set; }
  331. internal IImageEncoder ImageEncoder { get; private set; }
  332. protected IProcessFactory ProcessFactory { get; private set; }
  333. protected ITimerFactory TimerFactory { get; private set; }
  334. protected ICryptoProvider CryptographyProvider = new CryptographyProvider();
  335. protected readonly IXmlSerializer XmlSerializer;
  336. protected ISocketFactory SocketFactory { get; private set; }
  337. protected ITaskManager TaskManager { get; private set; }
  338. public IHttpClient HttpClient { get; private set; }
  339. protected INetworkManager NetworkManager { get; set; }
  340. public IJsonSerializer JsonSerializer { get; private set; }
  341. protected IIsoManager IsoManager { get; private set; }
  342. /// <summary>
  343. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  344. /// </summary>
  345. public ApplicationHost(ServerApplicationPaths applicationPaths,
  346. ILoggerFactory loggerFactory,
  347. StartupOptions options,
  348. IFileSystem fileSystem,
  349. IPowerManagement powerManagement,
  350. string releaseAssetFilename,
  351. IEnvironmentInfo environmentInfo,
  352. IImageEncoder imageEncoder,
  353. ISystemEvents systemEvents,
  354. INetworkManager networkManager)
  355. {
  356. // hack alert, until common can target .net core
  357. BaseExtensions.CryptographyProvider = CryptographyProvider;
  358. XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory.CreateLogger("XmlSerializer"));
  359. NetworkManager = networkManager;
  360. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  361. EnvironmentInfo = environmentInfo;
  362. SystemEvents = systemEvents;
  363. ApplicationPaths = applicationPaths;
  364. LoggerFactory = loggerFactory;
  365. FileSystemManager = fileSystem;
  366. ConfigurationManager = GetConfigurationManager();
  367. Logger = LoggerFactory.CreateLogger("App");
  368. StartupOptions = options;
  369. ReleaseAssetFilename = releaseAssetFilename;
  370. PowerManagement = powerManagement;
  371. ImageEncoder = imageEncoder;
  372. //SetBaseExceptionMessage();
  373. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  374. NetworkManager.NetworkChanged += NetworkManager_NetworkChanged;
  375. }
  376. public string ExpandVirtualPath(string path)
  377. {
  378. var appPaths = ApplicationPaths;
  379. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  380. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  381. }
  382. public string ReverseVirtualPath(string path)
  383. {
  384. var appPaths = ApplicationPaths;
  385. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  386. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  387. }
  388. private string[] GetConfiguredLocalSubnets()
  389. {
  390. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  391. }
  392. private void NetworkManager_NetworkChanged(object sender, EventArgs e)
  393. {
  394. _validAddressResults.Clear();
  395. }
  396. private Version _version;
  397. /// <summary>
  398. /// Gets the current application version
  399. /// </summary>
  400. /// <value>The application version.</value>
  401. public Version ApplicationVersion
  402. {
  403. get
  404. {
  405. return _version ?? (_version = typeof(ApplicationHost).Assembly.GetName().Version);
  406. }
  407. }
  408. private DeviceId _deviceId;
  409. public string SystemId
  410. {
  411. get
  412. {
  413. if (_deviceId == null)
  414. {
  415. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger("SystemId"), FileSystemManager);
  416. }
  417. return _deviceId.Value;
  418. }
  419. }
  420. /// <summary>
  421. /// Gets the name.
  422. /// </summary>
  423. /// <value>The name.</value>
  424. public string Name
  425. {
  426. get
  427. {
  428. return "Emby Server";
  429. }
  430. }
  431. private Tuple<Assembly, string> GetAssembly(Type type)
  432. {
  433. var assembly = type.GetTypeInfo().Assembly;
  434. string path = null;
  435. return new Tuple<Assembly, string>(assembly, path);
  436. }
  437. public virtual IStreamHelper CreateStreamHelper()
  438. {
  439. return new StreamHelper();
  440. }
  441. public virtual bool SupportsAutoRunAtStartup
  442. {
  443. get
  444. {
  445. return EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
  446. }
  447. }
  448. /// <summary>
  449. /// Creates an instance of type and resolves all constructor dependancies
  450. /// </summary>
  451. /// <param name="type">The type.</param>
  452. /// <returns>System.Object.</returns>
  453. public object CreateInstance(Type type)
  454. {
  455. return Container.GetInstance(type);
  456. }
  457. /// <summary>
  458. /// Creates the instance safe.
  459. /// </summary>
  460. /// <param name="type">The type.</param>
  461. /// <returns>System.Object.</returns>
  462. protected object CreateInstanceSafe(Tuple<Type, string> typeInfo)
  463. {
  464. var type = typeInfo.Item1;
  465. try
  466. {
  467. return Container.GetInstance(type);
  468. }
  469. catch (Exception ex)
  470. {
  471. Logger.LogError(ex, "Error creating {type}", type.FullName);
  472. // Don't blow up in release mode
  473. return null;
  474. }
  475. }
  476. /// <summary>
  477. /// Registers the specified obj.
  478. /// </summary>
  479. /// <typeparam name="T"></typeparam>
  480. /// <param name="obj">The obj.</param>
  481. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  482. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  483. where T : class
  484. {
  485. Container.RegisterSingleton(obj);
  486. if (manageLifetime)
  487. {
  488. var disposable = obj as IDisposable;
  489. if (disposable != null)
  490. {
  491. DisposableParts.Add(disposable);
  492. }
  493. }
  494. }
  495. /// <summary>
  496. /// Registers the single instance.
  497. /// </summary>
  498. /// <typeparam name="T"></typeparam>
  499. /// <param name="func">The func.</param>
  500. protected void RegisterSingleInstance<T>(Func<T> func)
  501. where T : class
  502. {
  503. Container.RegisterSingleton(func);
  504. }
  505. /// <summary>
  506. /// Resolves this instance.
  507. /// </summary>
  508. /// <typeparam name="T"></typeparam>
  509. /// <returns>``0.</returns>
  510. public T Resolve<T>()
  511. {
  512. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  513. }
  514. /// <summary>
  515. /// Resolves this instance.
  516. /// </summary>
  517. /// <typeparam name="T"></typeparam>
  518. /// <returns>``0.</returns>
  519. public T TryResolve<T>()
  520. {
  521. var result = Container.GetRegistration(typeof(T), false);
  522. if (result == null)
  523. {
  524. return default(T);
  525. }
  526. return (T)result.GetInstance();
  527. }
  528. /// <summary>
  529. /// Loads the assembly.
  530. /// </summary>
  531. /// <param name="file">The file.</param>
  532. /// <returns>Assembly.</returns>
  533. protected Tuple<Assembly, string> LoadAssembly(string file)
  534. {
  535. try
  536. {
  537. var assembly = Assembly.Load(File.ReadAllBytes(file));
  538. return new Tuple<Assembly, string>(assembly, file);
  539. }
  540. catch (Exception ex)
  541. {
  542. Logger.LogError(ex, "Error loading assembly {file}", file);
  543. return null;
  544. }
  545. }
  546. /// <summary>
  547. /// Gets the export types.
  548. /// </summary>
  549. /// <typeparam name="T"></typeparam>
  550. /// <returns>IEnumerable{Type}.</returns>
  551. public IEnumerable<Tuple<Type, string>> GetExportTypes<T>()
  552. {
  553. var currentType = typeof(T);
  554. return AllConcreteTypes.Where(i => currentType.IsAssignableFrom(i.Item1));
  555. }
  556. /// <summary>
  557. /// Gets the exports.
  558. /// </summary>
  559. /// <typeparam name="T"></typeparam>
  560. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  561. /// <returns>IEnumerable{``0}.</returns>
  562. public IEnumerable<T> GetExports<T>(bool manageLifetime = true)
  563. {
  564. var parts = GetExportTypes<T>()
  565. .Select(CreateInstanceSafe)
  566. .Where(i => i != null)
  567. .Cast<T>()
  568. .ToList();
  569. if (manageLifetime)
  570. {
  571. lock (DisposableParts)
  572. {
  573. DisposableParts.AddRange(parts.OfType<IDisposable>());
  574. }
  575. }
  576. return parts;
  577. }
  578. public List<Tuple<T, string>> GetExportsWithInfo<T>(bool manageLifetime = true)
  579. {
  580. var parts = GetExportTypes<T>()
  581. .Select(i =>
  582. {
  583. var obj = CreateInstanceSafe(i);
  584. if (obj == null)
  585. {
  586. return null;
  587. }
  588. return new Tuple<T, string>((T)obj, i.Item2);
  589. })
  590. .Where(i => i != null)
  591. .ToList();
  592. if (manageLifetime)
  593. {
  594. lock (DisposableParts)
  595. {
  596. DisposableParts.AddRange(parts.Select(i => i.Item1).OfType<IDisposable>());
  597. }
  598. }
  599. return parts;
  600. }
  601. // TODO: @bond
  602. /*
  603. private void SetBaseExceptionMessage()
  604. {
  605. var builder = GetBaseExceptionMessage(ApplicationPaths);
  606. builder.Insert(0, string.Format("Version: {0}{1}", ApplicationVersion, Environment.NewLine));
  607. builder.Insert(0, "*** Error Report ***" + Environment.NewLine);
  608. LoggerFactory.ExceptionMessagePrefix = builder.ToString();
  609. }*/
  610. /// <summary>
  611. /// Runs the startup tasks.
  612. /// </summary>
  613. public async Task RunStartupTasks()
  614. {
  615. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  616. ConfigureAutorun();
  617. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  618. MediaEncoder.Init();
  619. //if (string.IsNullOrWhiteSpace(MediaEncoder.EncoderPath))
  620. //{
  621. // if (ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
  622. // {
  623. // ServerConfigurationManager.Configuration.IsStartupWizardCompleted = false;
  624. // ServerConfigurationManager.SaveConfiguration();
  625. // }
  626. //}
  627. Logger.LogInformation("ServerId: {0}", SystemId);
  628. var entryPoints = GetExports<IServerEntryPoint>();
  629. RunEntryPoints(entryPoints, true);
  630. Logger.LogInformation("Core startup complete");
  631. HttpServer.GlobalResponse = null;
  632. Logger.LogInformation("Post-init migrations complete");
  633. RunEntryPoints(entryPoints, false);
  634. Logger.LogInformation("All entry points have started");
  635. //LoggerFactory.RemoveConsoleOutput();
  636. }
  637. private void RunEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  638. {
  639. foreach (var entryPoint in entryPoints)
  640. {
  641. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  642. {
  643. continue;
  644. }
  645. var name = entryPoint.GetType().FullName;
  646. Logger.LogInformation("Starting entry point {0}", name);
  647. var now = DateTime.UtcNow;
  648. try
  649. {
  650. entryPoint.Run();
  651. }
  652. catch (Exception ex)
  653. {
  654. Logger.LogError(ex, "Error in {name}", name);
  655. }
  656. Logger.LogInformation("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos");
  657. }
  658. }
  659. /// <summary>
  660. /// Configures the autorun.
  661. /// </summary>
  662. private void ConfigureAutorun()
  663. {
  664. try
  665. {
  666. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  667. }
  668. catch (Exception ex)
  669. {
  670. Logger.LogError(ex, "Error configuring autorun");
  671. }
  672. }
  673. private IJsonSerializer CreateJsonSerializer()
  674. {
  675. return new JsonSerializer(FileSystemManager, LoggerFactory.CreateLogger("JsonSerializer"));
  676. }
  677. public void Init()
  678. {
  679. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  680. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  681. // Safeguard against invalid configuration
  682. if (HttpPort == HttpsPort)
  683. {
  684. HttpPort = ServerConfiguration.DefaultHttpPort;
  685. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  686. }
  687. JsonSerializer = CreateJsonSerializer();
  688. if (Plugins != null)
  689. {
  690. var pluginBuilder = new StringBuilder();
  691. foreach (var plugin in Plugins)
  692. {
  693. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  694. }
  695. Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString());
  696. }
  697. DiscoverTypes();
  698. SetHttpLimit();
  699. RegisterResources();
  700. FindParts();
  701. }
  702. protected virtual IHttpClient CreateHttpClient()
  703. {
  704. return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory.CreateLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent);
  705. }
  706. public static IStreamHelper StreamHelper { get; set; }
  707. /// <summary>
  708. /// Registers resources that classes will depend on
  709. /// </summary>
  710. protected void RegisterResources()
  711. {
  712. RegisterSingleInstance(ConfigurationManager);
  713. RegisterSingleInstance<IApplicationHost>(this);
  714. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  715. RegisterSingleInstance(JsonSerializer);
  716. RegisterSingleInstance(SystemEvents);
  717. RegisterSingleInstance(LoggerFactory, false);
  718. RegisterSingleInstance(Logger);
  719. RegisterSingleInstance(EnvironmentInfo);
  720. RegisterSingleInstance(FileSystemManager);
  721. HttpClient = CreateHttpClient();
  722. RegisterSingleInstance(HttpClient);
  723. RegisterSingleInstance(NetworkManager);
  724. IsoManager = new IsoManager();
  725. RegisterSingleInstance(IsoManager);
  726. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory.CreateLogger("TaskManager"), FileSystemManager, SystemEvents);
  727. RegisterSingleInstance(TaskManager);
  728. RegisterSingleInstance(XmlSerializer);
  729. ProcessFactory = new ProcessFactory();
  730. RegisterSingleInstance(ProcessFactory);
  731. TimerFactory = new TimerFactory();
  732. RegisterSingleInstance(TimerFactory);
  733. var streamHelper = CreateStreamHelper();
  734. ApplicationHost.StreamHelper = streamHelper;
  735. RegisterSingleInstance(streamHelper);
  736. RegisterSingleInstance(CryptographyProvider);
  737. SocketFactory = new SocketFactory(LoggerFactory.CreateLogger("SocketFactory"));
  738. RegisterSingleInstance(SocketFactory);
  739. RegisterSingleInstance(PowerManagement);
  740. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LoggerFactory, FileSystemManager, CryptographyProvider);
  741. RegisterSingleInstance(SecurityManager);
  742. InstallationManager = new InstallationManager(LoggerFactory.CreateLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime);
  743. RegisterSingleInstance(InstallationManager);
  744. ZipClient = new ZipClient(FileSystemManager);
  745. RegisterSingleInstance(ZipClient);
  746. HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, CreateBrotliCompressor());
  747. RegisterSingleInstance(HttpResultFactory);
  748. RegisterSingleInstance<IServerApplicationHost>(this);
  749. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  750. RegisterSingleInstance(ServerConfigurationManager);
  751. IAssemblyInfo assemblyInfo = new AssemblyInfo();
  752. RegisterSingleInstance<IAssemblyInfo>(assemblyInfo);
  753. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory.CreateLogger("LocalizationManager"), assemblyInfo, new TextLocalizer());
  754. StringExtensions.LocalizationManager = LocalizationManager;
  755. RegisterSingleInstance(LocalizationManager);
  756. TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LoggerFactory.CreateLogger("TextEncoding"), JsonSerializer);
  757. RegisterSingleInstance(TextEncoding);
  758. BlurayExaminer = new BdInfoExaminer(FileSystemManager, TextEncoding);
  759. RegisterSingleInstance(BlurayExaminer);
  760. RegisterSingleInstance<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
  761. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  762. RegisterSingleInstance(UserDataManager);
  763. UserRepository = GetUserRepository();
  764. // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it
  765. RegisterSingleInstance(UserRepository);
  766. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory.CreateLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager);
  767. DisplayPreferencesRepository = displayPreferencesRepo;
  768. RegisterSingleInstance(DisplayPreferencesRepository);
  769. var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory.CreateLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory);
  770. ItemRepository = itemRepo;
  771. RegisterSingleInstance(ItemRepository);
  772. AuthenticationRepository = GetAuthenticationRepository();
  773. RegisterSingleInstance(AuthenticationRepository);
  774. UserManager = new UserManager(LoggerFactory.CreateLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider);
  775. RegisterSingleInstance(UserManager);
  776. LibraryManager = new LibraryManager(this, Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  777. RegisterSingleInstance(LibraryManager);
  778. var musicManager = new MusicManager(LibraryManager);
  779. RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
  780. LibraryMonitor = new LibraryMonitor(LoggerFactory, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo);
  781. RegisterSingleInstance(LibraryMonitor);
  782. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  783. CertificateInfo = GetCertificateInfo(true);
  784. Certificate = GetCertificate(CertificateInfo);
  785. HttpServer = new HttpListenerHost(this,
  786. LoggerFactory.CreateLogger("HttpServer"),
  787. ServerConfigurationManager,
  788. "web/index.html",
  789. NetworkManager,
  790. TextEncoding,
  791. JsonSerializer,
  792. XmlSerializer,
  793. GetParseFn);
  794. HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  795. RegisterSingleInstance(HttpServer);
  796. ImageProcessor = GetImageProcessor();
  797. RegisterSingleInstance(ImageProcessor);
  798. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  799. RegisterSingleInstance(TVSeriesManager);
  800. var encryptionManager = new EncryptionManager();
  801. RegisterSingleInstance<IEncryptionManager>(encryptionManager);
  802. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory.CreateLogger("DeviceManager"), NetworkManager);
  803. RegisterSingleInstance(DeviceManager);
  804. var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  805. RegisterSingleInstance<INewsService>(newsService);
  806. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory.CreateLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder);
  807. RegisterSingleInstance(MediaSourceManager);
  808. SubtitleManager = new SubtitleManager(LoggerFactory.CreateLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager);
  809. RegisterSingleInstance(SubtitleManager);
  810. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  811. RegisterSingleInstance(ProviderManager);
  812. DtoService = new DtoService(LoggerFactory.CreateLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager);
  813. RegisterSingleInstance(DtoService);
  814. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory.CreateLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
  815. RegisterSingleInstance(ChannelManager);
  816. SessionManager = new SessionManager(UserDataManager, LoggerFactory.CreateLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory);
  817. RegisterSingleInstance(SessionManager);
  818. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory.CreateLogger("Dlna"), JsonSerializer, this, assemblyInfo);
  819. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  820. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("CollectionManager"), ProviderManager);
  821. RegisterSingleInstance(CollectionManager);
  822. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("PlaylistManager"), UserManager, ProviderManager);
  823. RegisterSingleInstance<IPlaylistManager>(PlaylistManager);
  824. LiveTvManager = new LiveTvManager(this, HttpClient, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager, () => ChannelManager);
  825. RegisterSingleInstance(LiveTvManager);
  826. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  827. RegisterSingleInstance(UserViewManager);
  828. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  829. RegisterSingleInstance(NotificationManager);
  830. RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LoggerFactory.CreateLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory));
  831. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory.CreateLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
  832. RegisterSingleInstance(ChapterManager);
  833. RegisterMediaEncoder(assemblyInfo);
  834. EncodingManager = new Emby.Server.Implementations.MediaEncoder.EncodingManager(FileSystemManager, Logger, MediaEncoder, ChapterManager, LibraryManager);
  835. RegisterSingleInstance(EncodingManager);
  836. var activityLogRepo = GetActivityLogRepository();
  837. RegisterSingleInstance(activityLogRepo);
  838. RegisterSingleInstance<IActivityManager>(new ActivityManager(LoggerFactory.CreateLogger("ActivityManager"), activityLogRepo, UserManager));
  839. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  840. RegisterSingleInstance<IAuthorizationContext>(authContext);
  841. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  842. AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  843. RegisterSingleInstance<IAuthService>(AuthService);
  844. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory.CreateLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding);
  845. RegisterSingleInstance(SubtitleEncoder);
  846. RegisterSingleInstance(CreateResourceFileManager());
  847. displayPreferencesRepo.Initialize();
  848. var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager);
  849. SetStaticProperties();
  850. ((UserManager)UserManager).Initialize();
  851. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  852. itemRepo.Initialize(userDataRepo, UserManager);
  853. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  854. }
  855. protected virtual IBrotliCompressor CreateBrotliCompressor()
  856. {
  857. return null;
  858. }
  859. private static Func<string, object> GetParseFn(Type propertyType)
  860. {
  861. return s => JsvReader.GetParseFn(propertyType)(s);
  862. }
  863. public virtual string PackageRuntime
  864. {
  865. get
  866. {
  867. return "netcore";
  868. }
  869. }
  870. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo)
  871. {
  872. // Distinct these to prevent users from reporting problems that aren't actually problems
  873. var commandLineArgs = Environment
  874. .GetCommandLineArgs()
  875. .Distinct();
  876. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  877. logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion);
  878. logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture);
  879. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  880. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  881. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  882. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  883. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  884. }
  885. private void SetHttpLimit()
  886. {
  887. try
  888. {
  889. // Increase the max http request limit
  890. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  891. }
  892. catch (Exception ex)
  893. {
  894. Logger.LogError(ex, "Error setting http limit");
  895. }
  896. }
  897. protected string GetDefaultUserAgent()
  898. {
  899. var name = FormatAttribute(Name);
  900. return name + "/" + ApplicationVersion;
  901. }
  902. private string FormatAttribute(string str)
  903. {
  904. var arr = str.ToCharArray();
  905. arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
  906. || char.IsWhiteSpace(c))));
  907. var result = new string(arr);
  908. if (string.IsNullOrWhiteSpace(result))
  909. {
  910. result = "Emby";
  911. }
  912. return result;
  913. }
  914. protected virtual bool SupportsDualModeSockets
  915. {
  916. get
  917. {
  918. return true;
  919. }
  920. }
  921. private X509Certificate GetCertificate(CertificateInfo info)
  922. {
  923. var certificateLocation = info == null ? null : info.Path;
  924. if (string.IsNullOrWhiteSpace(certificateLocation))
  925. {
  926. return null;
  927. }
  928. try
  929. {
  930. if (!FileSystemManager.FileExists(certificateLocation))
  931. {
  932. return null;
  933. }
  934. // Don't use an empty string password
  935. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  936. X509Certificate2 localCert = new X509Certificate2(certificateLocation, password);
  937. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  938. if (!localCert.HasPrivateKey)
  939. {
  940. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  941. return null;
  942. }
  943. return localCert;
  944. }
  945. catch (Exception ex)
  946. {
  947. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  948. return null;
  949. }
  950. }
  951. private IImageProcessor GetImageProcessor()
  952. {
  953. return new ImageProcessor(LoggerFactory.CreateLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder);
  954. }
  955. protected virtual FFMpegInstallInfo GetFfmpegInstallInfo()
  956. {
  957. var info = new FFMpegInstallInfo();
  958. // Windows builds: http://ffmpeg.zeranoe.com/builds/
  959. // Linux builds: http://johnvansickle.com/ffmpeg/
  960. // OS X builds: http://ffmpegmac.net/
  961. // OS X x64: http://www.evermeet.cx/ffmpeg/
  962. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux)
  963. {
  964. info.FFMpegFilename = "ffmpeg";
  965. info.FFProbeFilename = "ffprobe";
  966. info.ArchiveType = "7z";
  967. info.Version = "20170308";
  968. }
  969. else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  970. {
  971. info.FFMpegFilename = "ffmpeg.exe";
  972. info.FFProbeFilename = "ffprobe.exe";
  973. info.Version = "20170308";
  974. info.ArchiveType = "7z";
  975. }
  976. else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
  977. {
  978. info.FFMpegFilename = "ffmpeg";
  979. info.FFProbeFilename = "ffprobe";
  980. info.ArchiveType = "7z";
  981. info.Version = "20170308";
  982. }
  983. return info;
  984. }
  985. protected virtual FFMpegInfo GetFFMpegInfo()
  986. {
  987. return new FFMpegLoader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager, GetFfmpegInstallInfo())
  988. .GetFFMpegInfo(StartupOptions);
  989. }
  990. /// <summary>
  991. /// Registers the media encoder.
  992. /// </summary>
  993. /// <returns>Task.</returns>
  994. private void RegisterMediaEncoder(IAssemblyInfo assemblyInfo)
  995. {
  996. string encoderPath = null;
  997. string probePath = null;
  998. var info = GetFFMpegInfo();
  999. encoderPath = info.EncoderPath;
  1000. probePath = info.ProbePath;
  1001. var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase);
  1002. var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  1003. LoggerFactory.CreateLogger("MediaEncoder"),
  1004. JsonSerializer,
  1005. encoderPath,
  1006. probePath,
  1007. hasExternalEncoder,
  1008. ServerConfigurationManager,
  1009. FileSystemManager,
  1010. LiveTvManager,
  1011. IsoManager,
  1012. LibraryManager,
  1013. ChannelManager,
  1014. SessionManager,
  1015. () => SubtitleEncoder,
  1016. () => MediaSourceManager,
  1017. HttpClient,
  1018. ZipClient,
  1019. ProcessFactory,
  1020. 5000, false,
  1021. EnvironmentInfo);
  1022. MediaEncoder = mediaEncoder;
  1023. RegisterSingleInstance(MediaEncoder);
  1024. }
  1025. /// <summary>
  1026. /// Gets the user repository.
  1027. /// </summary>
  1028. /// <returns>Task{IUserRepository}.</returns>
  1029. private IUserRepository GetUserRepository()
  1030. {
  1031. var repo = new SqliteUserRepository(LoggerFactory.CreateLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer);
  1032. repo.Initialize();
  1033. return repo;
  1034. }
  1035. private IAuthenticationRepository GetAuthenticationRepository()
  1036. {
  1037. var repo = new AuthenticationRepository(LoggerFactory.CreateLogger("AuthenticationRepository"), ServerConfigurationManager);
  1038. repo.Initialize();
  1039. return repo;
  1040. }
  1041. private IActivityRepository GetActivityLogRepository()
  1042. {
  1043. var repo = new ActivityRepository(LoggerFactory.CreateLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  1044. repo.Initialize();
  1045. return repo;
  1046. }
  1047. /// <summary>
  1048. /// Dirty hacks
  1049. /// </summary>
  1050. private void SetStaticProperties()
  1051. {
  1052. ((SqliteItemRepository)ItemRepository).ImageProcessor = ImageProcessor;
  1053. // For now there's no real way to inject these properly
  1054. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  1055. BaseItem.ConfigurationManager = ServerConfigurationManager;
  1056. BaseItem.LibraryManager = LibraryManager;
  1057. BaseItem.ProviderManager = ProviderManager;
  1058. BaseItem.LocalizationManager = LocalizationManager;
  1059. BaseItem.ItemRepository = ItemRepository;
  1060. User.UserManager = UserManager;
  1061. BaseItem.FileSystem = FileSystemManager;
  1062. BaseItem.UserDataManager = UserDataManager;
  1063. BaseItem.ChannelManager = ChannelManager;
  1064. Video.LiveTvManager = LiveTvManager;
  1065. Folder.UserViewManager = UserViewManager;
  1066. UserView.TVSeriesManager = TVSeriesManager;
  1067. UserView.PlaylistManager = PlaylistManager;
  1068. UserView.CollectionManager = CollectionManager;
  1069. BaseItem.MediaSourceManager = MediaSourceManager;
  1070. CollectionFolder.XmlSerializer = XmlSerializer;
  1071. CollectionFolder.JsonSerializer = JsonSerializer;
  1072. CollectionFolder.ApplicationHost = this;
  1073. AuthenticatedAttribute.AuthService = AuthService;
  1074. }
  1075. /// <summary>
  1076. /// Finds the parts.
  1077. /// </summary>
  1078. protected void FindParts()
  1079. {
  1080. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  1081. {
  1082. RegisterServerWithAdministratorAccess();
  1083. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  1084. ConfigurationManager.SaveConfiguration();
  1085. }
  1086. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  1087. Plugins = GetExportsWithInfo<IPlugin>().Select(LoadPlugin).Where(i => i != null).ToArray();
  1088. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>());
  1089. StartServer();
  1090. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  1091. GetExports<IItemResolver>(),
  1092. GetExports<IIntroProvider>(),
  1093. GetExports<IBaseItemComparer>(),
  1094. GetExports<ILibraryPostScanTask>());
  1095. ProviderManager.AddParts(GetExports<IImageProvider>(),
  1096. GetExports<IMetadataService>(),
  1097. GetExports<IMetadataProvider>(),
  1098. GetExports<IMetadataSaver>(),
  1099. GetExports<IExternalId>());
  1100. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  1101. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  1102. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  1103. ChannelManager.AddParts(GetExports<IChannel>());
  1104. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  1105. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  1106. UserManager.AddParts(GetExports<IAuthenticationProvider>());
  1107. IsoManager.AddParts(GetExports<IIsoMounter>());
  1108. }
  1109. private IPlugin LoadPlugin(Tuple<IPlugin, string> info)
  1110. {
  1111. var plugin = info.Item1;
  1112. var assemblyFilePath = info.Item2;
  1113. try
  1114. {
  1115. var assemblyPlugin = plugin as IPluginAssembly;
  1116. if (assemblyPlugin != null)
  1117. {
  1118. var assembly = plugin.GetType().Assembly;
  1119. var assemblyName = assembly.GetName();
  1120. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  1121. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  1122. try
  1123. {
  1124. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  1125. if (idAttributes.Length > 0)
  1126. {
  1127. var attribute = (GuidAttribute)idAttributes[0];
  1128. var assemblyId = new Guid(attribute.Value);
  1129. assemblyPlugin.SetId(assemblyId);
  1130. }
  1131. }
  1132. catch (Exception ex)
  1133. {
  1134. Logger.LogError(ex, "Error getting plugin Id from {pluginName}.", plugin.GetType().FullName);
  1135. }
  1136. }
  1137. var hasPluginConfiguration = plugin as IHasPluginConfiguration;
  1138. if (hasPluginConfiguration != null)
  1139. {
  1140. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  1141. }
  1142. }
  1143. catch (Exception ex)
  1144. {
  1145. Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName);
  1146. return null;
  1147. }
  1148. return plugin;
  1149. }
  1150. /// <summary>
  1151. /// Discovers the types.
  1152. /// </summary>
  1153. protected void DiscoverTypes()
  1154. {
  1155. Logger.LogInformation("Loading assemblies");
  1156. var assemblyInfos = GetComposablePartAssemblies();
  1157. foreach (var assemblyInfo in assemblyInfos)
  1158. {
  1159. var assembly = assemblyInfo.Item1;
  1160. var path = assemblyInfo.Item2;
  1161. if (path == null)
  1162. {
  1163. Logger.LogInformation("Loading {assemblyName}", assembly.FullName);
  1164. }
  1165. else
  1166. {
  1167. Logger.LogInformation("Loading {assemblyName} from {path}", assembly.FullName, path);
  1168. }
  1169. }
  1170. AllConcreteTypes = assemblyInfos
  1171. .SelectMany(GetTypes)
  1172. .Where(info =>
  1173. {
  1174. var t = info.Item1;
  1175. return t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType;
  1176. })
  1177. .ToArray();
  1178. }
  1179. /// <summary>
  1180. /// Gets a list of types within an assembly
  1181. /// This will handle situations that would normally throw an exception - such as a type within the assembly that depends on some other non-existant reference
  1182. /// </summary>
  1183. protected List<Tuple<Type, string>> GetTypes(Tuple<Assembly, string> assemblyInfo)
  1184. {
  1185. if (assemblyInfo == null)
  1186. {
  1187. return new List<Tuple<Type, string>>();
  1188. }
  1189. var assembly = assemblyInfo.Item1;
  1190. try
  1191. {
  1192. // This null checking really shouldn't be needed but adding it due to some
  1193. // unhandled exceptions in mono 5.0 that are a little hard to hunt down
  1194. var types = assembly.GetTypes() ?? new Type[] { };
  1195. return types.Where(t => t != null).Select(i => new Tuple<Type, string>(i, assemblyInfo.Item2)).ToList();
  1196. }
  1197. catch (ReflectionTypeLoadException ex)
  1198. {
  1199. if (ex.LoaderExceptions != null)
  1200. {
  1201. foreach (var loaderException in ex.LoaderExceptions)
  1202. {
  1203. if (loaderException != null)
  1204. {
  1205. Logger.LogError("LoaderException: " + loaderException.Message);
  1206. }
  1207. }
  1208. }
  1209. // If it fails we can still get a list of the Types it was able to resolve
  1210. var types = ex.Types ?? new Type[] { };
  1211. return types.Where(t => t != null).Select(i => new Tuple<Type, string>(i, assemblyInfo.Item2)).ToList();
  1212. }
  1213. catch (Exception ex)
  1214. {
  1215. Logger.LogError(ex, "Error loading types from assembly");
  1216. return new List<Tuple<Type, string>>();
  1217. }
  1218. }
  1219. private CertificateInfo CertificateInfo { get; set; }
  1220. protected X509Certificate Certificate { get; private set; }
  1221. private IEnumerable<string> GetUrlPrefixes()
  1222. {
  1223. var hosts = new[] { "+" };
  1224. return hosts.SelectMany(i =>
  1225. {
  1226. var prefixes = new List<string>
  1227. {
  1228. "http://"+i+":" + HttpPort + "/"
  1229. };
  1230. if (CertificateInfo != null)
  1231. {
  1232. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  1233. }
  1234. return prefixes;
  1235. });
  1236. }
  1237. protected abstract IHttpListener CreateHttpListener();
  1238. /// <summary>
  1239. /// Starts the server.
  1240. /// </summary>
  1241. private void StartServer()
  1242. {
  1243. try
  1244. {
  1245. ((HttpListenerHost)HttpServer).StartServer(GetUrlPrefixes().ToArray(), CreateHttpListener());
  1246. return;
  1247. }
  1248. catch (Exception ex)
  1249. {
  1250. var msg = string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase)
  1251. ? "The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system."
  1252. : "Error starting Http Server";
  1253. Logger.LogError(ex, msg);
  1254. if (HttpPort == ServerConfiguration.DefaultHttpPort)
  1255. {
  1256. throw;
  1257. }
  1258. }
  1259. HttpPort = ServerConfiguration.DefaultHttpPort;
  1260. try
  1261. {
  1262. ((HttpListenerHost)HttpServer).StartServer(GetUrlPrefixes().ToArray(), CreateHttpListener());
  1263. }
  1264. catch (Exception ex)
  1265. {
  1266. Logger.LogError(ex, "Error starting http server");
  1267. throw;
  1268. }
  1269. }
  1270. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  1271. {
  1272. if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
  1273. {
  1274. // Custom cert
  1275. return new CertificateInfo
  1276. {
  1277. Path = ServerConfigurationManager.Configuration.CertificatePath,
  1278. Password = ServerConfigurationManager.Configuration.CertificatePassword
  1279. };
  1280. }
  1281. // Generate self-signed cert
  1282. var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
  1283. var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "2").GetMD5().ToString("N") + ".pfx");
  1284. var password = "embycert";
  1285. //if (generateCertificate)
  1286. //{
  1287. // if (!FileSystemManager.FileExists(certPath))
  1288. // {
  1289. // FileSystemManager.CreateDirectory(FileSystemManager.GetDirectoryName(certPath));
  1290. // try
  1291. // {
  1292. // CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, password, Logger);
  1293. // }
  1294. // catch (Exception ex)
  1295. // {
  1296. // Logger.LogError(ex, "Error creating ssl cert");
  1297. // return null;
  1298. // }
  1299. // }
  1300. //}
  1301. return new CertificateInfo
  1302. {
  1303. Path = certPath,
  1304. Password = password
  1305. };
  1306. }
  1307. /// <summary>
  1308. /// Called when [configuration updated].
  1309. /// </summary>
  1310. /// <param name="sender">The sender.</param>
  1311. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  1312. protected void OnConfigurationUpdated(object sender, EventArgs e)
  1313. {
  1314. ConfigureAutorun();
  1315. var requiresRestart = false;
  1316. // Don't do anything if these haven't been set yet
  1317. if (HttpPort != 0 && HttpsPort != 0)
  1318. {
  1319. // Need to restart if ports have changed
  1320. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  1321. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  1322. {
  1323. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  1324. {
  1325. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  1326. ServerConfigurationManager.SaveConfiguration();
  1327. requiresRestart = true;
  1328. }
  1329. }
  1330. }
  1331. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  1332. {
  1333. requiresRestart = true;
  1334. }
  1335. var currentCertPath = CertificateInfo == null ? null : CertificateInfo.Path;
  1336. var newCertInfo = GetCertificateInfo(false);
  1337. var newCertPath = newCertInfo == null ? null : newCertInfo.Path;
  1338. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  1339. {
  1340. requiresRestart = true;
  1341. }
  1342. if (requiresRestart)
  1343. {
  1344. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1345. NotifyPendingRestart();
  1346. }
  1347. }
  1348. /// <summary>
  1349. /// Notifies that the kernel that a change has been made that requires a restart
  1350. /// </summary>
  1351. public void NotifyPendingRestart()
  1352. {
  1353. Logger.LogInformation("App needs to be restarted.");
  1354. var changed = !HasPendingRestart;
  1355. HasPendingRestart = true;
  1356. if (changed)
  1357. {
  1358. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1359. }
  1360. }
  1361. /// <summary>
  1362. /// Restarts this instance.
  1363. /// </summary>
  1364. public void Restart()
  1365. {
  1366. if (!CanSelfRestart)
  1367. {
  1368. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1369. }
  1370. if (IsShuttingDown)
  1371. {
  1372. return;
  1373. }
  1374. IsShuttingDown = true;
  1375. Task.Run(async () =>
  1376. {
  1377. try
  1378. {
  1379. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1380. }
  1381. catch (Exception ex)
  1382. {
  1383. Logger.LogError(ex, "Error sending server restart notification");
  1384. }
  1385. Logger.LogInformation("Calling RestartInternal");
  1386. RestartInternal();
  1387. });
  1388. }
  1389. protected abstract void RestartInternal();
  1390. /// <summary>
  1391. /// Gets the composable part assemblies.
  1392. /// </summary>
  1393. /// <returns>IEnumerable{Assembly}.</returns>
  1394. protected List<Tuple<Assembly, string>> GetComposablePartAssemblies()
  1395. {
  1396. var list = GetPluginAssemblies();
  1397. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  1398. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  1399. // Include composable parts in the Api assembly
  1400. list.Add(GetAssembly(typeof(ApiEntryPoint)));
  1401. // Include composable parts in the Dashboard assembly
  1402. list.Add(GetAssembly(typeof(DashboardService)));
  1403. // Include composable parts in the Model assembly
  1404. list.Add(GetAssembly(typeof(SystemInfo)));
  1405. // Include composable parts in the Common assembly
  1406. list.Add(GetAssembly(typeof(IApplicationHost)));
  1407. // Include composable parts in the Controller assembly
  1408. list.Add(GetAssembly(typeof(IServerApplicationHost)));
  1409. // Include composable parts in the Providers assembly
  1410. list.Add(GetAssembly(typeof(ProviderUtils)));
  1411. // Include composable parts in the Photos assembly
  1412. list.Add(GetAssembly(typeof(PhotoProvider)));
  1413. // Emby.Server implementations
  1414. list.Add(GetAssembly(typeof(InstallationManager)));
  1415. // MediaEncoding
  1416. list.Add(GetAssembly(typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder)));
  1417. // Dlna
  1418. list.Add(GetAssembly(typeof(DlnaEntryPoint)));
  1419. // Local metadata
  1420. list.Add(GetAssembly(typeof(BoxSetXmlSaver)));
  1421. // Notifications
  1422. list.Add(GetAssembly(typeof(NotificationManager)));
  1423. // Xbmc
  1424. list.Add(GetAssembly(typeof(ArtistNfoProvider)));
  1425. list.AddRange(GetAssembliesWithPartsInternal().Select(i => new Tuple<Assembly, string>(i, null)));
  1426. return list.ToList();
  1427. }
  1428. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1429. /// <summary>
  1430. /// Gets the plugin assemblies.
  1431. /// </summary>
  1432. /// <returns>IEnumerable{Assembly}.</returns>
  1433. private List<Tuple<Assembly, string>> GetPluginAssemblies()
  1434. {
  1435. // Copy pre-installed plugins
  1436. var sourcePath = Path.Combine(ApplicationPaths.ApplicationResourcesPath, "plugins");
  1437. CopyPlugins(sourcePath, ApplicationPaths.PluginsPath);
  1438. return GetPluginAssemblies(ApplicationPaths.PluginsPath);
  1439. }
  1440. private void CopyPlugins(string source, string target)
  1441. {
  1442. List<string> files;
  1443. try
  1444. {
  1445. files = Directory.EnumerateFiles(source, "*.dll", SearchOption.TopDirectoryOnly)
  1446. .ToList();
  1447. }
  1448. catch (DirectoryNotFoundException)
  1449. {
  1450. return;
  1451. }
  1452. if (files.Count == 0)
  1453. {
  1454. return;
  1455. }
  1456. foreach (var sourceFile in files)
  1457. {
  1458. var filename = Path.GetFileName(sourceFile);
  1459. var targetFile = Path.Combine(target, filename);
  1460. var targetFileExists = File.Exists(targetFile);
  1461. if (!targetFileExists && ServerConfigurationManager.Configuration.UninstalledPlugins.Contains(filename, StringComparer.OrdinalIgnoreCase))
  1462. {
  1463. continue;
  1464. }
  1465. if (targetFileExists && GetDllVersion(targetFile) >= GetDllVersion(sourceFile))
  1466. {
  1467. continue;
  1468. }
  1469. Directory.CreateDirectory(target);
  1470. File.Copy(sourceFile, targetFile, true);
  1471. }
  1472. }
  1473. private Version GetDllVersion(string path)
  1474. {
  1475. try
  1476. {
  1477. var result = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion);
  1478. Logger.LogInformation("File {0} has version {1}", path, result);
  1479. return result;
  1480. }
  1481. catch (Exception ex)
  1482. {
  1483. Logger.LogError(ex, "Error getting version number from {path}", path);
  1484. return new Version(1, 0);
  1485. }
  1486. }
  1487. private List<Tuple<Assembly, string>> GetPluginAssemblies(string path)
  1488. {
  1489. try
  1490. {
  1491. return FilterAssembliesToLoad(Directory.EnumerateFiles(path, "*.dll", SearchOption.TopDirectoryOnly))
  1492. .Select(LoadAssembly)
  1493. .Where(a => a != null)
  1494. .ToList();
  1495. }
  1496. catch (DirectoryNotFoundException)
  1497. {
  1498. return new List<Tuple<Assembly, string>>();
  1499. }
  1500. }
  1501. private IEnumerable<string> FilterAssembliesToLoad(IEnumerable<string> paths)
  1502. {
  1503. var exclude = new[]
  1504. {
  1505. "mbplus.dll",
  1506. "mbintros.dll",
  1507. "embytv.dll",
  1508. "Messenger.dll",
  1509. "Messages.dll",
  1510. "MediaBrowser.Plugins.TvMazeProvider.dll",
  1511. "MBBookshelf.dll",
  1512. "MediaBrowser.Channels.Adult.YouJizz.dll",
  1513. "MediaBrowser.Channels.Vine-co.dll",
  1514. "MediaBrowser.Plugins.Vimeo.dll",
  1515. "MediaBrowser.Channels.Vevo.dll",
  1516. "MediaBrowser.Plugins.Twitch.dll",
  1517. "MediaBrowser.Channels.SvtPlay.dll",
  1518. "MediaBrowser.Plugins.SoundCloud.dll",
  1519. "MediaBrowser.Plugins.SnesBox.dll",
  1520. "MediaBrowser.Plugins.RottenTomatoes.dll",
  1521. "MediaBrowser.Plugins.Revision3.dll",
  1522. "MediaBrowser.Plugins.NesBox.dll",
  1523. "MBChapters.dll",
  1524. "MediaBrowser.Channels.LeagueOfLegends.dll",
  1525. "MediaBrowser.Plugins.ADEProvider.dll",
  1526. "MediaBrowser.Channels.BallStreams.dll",
  1527. "MediaBrowser.Channels.Adult.Beeg.dll",
  1528. "ChannelDownloader.dll",
  1529. "Hamstercat.Emby.EmbyBands.dll",
  1530. "EmbyTV.dll",
  1531. "MediaBrowser.Channels.HitboxTV.dll",
  1532. "MediaBrowser.Channels.HockeyStreams.dll",
  1533. "MediaBrowser.Plugins.ITV.dll",
  1534. "MediaBrowser.Plugins.Lastfm.dll",
  1535. "ServerRestart.dll",
  1536. "MediaBrowser.Plugins.NotifyMyAndroidNotifications.dll",
  1537. "MetadataViewer.dll"
  1538. };
  1539. var minRequiredVersions = new Dictionary<string, Version>(StringComparer.OrdinalIgnoreCase)
  1540. {
  1541. { "GameBrowser.dll", new Version(3, 1) },
  1542. { "moviethemesongs.dll", new Version(1, 6) },
  1543. { "themesongs.dll", new Version(1, 2) }
  1544. };
  1545. return paths.Where(path =>
  1546. {
  1547. var filename = Path.GetFileName(path);
  1548. if (exclude.Contains(filename ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  1549. {
  1550. return false;
  1551. }
  1552. Version minRequiredVersion;
  1553. if (minRequiredVersions.TryGetValue(filename, out minRequiredVersion))
  1554. {
  1555. try
  1556. {
  1557. var version = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion);
  1558. if (version < minRequiredVersion)
  1559. {
  1560. Logger.LogInformation("Not loading {filename} {version} because the minimum supported version is {minRequiredVersion}. Please update to the newer version", filename, version, minRequiredVersion);
  1561. return false;
  1562. }
  1563. }
  1564. catch (Exception ex)
  1565. {
  1566. Logger.LogError(ex, "Error getting version number from {path}", path);
  1567. return false;
  1568. }
  1569. }
  1570. return true;
  1571. });
  1572. }
  1573. /// <summary>
  1574. /// Gets the system status.
  1575. /// </summary>
  1576. /// <returns>SystemInfo.</returns>
  1577. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1578. {
  1579. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1580. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1581. return new SystemInfo
  1582. {
  1583. HasPendingRestart = HasPendingRestart,
  1584. IsShuttingDown = IsShuttingDown,
  1585. Version = ApplicationVersion.ToString(),
  1586. WebSocketPortNumber = HttpPort,
  1587. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1588. Id = SystemId,
  1589. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1590. LogPath = ApplicationPaths.LogDirectoryPath,
  1591. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1592. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1593. CachePath = ApplicationPaths.CachePath,
  1594. HttpServerPortNumber = HttpPort,
  1595. SupportsHttps = SupportsHttps,
  1596. HttpsPortNumber = HttpsPort,
  1597. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1598. OperatingSystemDisplayName = OperatingSystemDisplayName,
  1599. CanSelfRestart = CanSelfRestart,
  1600. CanSelfUpdate = CanSelfUpdate,
  1601. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1602. WanAddress = wanAddress,
  1603. HasUpdateAvailable = HasUpdateAvailable,
  1604. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  1605. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1606. ServerName = FriendlyName,
  1607. LocalAddress = localAddress,
  1608. SupportsLibraryMonitor = true,
  1609. EncoderLocationType = MediaEncoder.EncoderLocationType,
  1610. SystemArchitecture = EnvironmentInfo.SystemArchitecture,
  1611. SystemUpdateLevel = SystemUpdateLevel,
  1612. PackageName = StartupOptions.GetOption("-package")
  1613. };
  1614. }
  1615. public WakeOnLanInfo[] GetWakeOnLanInfo()
  1616. {
  1617. return NetworkManager.GetMacAddresses()
  1618. .Select(i => new WakeOnLanInfo
  1619. {
  1620. MacAddress = i
  1621. })
  1622. .ToArray();
  1623. }
  1624. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1625. {
  1626. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1627. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1628. return new PublicSystemInfo
  1629. {
  1630. Version = ApplicationVersion.ToString(),
  1631. Id = SystemId,
  1632. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1633. WanAddress = wanAddress,
  1634. ServerName = FriendlyName,
  1635. LocalAddress = localAddress
  1636. };
  1637. }
  1638. public bool EnableHttps
  1639. {
  1640. get
  1641. {
  1642. return SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1643. }
  1644. }
  1645. public bool SupportsHttps
  1646. {
  1647. get { return Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy; }
  1648. }
  1649. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1650. {
  1651. try
  1652. {
  1653. // Return the first matched address, if found, or the first known local address
  1654. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1655. foreach (var address in addresses)
  1656. {
  1657. return GetLocalApiUrl(address);
  1658. }
  1659. return null;
  1660. }
  1661. catch (Exception ex)
  1662. {
  1663. Logger.LogError(ex, "Error getting local Ip address information");
  1664. }
  1665. return null;
  1666. }
  1667. public async Task<string> GetWanApiUrl(CancellationToken cancellationToken)
  1668. {
  1669. var url = "http://ipv4.icanhazip.com";
  1670. try
  1671. {
  1672. using (var response = await HttpClient.Get(new HttpRequestOptions
  1673. {
  1674. Url = url,
  1675. LogErrorResponseBody = false,
  1676. LogErrors = false,
  1677. LogRequest = false,
  1678. TimeoutMs = 10000,
  1679. BufferContent = false,
  1680. CancellationToken = cancellationToken
  1681. }))
  1682. {
  1683. return GetLocalApiUrl(response.ReadToEnd().Trim());
  1684. }
  1685. }
  1686. catch(Exception ex)
  1687. {
  1688. Logger.LogError(ex, "Error getting WAN Ip address information");
  1689. }
  1690. return null;
  1691. }
  1692. public string GetLocalApiUrl(IpAddressInfo ipAddress)
  1693. {
  1694. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1695. {
  1696. return GetLocalApiUrl("[" + ipAddress.Address + "]");
  1697. }
  1698. return GetLocalApiUrl(ipAddress.Address);
  1699. }
  1700. public string GetLocalApiUrl(string host)
  1701. {
  1702. return string.Format("http://{0}:{1}",
  1703. host,
  1704. HttpPort.ToString(CultureInfo.InvariantCulture));
  1705. }
  1706. public Task<List<IpAddressInfo>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1707. {
  1708. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1709. }
  1710. private async Task<List<IpAddressInfo>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1711. {
  1712. var addresses = ServerConfigurationManager
  1713. .Configuration
  1714. .LocalNetworkAddresses
  1715. .Select(NormalizeConfiguredLocalAddress)
  1716. .Where(i => i != null)
  1717. .ToList();
  1718. if (addresses.Count == 0)
  1719. {
  1720. addresses.AddRange(NetworkManager.GetLocalIpAddresses());
  1721. }
  1722. var resultList = new List<IpAddressInfo>();
  1723. foreach (var address in addresses)
  1724. {
  1725. if (!allowLoopback)
  1726. {
  1727. if (address.Equals(IpAddressInfo.Loopback) || address.Equals(IpAddressInfo.IPv6Loopback))
  1728. {
  1729. continue;
  1730. }
  1731. }
  1732. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1733. if (valid)
  1734. {
  1735. resultList.Add(address);
  1736. if (limit > 0 && resultList.Count >= limit)
  1737. {
  1738. return resultList;
  1739. }
  1740. }
  1741. }
  1742. return resultList;
  1743. }
  1744. private IpAddressInfo NormalizeConfiguredLocalAddress(string address)
  1745. {
  1746. var index = address.Trim('/').IndexOf('/');
  1747. if (index != -1)
  1748. {
  1749. address = address.Substring(index + 1);
  1750. }
  1751. IpAddressInfo result;
  1752. if (NetworkManager.TryParseIpAddress(address.Trim('/'), out result))
  1753. {
  1754. return result;
  1755. }
  1756. return null;
  1757. }
  1758. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1759. private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address, CancellationToken cancellationToken)
  1760. {
  1761. if (address.Equals(IpAddressInfo.Loopback) ||
  1762. address.Equals(IpAddressInfo.IPv6Loopback))
  1763. {
  1764. return true;
  1765. }
  1766. var apiUrl = GetLocalApiUrl(address);
  1767. apiUrl += "/system/ping";
  1768. bool cachedResult;
  1769. if (_validAddressResults.TryGetValue(apiUrl, out cachedResult))
  1770. {
  1771. return cachedResult;
  1772. }
  1773. var logPing = false;
  1774. #if DEBUG
  1775. logPing = true;
  1776. #endif
  1777. try
  1778. {
  1779. using (var response = await HttpClient.SendAsync(new HttpRequestOptions
  1780. {
  1781. Url = apiUrl,
  1782. LogErrorResponseBody = false,
  1783. LogErrors = logPing,
  1784. LogRequest = logPing,
  1785. TimeoutMs = 30000,
  1786. BufferContent = false,
  1787. CancellationToken = cancellationToken
  1788. }, "POST").ConfigureAwait(false))
  1789. {
  1790. using (var reader = new StreamReader(response.Content))
  1791. {
  1792. var result = reader.ReadToEnd();
  1793. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1794. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1795. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1796. return valid;
  1797. }
  1798. }
  1799. }
  1800. catch (OperationCanceledException)
  1801. {
  1802. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1803. throw;
  1804. }
  1805. catch (Exception ex)
  1806. {
  1807. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1808. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1809. return false;
  1810. }
  1811. }
  1812. public string FriendlyName
  1813. {
  1814. get
  1815. {
  1816. return string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1817. ? Environment.MachineName
  1818. : ServerConfigurationManager.Configuration.ServerName;
  1819. }
  1820. }
  1821. public int HttpPort { get; private set; }
  1822. public int HttpsPort { get; private set; }
  1823. /// <summary>
  1824. /// Shuts down.
  1825. /// </summary>
  1826. public async Task Shutdown()
  1827. {
  1828. if (IsShuttingDown)
  1829. {
  1830. return;
  1831. }
  1832. IsShuttingDown = true;
  1833. try
  1834. {
  1835. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1836. }
  1837. catch (Exception ex)
  1838. {
  1839. Logger.LogError(ex, "Error sending server shutdown notification");
  1840. }
  1841. ShutdownInternal();
  1842. }
  1843. protected abstract void ShutdownInternal();
  1844. /// <summary>
  1845. /// Registers the server with administrator access.
  1846. /// </summary>
  1847. private void RegisterServerWithAdministratorAccess()
  1848. {
  1849. Logger.LogInformation("Requesting administrative access to authorize http server");
  1850. try
  1851. {
  1852. AuthorizeServer();
  1853. }
  1854. catch (NotImplementedException)
  1855. {
  1856. }
  1857. catch (Exception ex)
  1858. {
  1859. Logger.LogError(ex, "Error authorizing server");
  1860. }
  1861. }
  1862. protected virtual void AuthorizeServer()
  1863. {
  1864. throw new NotImplementedException();
  1865. }
  1866. public event EventHandler HasUpdateAvailableChanged;
  1867. private bool _hasUpdateAvailable;
  1868. public bool HasUpdateAvailable
  1869. {
  1870. get { return _hasUpdateAvailable; }
  1871. set
  1872. {
  1873. var fireEvent = value && !_hasUpdateAvailable;
  1874. _hasUpdateAvailable = value;
  1875. if (fireEvent)
  1876. {
  1877. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  1878. }
  1879. }
  1880. }
  1881. /// <summary>
  1882. /// Removes the plugin.
  1883. /// </summary>
  1884. /// <param name="plugin">The plugin.</param>
  1885. public void RemovePlugin(IPlugin plugin)
  1886. {
  1887. var list = Plugins.ToList();
  1888. list.Remove(plugin);
  1889. Plugins = list.ToArray();
  1890. }
  1891. /// <summary>
  1892. /// Checks for update.
  1893. /// </summary>
  1894. /// <param name="cancellationToken">The cancellation token.</param>
  1895. /// <param name="progress">The progress.</param>
  1896. /// <returns>Task{CheckForUpdateResult}.</returns>
  1897. public async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  1898. {
  1899. var updateLevel = SystemUpdateLevel;
  1900. var cacheLength = updateLevel == PackageVersionClass.Release ?
  1901. TimeSpan.FromHours(12) :
  1902. TimeSpan.FromMinutes(5);
  1903. try
  1904. {
  1905. var result = await new GithubUpdater(HttpClient, JsonSerializer).CheckForUpdateResult("MediaBrowser",
  1906. "Emby.Releases",
  1907. ApplicationVersion,
  1908. updateLevel,
  1909. ReleaseAssetFilename,
  1910. "MBServer",
  1911. UpdateTargetFileName,
  1912. cacheLength,
  1913. cancellationToken).ConfigureAwait(false);
  1914. HasUpdateAvailable = result.IsUpdateAvailable;
  1915. return result;
  1916. }
  1917. catch (HttpException ex)
  1918. {
  1919. // users are overreacting to this occasionally failing
  1920. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.Forbidden)
  1921. {
  1922. HasUpdateAvailable = false;
  1923. return new CheckForUpdateResult
  1924. {
  1925. IsUpdateAvailable = false
  1926. };
  1927. }
  1928. throw;
  1929. }
  1930. }
  1931. protected virtual string UpdateTargetFileName
  1932. {
  1933. get { return "Mbserver.zip"; }
  1934. }
  1935. /// <summary>
  1936. /// Updates the application.
  1937. /// </summary>
  1938. /// <param name="package">The package that contains the update</param>
  1939. /// <param name="cancellationToken">The cancellation token.</param>
  1940. /// <param name="progress">The progress.</param>
  1941. public async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  1942. {
  1943. await InstallationManager.InstallPackage(package, false, progress, cancellationToken).ConfigureAwait(false);
  1944. HasUpdateAvailable = false;
  1945. OnApplicationUpdated(package);
  1946. }
  1947. /// <summary>
  1948. /// Configures the automatic run at startup.
  1949. /// </summary>
  1950. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  1951. protected void ConfigureAutoRunAtStartup(bool autorun)
  1952. {
  1953. if (SupportsAutoRunAtStartup)
  1954. {
  1955. ConfigureAutoRunInternal(autorun);
  1956. }
  1957. }
  1958. protected virtual void ConfigureAutoRunInternal(bool autorun)
  1959. {
  1960. throw new NotImplementedException();
  1961. }
  1962. /// <summary>
  1963. /// This returns localhost in the case of no external dns, and the hostname if the
  1964. /// dns is prefixed with a valid Uri prefix.
  1965. /// </summary>
  1966. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1967. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1968. private static string GetHostnameFromExternalDns(string externalDns)
  1969. {
  1970. if (string.IsNullOrEmpty(externalDns))
  1971. {
  1972. return "localhost";
  1973. }
  1974. try
  1975. {
  1976. return new Uri(externalDns).Host;
  1977. }
  1978. catch
  1979. {
  1980. return externalDns;
  1981. }
  1982. }
  1983. public virtual void LaunchUrl(string url)
  1984. {
  1985. if (!CanLaunchWebBrowser)
  1986. {
  1987. throw new NotSupportedException();
  1988. }
  1989. var process = ProcessFactory.Create(new ProcessOptions
  1990. {
  1991. FileName = url,
  1992. //EnableRaisingEvents = true,
  1993. UseShellExecute = true,
  1994. ErrorDialog = false
  1995. });
  1996. process.Exited += ProcessExited;
  1997. try
  1998. {
  1999. process.Start();
  2000. }
  2001. catch (Exception ex)
  2002. {
  2003. Logger.LogError(ex, "Error launching url: {url}", url);
  2004. throw;
  2005. }
  2006. }
  2007. private static void ProcessExited(object sender, EventArgs e)
  2008. {
  2009. ((IProcess)sender).Dispose();
  2010. }
  2011. public virtual void EnableLoopback(string appName)
  2012. {
  2013. }
  2014. /// <summary>
  2015. /// Called when [application updated].
  2016. /// </summary>
  2017. /// <param name="package">The package.</param>
  2018. protected void OnApplicationUpdated(PackageVersionInfo package)
  2019. {
  2020. Logger.LogInformation("Application has been updated to version {0}", package.versionStr);
  2021. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  2022. {
  2023. Argument = package
  2024. }, Logger);
  2025. NotifyPendingRestart();
  2026. }
  2027. private bool _disposed;
  2028. /// <summary>
  2029. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  2030. /// </summary>
  2031. public void Dispose()
  2032. {
  2033. if (!_disposed)
  2034. {
  2035. _disposed = true;
  2036. Dispose(true);
  2037. }
  2038. }
  2039. /// <summary>
  2040. /// Releases unmanaged and - optionally - managed resources.
  2041. /// </summary>
  2042. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  2043. protected virtual void Dispose(bool dispose)
  2044. {
  2045. if (dispose)
  2046. {
  2047. var type = GetType();
  2048. //LoggerFactory.AddConsoleOutput();
  2049. Logger.LogInformation("Disposing " + type.Name);
  2050. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  2051. DisposableParts.Clear();
  2052. foreach (var part in parts)
  2053. {
  2054. Logger.LogInformation("Disposing " + part.GetType().Name);
  2055. try
  2056. {
  2057. part.Dispose();
  2058. }
  2059. catch (Exception ex)
  2060. {
  2061. Logger.LogError(ex, "Error disposing {0}", part.GetType().Name);
  2062. }
  2063. }
  2064. }
  2065. }
  2066. private Dictionary<string, string> _values;
  2067. public string GetValue(string name)
  2068. {
  2069. if (_values == null)
  2070. {
  2071. _values = LoadValues();
  2072. }
  2073. string value;
  2074. if (_values.TryGetValue(name, out value))
  2075. {
  2076. return value;
  2077. }
  2078. return null;
  2079. }
  2080. // TODO: @bond Remove?
  2081. private Dictionary<string, string> LoadValues()
  2082. {
  2083. Dictionary<string, string> values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  2084. using (var stream = typeof(ApplicationHost).Assembly.GetManifestResourceStream(typeof(ApplicationHost).Namespace + ".values.txt"))
  2085. {
  2086. using (var reader = new StreamReader(stream))
  2087. {
  2088. while (!reader.EndOfStream)
  2089. {
  2090. var line = reader.ReadLine();
  2091. if (string.IsNullOrEmpty(line))
  2092. {
  2093. continue;
  2094. }
  2095. var index = line.IndexOf('=');
  2096. if (index != -1)
  2097. {
  2098. values[line.Substring(0, index)] = line.Substring(index + 1);
  2099. }
  2100. }
  2101. }
  2102. }
  2103. return values;
  2104. }
  2105. }
  2106. internal class CertificateInfo
  2107. {
  2108. public string Path { get; set; }
  2109. public string Password { get; set; }
  2110. }
  2111. }