ApplicationHost.cs 86 KB

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