ApplicationHost.cs 93 KB

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