BaseItem.cs 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json.Serialization;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Data.Entities;
  12. using Jellyfin.Data.Enums;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.Channels;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Dto;
  17. using MediaBrowser.Controller.Extensions;
  18. using MediaBrowser.Controller.Library;
  19. using MediaBrowser.Controller.Persistence;
  20. using MediaBrowser.Controller.Providers;
  21. using MediaBrowser.Model.Configuration;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.Entities;
  24. using MediaBrowser.Model.Globalization;
  25. using MediaBrowser.Model.IO;
  26. using MediaBrowser.Model.Library;
  27. using MediaBrowser.Model.LiveTv;
  28. using MediaBrowser.Model.MediaInfo;
  29. using MediaBrowser.Model.Providers;
  30. using Microsoft.Extensions.Logging;
  31. namespace MediaBrowser.Controller.Entities
  32. {
  33. /// <summary>
  34. /// Class BaseItem.
  35. /// </summary>
  36. public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>, IEquatable<BaseItem>
  37. {
  38. /// <summary>
  39. /// The supported image extensions.
  40. /// </summary>
  41. public static readonly string[] SupportedImageExtensions
  42. = new[] { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
  43. private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
  44. {
  45. ".nfo",
  46. ".xml",
  47. ".srt",
  48. ".vtt",
  49. ".sub",
  50. ".idx",
  51. ".txt",
  52. ".edl",
  53. ".bif",
  54. ".smi",
  55. ".ttml"
  56. };
  57. protected BaseItem()
  58. {
  59. Tags = Array.Empty<string>();
  60. Genres = Array.Empty<string>();
  61. Studios = Array.Empty<string>();
  62. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  63. LockedFields = Array.Empty<MetadataField>();
  64. ImageInfos = Array.Empty<ItemImageInfo>();
  65. ProductionLocations = Array.Empty<string>();
  66. RemoteTrailers = Array.Empty<MediaUrl>();
  67. ExtraIds = Array.Empty<Guid>();
  68. }
  69. public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
  70. public static char SlugChar = '-';
  71. /// <summary>
  72. /// The trailer folder name.
  73. /// </summary>
  74. public const string TrailerFolderName = "trailers";
  75. public const string ThemeSongsFolderName = "theme-music";
  76. public const string ThemeSongFilename = "theme";
  77. public const string ThemeVideosFolderName = "backdrops";
  78. public const string ExtrasFolderName = "extras";
  79. public const string BehindTheScenesFolderName = "behind the scenes";
  80. public const string DeletedScenesFolderName = "deleted scenes";
  81. public const string InterviewFolderName = "interviews";
  82. public const string SceneFolderName = "scenes";
  83. public const string SampleFolderName = "samples";
  84. public static readonly string[] AllExtrasTypesFolderNames = {
  85. ExtrasFolderName,
  86. BehindTheScenesFolderName,
  87. DeletedScenesFolderName,
  88. InterviewFolderName,
  89. SceneFolderName,
  90. SampleFolderName
  91. };
  92. [JsonIgnore]
  93. public Guid[] ThemeSongIds
  94. {
  95. get
  96. {
  97. if (_themeSongIds == null)
  98. {
  99. _themeSongIds = GetExtras()
  100. .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeSong)
  101. .Select(song => song.Id)
  102. .ToArray();
  103. }
  104. return _themeSongIds;
  105. }
  106. private set
  107. {
  108. _themeSongIds = value;
  109. }
  110. }
  111. [JsonIgnore]
  112. public Guid[] ThemeVideoIds
  113. {
  114. get
  115. {
  116. if (_themeVideoIds == null)
  117. {
  118. _themeVideoIds = GetExtras()
  119. .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeVideo)
  120. .Select(song => song.Id)
  121. .ToArray();
  122. }
  123. return _themeVideoIds;
  124. }
  125. private set
  126. {
  127. _themeVideoIds = value;
  128. }
  129. }
  130. [JsonIgnore]
  131. public string PreferredMetadataCountryCode { get; set; }
  132. [JsonIgnore]
  133. public string PreferredMetadataLanguage { get; set; }
  134. public long? Size { get; set; }
  135. public string Container { get; set; }
  136. [JsonIgnore]
  137. public string Tagline { get; set; }
  138. [JsonIgnore]
  139. public virtual ItemImageInfo[] ImageInfos { get; set; }
  140. [JsonIgnore]
  141. public bool IsVirtualItem { get; set; }
  142. /// <summary>
  143. /// Gets or sets the album.
  144. /// </summary>
  145. /// <value>The album.</value>
  146. [JsonIgnore]
  147. public string Album { get; set; }
  148. /// <summary>
  149. /// Gets or sets the channel identifier.
  150. /// </summary>
  151. /// <value>The channel identifier.</value>
  152. [JsonIgnore]
  153. public Guid ChannelId { get; set; }
  154. [JsonIgnore]
  155. public virtual bool SupportsAddingToPlaylist => false;
  156. [JsonIgnore]
  157. public virtual bool AlwaysScanInternalMetadataPath => false;
  158. /// <summary>
  159. /// Gets a value indicating whether this instance is in mixed folder.
  160. /// </summary>
  161. /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
  162. [JsonIgnore]
  163. public bool IsInMixedFolder { get; set; }
  164. [JsonIgnore]
  165. public virtual bool SupportsPlayedStatus => false;
  166. [JsonIgnore]
  167. public virtual bool SupportsPositionTicksResume => false;
  168. [JsonIgnore]
  169. public virtual bool SupportsRemoteImageDownloading => true;
  170. private string _name;
  171. /// <summary>
  172. /// Gets or sets the name.
  173. /// </summary>
  174. /// <value>The name.</value>
  175. [JsonIgnore]
  176. public virtual string Name
  177. {
  178. get => _name;
  179. set
  180. {
  181. _name = value;
  182. // lazy load this again
  183. _sortName = null;
  184. }
  185. }
  186. [JsonIgnore]
  187. public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
  188. [JsonIgnore]
  189. public int? TotalBitrate { get; set; }
  190. [JsonIgnore]
  191. public ExtraType? ExtraType { get; set; }
  192. [JsonIgnore]
  193. public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || ExtraType.Value == Model.Entities.ExtraType.ThemeVideo);
  194. [JsonIgnore]
  195. public string OriginalTitle { get; set; }
  196. /// <summary>
  197. /// Gets or sets the id.
  198. /// </summary>
  199. /// <value>The id.</value>
  200. [JsonIgnore]
  201. public Guid Id { get; set; }
  202. [JsonIgnore]
  203. public Guid OwnerId { get; set; }
  204. /// <summary>
  205. /// Gets or sets the audio.
  206. /// </summary>
  207. /// <value>The audio.</value>
  208. [JsonIgnore]
  209. public ProgramAudio? Audio { get; set; }
  210. /// <summary>
  211. /// Return the id that should be used to key display prefs for this item.
  212. /// Default is based on the type for everything except actual generic folders.
  213. /// </summary>
  214. /// <value>The display prefs id.</value>
  215. [JsonIgnore]
  216. public virtual Guid DisplayPreferencesId
  217. {
  218. get
  219. {
  220. var thisType = GetType();
  221. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  222. }
  223. }
  224. /// <summary>
  225. /// Gets or sets the path.
  226. /// </summary>
  227. /// <value>The path.</value>
  228. [JsonIgnore]
  229. public virtual string Path { get; set; }
  230. [JsonIgnore]
  231. public virtual SourceType SourceType
  232. {
  233. get
  234. {
  235. if (!ChannelId.Equals(Guid.Empty))
  236. {
  237. return SourceType.Channel;
  238. }
  239. return SourceType.Library;
  240. }
  241. }
  242. /// <summary>
  243. /// Returns the folder containing the item.
  244. /// If the item is a folder, it returns the folder itself.
  245. /// </summary>
  246. [JsonIgnore]
  247. public virtual string ContainingFolderPath
  248. {
  249. get
  250. {
  251. if (IsFolder)
  252. {
  253. return Path;
  254. }
  255. return System.IO.Path.GetDirectoryName(Path);
  256. }
  257. }
  258. /// <summary>
  259. /// Gets or sets the name of the service.
  260. /// </summary>
  261. /// <value>The name of the service.</value>
  262. [JsonIgnore]
  263. public string ServiceName { get; set; }
  264. /// <summary>
  265. /// If this content came from an external service, the id of the content on that service.
  266. /// </summary>
  267. [JsonIgnore]
  268. public string ExternalId { get; set; }
  269. [JsonIgnore]
  270. public string ExternalSeriesId { get; set; }
  271. /// <summary>
  272. /// Gets or sets the etag.
  273. /// </summary>
  274. /// <value>The etag.</value>
  275. [JsonIgnore]
  276. public string ExternalEtag { get; set; }
  277. [JsonIgnore]
  278. public virtual bool IsHidden => false;
  279. public BaseItem GetOwner()
  280. {
  281. var ownerId = OwnerId;
  282. return ownerId.Equals(Guid.Empty) ? null : LibraryManager.GetItemById(ownerId);
  283. }
  284. /// <summary>
  285. /// Gets or sets the type of the location.
  286. /// </summary>
  287. /// <value>The type of the location.</value>
  288. [JsonIgnore]
  289. public virtual LocationType LocationType
  290. {
  291. get
  292. {
  293. // if (IsOffline)
  294. //{
  295. // return LocationType.Offline;
  296. //}
  297. var path = Path;
  298. if (string.IsNullOrEmpty(path))
  299. {
  300. if (SourceType == SourceType.Channel)
  301. {
  302. return LocationType.Remote;
  303. }
  304. return LocationType.Virtual;
  305. }
  306. return FileSystem.IsPathFile(path) ? LocationType.FileSystem : LocationType.Remote;
  307. }
  308. }
  309. [JsonIgnore]
  310. public MediaProtocol? PathProtocol
  311. {
  312. get
  313. {
  314. var path = Path;
  315. if (string.IsNullOrEmpty(path))
  316. {
  317. return null;
  318. }
  319. return MediaSourceManager.GetPathProtocol(path);
  320. }
  321. }
  322. public bool IsPathProtocol(MediaProtocol protocol)
  323. {
  324. var current = PathProtocol;
  325. return current.HasValue && current.Value == protocol;
  326. }
  327. [JsonIgnore]
  328. public bool IsFileProtocol => IsPathProtocol(MediaProtocol.File);
  329. [JsonIgnore]
  330. public bool HasPathProtocol => PathProtocol.HasValue;
  331. [JsonIgnore]
  332. public virtual bool SupportsLocalMetadata
  333. {
  334. get
  335. {
  336. if (SourceType == SourceType.Channel)
  337. {
  338. return false;
  339. }
  340. return IsFileProtocol;
  341. }
  342. }
  343. [JsonIgnore]
  344. public virtual string FileNameWithoutExtension
  345. {
  346. get
  347. {
  348. if (IsFileProtocol)
  349. {
  350. return System.IO.Path.GetFileNameWithoutExtension(Path);
  351. }
  352. return null;
  353. }
  354. }
  355. [JsonIgnore]
  356. public virtual bool EnableAlphaNumericSorting => true;
  357. private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
  358. {
  359. var list = new List<Tuple<StringBuilder, bool>>();
  360. int thisMarker = 0;
  361. while (thisMarker < s1.Length)
  362. {
  363. char thisCh = s1[thisMarker];
  364. var thisChunk = new StringBuilder();
  365. bool isNumeric = char.IsDigit(thisCh);
  366. while (thisMarker < s1.Length && char.IsDigit(thisCh) == isNumeric)
  367. {
  368. thisChunk.Append(thisCh);
  369. thisMarker++;
  370. if (thisMarker < s1.Length)
  371. {
  372. thisCh = s1[thisMarker];
  373. }
  374. }
  375. list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
  376. }
  377. return list;
  378. }
  379. /// <summary>
  380. /// This is just a helper for convenience.
  381. /// </summary>
  382. /// <value>The primary image path.</value>
  383. [JsonIgnore]
  384. public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
  385. public bool IsMetadataFetcherEnabled(LibraryOptions libraryOptions, string name)
  386. {
  387. if (SourceType == SourceType.Channel)
  388. {
  389. // hack alert
  390. return !EnableMediaSourceDisplay;
  391. }
  392. var typeOptions = libraryOptions.GetTypeOptions(GetType().Name);
  393. if (typeOptions != null)
  394. {
  395. return typeOptions.MetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  396. }
  397. if (!libraryOptions.EnableInternetProviders)
  398. {
  399. return false;
  400. }
  401. var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
  402. return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  403. }
  404. public bool IsImageFetcherEnabled(LibraryOptions libraryOptions, string name)
  405. {
  406. if (this is Channel)
  407. {
  408. // hack alert
  409. return true;
  410. }
  411. if (SourceType == SourceType.Channel)
  412. {
  413. // hack alert
  414. return !EnableMediaSourceDisplay;
  415. }
  416. var typeOptions = libraryOptions.GetTypeOptions(GetType().Name);
  417. if (typeOptions != null)
  418. {
  419. return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  420. }
  421. if (!libraryOptions.EnableInternetProviders)
  422. {
  423. return false;
  424. }
  425. var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
  426. return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  427. }
  428. public virtual bool CanDelete()
  429. {
  430. if (SourceType == SourceType.Channel)
  431. {
  432. return ChannelManager.CanDelete(this);
  433. }
  434. return IsFileProtocol;
  435. }
  436. public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
  437. {
  438. if (user.HasPermission(PermissionKind.EnableContentDeletion))
  439. {
  440. return true;
  441. }
  442. var allowed = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders);
  443. if (SourceType == SourceType.Channel)
  444. {
  445. return allowed.Contains(ChannelId.ToString(""), StringComparer.OrdinalIgnoreCase);
  446. }
  447. else
  448. {
  449. var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
  450. foreach (var folder in collectionFolders)
  451. {
  452. if (allowed.Contains(folder.Id.ToString("N", CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase))
  453. {
  454. return true;
  455. }
  456. }
  457. }
  458. return false;
  459. }
  460. public bool CanDelete(User user, List<Folder> allCollectionFolders)
  461. {
  462. return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
  463. }
  464. public bool CanDelete(User user)
  465. {
  466. var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
  467. return CanDelete(user, allCollectionFolders);
  468. }
  469. public virtual bool CanDownload()
  470. {
  471. return false;
  472. }
  473. public virtual bool IsAuthorizedToDownload(User user)
  474. {
  475. return user.HasPermission(PermissionKind.EnableContentDownloading);
  476. }
  477. public bool CanDownload(User user)
  478. {
  479. return CanDownload() && IsAuthorizedToDownload(user);
  480. }
  481. /// <summary>
  482. /// Gets or sets the date created.
  483. /// </summary>
  484. /// <value>The date created.</value>
  485. [JsonIgnore]
  486. public DateTime DateCreated { get; set; }
  487. /// <summary>
  488. /// Gets or sets the date modified.
  489. /// </summary>
  490. /// <value>The date modified.</value>
  491. [JsonIgnore]
  492. public DateTime DateModified { get; set; }
  493. public DateTime DateLastSaved { get; set; }
  494. [JsonIgnore]
  495. public DateTime DateLastRefreshed { get; set; }
  496. /// <summary>
  497. /// The logger.
  498. /// </summary>
  499. public static ILogger<BaseItem> Logger { get; set; }
  500. public static ILibraryManager LibraryManager { get; set; }
  501. public static IServerConfigurationManager ConfigurationManager { get; set; }
  502. public static IProviderManager ProviderManager { get; set; }
  503. public static ILocalizationManager LocalizationManager { get; set; }
  504. public static IItemRepository ItemRepository { get; set; }
  505. public static IFileSystem FileSystem { get; set; }
  506. public static IUserDataManager UserDataManager { get; set; }
  507. public static IChannelManager ChannelManager { get; set; }
  508. public static IMediaSourceManager MediaSourceManager { get; set; }
  509. /// <summary>
  510. /// Returns a <see cref="string" /> that represents this instance.
  511. /// </summary>
  512. /// <returns>A <see cref="string" /> that represents this instance.</returns>
  513. public override string ToString()
  514. {
  515. return Name;
  516. }
  517. [JsonIgnore]
  518. public bool IsLocked { get; set; }
  519. /// <summary>
  520. /// Gets or sets the locked fields.
  521. /// </summary>
  522. /// <value>The locked fields.</value>
  523. [JsonIgnore]
  524. public MetadataField[] LockedFields { get; set; }
  525. /// <summary>
  526. /// Gets the type of the media.
  527. /// </summary>
  528. /// <value>The type of the media.</value>
  529. [JsonIgnore]
  530. public virtual string MediaType => null;
  531. [JsonIgnore]
  532. public virtual string[] PhysicalLocations
  533. {
  534. get
  535. {
  536. if (!IsFileProtocol)
  537. {
  538. return Array.Empty<string>();
  539. }
  540. return new[] { Path };
  541. }
  542. }
  543. private string _forcedSortName;
  544. /// <summary>
  545. /// Gets or sets the name of the forced sort.
  546. /// </summary>
  547. /// <value>The name of the forced sort.</value>
  548. [JsonIgnore]
  549. public string ForcedSortName
  550. {
  551. get => _forcedSortName;
  552. set { _forcedSortName = value; _sortName = null; }
  553. }
  554. private string _sortName;
  555. private Guid[] _themeSongIds;
  556. private Guid[] _themeVideoIds;
  557. /// <summary>
  558. /// Gets the name of the sort.
  559. /// </summary>
  560. /// <value>The name of the sort.</value>
  561. [JsonIgnore]
  562. public string SortName
  563. {
  564. get
  565. {
  566. if (_sortName == null)
  567. {
  568. if (!string.IsNullOrEmpty(ForcedSortName))
  569. {
  570. // Need the ToLower because that's what CreateSortName does
  571. _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
  572. }
  573. else
  574. {
  575. _sortName = CreateSortName();
  576. }
  577. }
  578. return _sortName;
  579. }
  580. set => _sortName = value;
  581. }
  582. public string GetInternalMetadataPath()
  583. {
  584. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  585. return GetInternalMetadataPath(basePath);
  586. }
  587. protected virtual string GetInternalMetadataPath(string basePath)
  588. {
  589. if (SourceType == SourceType.Channel)
  590. {
  591. return System.IO.Path.Combine(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture));
  592. }
  593. ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
  594. basePath = System.IO.Path.Combine(basePath, "library");
  595. return System.IO.Path.Join(basePath, idString.Slice(0, 2), idString);
  596. }
  597. /// <summary>
  598. /// Creates the name of the sort.
  599. /// </summary>
  600. /// <returns>System.String.</returns>
  601. protected virtual string CreateSortName()
  602. {
  603. if (Name == null)
  604. {
  605. return null; // some items may not have name filled in properly
  606. }
  607. if (!EnableAlphaNumericSorting)
  608. {
  609. return Name.TrimStart();
  610. }
  611. var sortable = Name.Trim().ToLowerInvariant();
  612. foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
  613. {
  614. sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
  615. }
  616. foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
  617. {
  618. sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
  619. }
  620. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  621. {
  622. // Remove from beginning if a space follows
  623. if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
  624. {
  625. sortable = sortable.Remove(0, search.Length + 1);
  626. }
  627. // Remove from middle if surrounded by spaces
  628. sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
  629. // Remove from end if followed by a space
  630. if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
  631. {
  632. sortable = sortable.Remove(sortable.Length - (search.Length + 1));
  633. }
  634. }
  635. return ModifySortChunks(sortable);
  636. }
  637. private string ModifySortChunks(string name)
  638. {
  639. var chunks = GetSortChunks(name);
  640. var builder = new StringBuilder();
  641. foreach (var chunk in chunks)
  642. {
  643. var chunkBuilder = chunk.Item1;
  644. // This chunk is numeric
  645. if (chunk.Item2)
  646. {
  647. while (chunkBuilder.Length < 10)
  648. {
  649. chunkBuilder.Insert(0, '0');
  650. }
  651. }
  652. builder.Append(chunkBuilder);
  653. }
  654. // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  655. return builder.ToString().RemoveDiacritics();
  656. }
  657. [JsonIgnore]
  658. public bool EnableMediaSourceDisplay
  659. {
  660. get
  661. {
  662. if (SourceType == SourceType.Channel)
  663. {
  664. return ChannelManager.EnableMediaSourceDisplay(this);
  665. }
  666. return true;
  667. }
  668. }
  669. [JsonIgnore]
  670. public Guid ParentId { get; set; }
  671. /// <summary>
  672. /// Gets or sets the parent.
  673. /// </summary>
  674. /// <value>The parent.</value>
  675. [JsonIgnore]
  676. public Folder Parent
  677. {
  678. get => GetParent() as Folder;
  679. set
  680. {
  681. }
  682. }
  683. public void SetParent(Folder parent)
  684. {
  685. ParentId = parent == null ? Guid.Empty : parent.Id;
  686. }
  687. public BaseItem GetParent()
  688. {
  689. var parentId = ParentId;
  690. if (!parentId.Equals(Guid.Empty))
  691. {
  692. return LibraryManager.GetItemById(parentId);
  693. }
  694. return null;
  695. }
  696. public IEnumerable<BaseItem> GetParents()
  697. {
  698. var parent = GetParent();
  699. while (parent != null)
  700. {
  701. yield return parent;
  702. parent = parent.GetParent();
  703. }
  704. }
  705. /// <summary>
  706. /// Finds a parent of a given type.
  707. /// </summary>
  708. /// <typeparam name="T"></typeparam>
  709. /// <returns>``0.</returns>
  710. public T FindParent<T>()
  711. where T : Folder
  712. {
  713. foreach (var parent in GetParents())
  714. {
  715. var item = parent as T;
  716. if (item != null)
  717. {
  718. return item;
  719. }
  720. }
  721. return null;
  722. }
  723. [JsonIgnore]
  724. public virtual Guid DisplayParentId
  725. {
  726. get
  727. {
  728. var parentId = ParentId;
  729. return parentId;
  730. }
  731. }
  732. [JsonIgnore]
  733. public BaseItem DisplayParent
  734. {
  735. get
  736. {
  737. var id = DisplayParentId;
  738. if (id.Equals(Guid.Empty))
  739. {
  740. return null;
  741. }
  742. return LibraryManager.GetItemById(id);
  743. }
  744. }
  745. /// <summary>
  746. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  747. /// </summary>
  748. /// <value>The premiere date.</value>
  749. [JsonIgnore]
  750. public DateTime? PremiereDate { get; set; }
  751. /// <summary>
  752. /// Gets or sets the end date.
  753. /// </summary>
  754. /// <value>The end date.</value>
  755. [JsonIgnore]
  756. public DateTime? EndDate { get; set; }
  757. /// <summary>
  758. /// Gets or sets the official rating.
  759. /// </summary>
  760. /// <value>The official rating.</value>
  761. [JsonIgnore]
  762. public string OfficialRating { get; set; }
  763. [JsonIgnore]
  764. public int InheritedParentalRatingValue { get; set; }
  765. /// <summary>
  766. /// Gets or sets the critic rating.
  767. /// </summary>
  768. /// <value>The critic rating.</value>
  769. [JsonIgnore]
  770. public float? CriticRating { get; set; }
  771. /// <summary>
  772. /// Gets or sets the custom rating.
  773. /// </summary>
  774. /// <value>The custom rating.</value>
  775. [JsonIgnore]
  776. public string CustomRating { get; set; }
  777. /// <summary>
  778. /// Gets or sets the overview.
  779. /// </summary>
  780. /// <value>The overview.</value>
  781. [JsonIgnore]
  782. public string Overview { get; set; }
  783. /// <summary>
  784. /// Gets or sets the studios.
  785. /// </summary>
  786. /// <value>The studios.</value>
  787. [JsonIgnore]
  788. public string[] Studios { get; set; }
  789. /// <summary>
  790. /// Gets or sets the genres.
  791. /// </summary>
  792. /// <value>The genres.</value>
  793. [JsonIgnore]
  794. public string[] Genres { get; set; }
  795. /// <summary>
  796. /// Gets or sets the tags.
  797. /// </summary>
  798. /// <value>The tags.</value>
  799. [JsonIgnore]
  800. public string[] Tags { get; set; }
  801. [JsonIgnore]
  802. public string[] ProductionLocations { get; set; }
  803. /// <summary>
  804. /// Gets or sets the home page URL.
  805. /// </summary>
  806. /// <value>The home page URL.</value>
  807. [JsonIgnore]
  808. public string HomePageUrl { get; set; }
  809. /// <summary>
  810. /// Gets or sets the community rating.
  811. /// </summary>
  812. /// <value>The community rating.</value>
  813. [JsonIgnore]
  814. public float? CommunityRating { get; set; }
  815. /// <summary>
  816. /// Gets or sets the run time ticks.
  817. /// </summary>
  818. /// <value>The run time ticks.</value>
  819. [JsonIgnore]
  820. public long? RunTimeTicks { get; set; }
  821. /// <summary>
  822. /// Gets or sets the production year.
  823. /// </summary>
  824. /// <value>The production year.</value>
  825. [JsonIgnore]
  826. public int? ProductionYear { get; set; }
  827. /// <summary>
  828. /// If the item is part of a series, this is it's number in the series.
  829. /// This could be episode number, album track number, etc.
  830. /// </summary>
  831. /// <value>The index number.</value>
  832. [JsonIgnore]
  833. public int? IndexNumber { get; set; }
  834. /// <summary>
  835. /// For an episode this could be the season number, or for a song this could be the disc number.
  836. /// </summary>
  837. /// <value>The parent index number.</value>
  838. [JsonIgnore]
  839. public int? ParentIndexNumber { get; set; }
  840. [JsonIgnore]
  841. public virtual bool HasLocalAlternateVersions => false;
  842. [JsonIgnore]
  843. public string OfficialRatingForComparison
  844. {
  845. get
  846. {
  847. var officialRating = OfficialRating;
  848. if (!string.IsNullOrEmpty(officialRating))
  849. {
  850. return officialRating;
  851. }
  852. var parent = DisplayParent;
  853. if (parent != null)
  854. {
  855. return parent.OfficialRatingForComparison;
  856. }
  857. return null;
  858. }
  859. }
  860. [JsonIgnore]
  861. public string CustomRatingForComparison
  862. {
  863. get
  864. {
  865. var customRating = CustomRating;
  866. if (!string.IsNullOrEmpty(customRating))
  867. {
  868. return customRating;
  869. }
  870. var parent = DisplayParent;
  871. if (parent != null)
  872. {
  873. return parent.CustomRatingForComparison;
  874. }
  875. return null;
  876. }
  877. }
  878. /// <summary>
  879. /// Gets the play access.
  880. /// </summary>
  881. /// <param name="user">The user.</param>
  882. /// <returns>PlayAccess.</returns>
  883. public PlayAccess GetPlayAccess(User user)
  884. {
  885. if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
  886. {
  887. return PlayAccess.None;
  888. }
  889. // if (!user.IsParentalScheduleAllowed())
  890. //{
  891. // return PlayAccess.None;
  892. //}
  893. return PlayAccess.Full;
  894. }
  895. public virtual List<MediaStream> GetMediaStreams()
  896. {
  897. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  898. {
  899. ItemId = Id
  900. });
  901. }
  902. protected virtual bool IsActiveRecording()
  903. {
  904. return false;
  905. }
  906. public virtual List<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  907. {
  908. if (SourceType == SourceType.Channel)
  909. {
  910. var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
  911. .ToList();
  912. if (sources.Count > 0)
  913. {
  914. return sources;
  915. }
  916. }
  917. var list = GetAllItemsForMediaSources();
  918. var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item1, i.Item2)).ToList();
  919. if (IsActiveRecording())
  920. {
  921. foreach (var mediaSource in result)
  922. {
  923. mediaSource.Type = MediaSourceType.Placeholder;
  924. }
  925. }
  926. return result.OrderBy(i =>
  927. {
  928. if (i.VideoType == VideoType.VideoFile)
  929. {
  930. return 0;
  931. }
  932. return 1;
  933. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  934. .ThenByDescending(i =>
  935. {
  936. var stream = i.VideoStream;
  937. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  938. })
  939. .ToList();
  940. }
  941. protected virtual List<Tuple<BaseItem, MediaSourceType>> GetAllItemsForMediaSources()
  942. {
  943. return new List<Tuple<BaseItem, MediaSourceType>>();
  944. }
  945. private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
  946. {
  947. if (item == null)
  948. {
  949. throw new ArgumentNullException(nameof(item));
  950. }
  951. var protocol = item.PathProtocol;
  952. var info = new MediaSourceInfo
  953. {
  954. Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
  955. Protocol = protocol ?? MediaProtocol.File,
  956. MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
  957. MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
  958. Name = GetMediaSourceName(item),
  959. Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
  960. RunTimeTicks = item.RunTimeTicks,
  961. Container = item.Container,
  962. Size = item.Size,
  963. Type = type
  964. };
  965. if (string.IsNullOrEmpty(info.Path))
  966. {
  967. info.Type = MediaSourceType.Placeholder;
  968. }
  969. if (info.Protocol == MediaProtocol.File)
  970. {
  971. info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  972. }
  973. var video = item as Video;
  974. if (video != null)
  975. {
  976. info.IsoType = video.IsoType;
  977. info.VideoType = video.VideoType;
  978. info.Video3DFormat = video.Video3DFormat;
  979. info.Timestamp = video.Timestamp;
  980. if (video.IsShortcut)
  981. {
  982. info.IsRemote = true;
  983. info.Path = video.ShortcutPath;
  984. info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
  985. }
  986. if (string.IsNullOrEmpty(info.Container))
  987. {
  988. if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
  989. {
  990. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  991. {
  992. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  993. }
  994. }
  995. }
  996. }
  997. if (string.IsNullOrEmpty(info.Container))
  998. {
  999. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  1000. {
  1001. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  1002. }
  1003. }
  1004. if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
  1005. {
  1006. info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
  1007. }
  1008. if (video != null && video.VideoType != VideoType.VideoFile)
  1009. {
  1010. info.SupportsDirectStream = false;
  1011. }
  1012. info.Bitrate = item.TotalBitrate;
  1013. info.InferTotalBitrate();
  1014. return info;
  1015. }
  1016. private string GetMediaSourceName(BaseItem item)
  1017. {
  1018. var terms = new List<string>();
  1019. var path = item.Path;
  1020. if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
  1021. {
  1022. if (HasLocalAlternateVersions)
  1023. {
  1024. var displayName = System.IO.Path.GetFileNameWithoutExtension(path)
  1025. .Replace(System.IO.Path.GetFileName(ContainingFolderPath), string.Empty, StringComparison.OrdinalIgnoreCase)
  1026. .TrimStart(new char[] { ' ', '-' });
  1027. if (!string.IsNullOrEmpty(displayName))
  1028. {
  1029. terms.Add(displayName);
  1030. }
  1031. }
  1032. if (terms.Count == 0)
  1033. {
  1034. var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
  1035. terms.Add(displayName);
  1036. }
  1037. }
  1038. if (terms.Count == 0)
  1039. {
  1040. terms.Add(item.Name);
  1041. }
  1042. var video = item as Video;
  1043. if (video != null)
  1044. {
  1045. if (video.Video3DFormat.HasValue)
  1046. {
  1047. terms.Add("3D");
  1048. }
  1049. if (video.VideoType == VideoType.BluRay)
  1050. {
  1051. terms.Add("Bluray");
  1052. }
  1053. else if (video.VideoType == VideoType.Dvd)
  1054. {
  1055. terms.Add("DVD");
  1056. }
  1057. else if (video.VideoType == VideoType.Iso)
  1058. {
  1059. if (video.IsoType.HasValue)
  1060. {
  1061. if (video.IsoType.Value == IsoType.BluRay)
  1062. {
  1063. terms.Add("Bluray");
  1064. }
  1065. else if (video.IsoType.Value == IsoType.Dvd)
  1066. {
  1067. terms.Add("DVD");
  1068. }
  1069. }
  1070. else
  1071. {
  1072. terms.Add("ISO");
  1073. }
  1074. }
  1075. }
  1076. return string.Join("/", terms.ToArray());
  1077. }
  1078. /// <summary>
  1079. /// Loads the theme songs.
  1080. /// </summary>
  1081. /// <returns>List{Audio.Audio}.</returns>
  1082. private static Audio.Audio[] LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1083. {
  1084. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1085. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  1086. .SelectMany(i => FileSystem.GetFiles(i.FullName))
  1087. .ToList();
  1088. // Support plex/xbmc convention
  1089. files.AddRange(fileSystemChildren
  1090. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase)));
  1091. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1092. .OfType<Audio.Audio>()
  1093. .Select(audio =>
  1094. {
  1095. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1096. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  1097. if (dbItem != null)
  1098. {
  1099. audio = dbItem;
  1100. }
  1101. else
  1102. {
  1103. // item is new
  1104. audio.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong;
  1105. }
  1106. return audio;
  1107. // Sort them so that the list can be easily compared for changes
  1108. }).OrderBy(i => i.Path).ToArray();
  1109. }
  1110. /// <summary>
  1111. /// Loads the video backdrops.
  1112. /// </summary>
  1113. /// <returns>List{Video}.</returns>
  1114. private static Video[] LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1115. {
  1116. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1117. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  1118. .SelectMany(i => FileSystem.GetFiles(i.FullName));
  1119. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1120. .OfType<Video>()
  1121. .Select(item =>
  1122. {
  1123. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1124. if (LibraryManager.GetItemById(item.Id) is Video dbItem)
  1125. {
  1126. item = dbItem;
  1127. }
  1128. else
  1129. {
  1130. // item is new
  1131. item.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1132. }
  1133. return item;
  1134. // Sort them so that the list can be easily compared for changes
  1135. }).OrderBy(i => i.Path).ToArray();
  1136. }
  1137. protected virtual BaseItem[] LoadExtras(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1138. {
  1139. var extras = new List<Video>();
  1140. var folders = fileSystemChildren.Where(i => i.IsDirectory).ToArray();
  1141. foreach (var extraFolderName in AllExtrasTypesFolderNames)
  1142. {
  1143. var files = folders
  1144. .Where(i => string.Equals(i.Name, extraFolderName, StringComparison.OrdinalIgnoreCase))
  1145. .SelectMany(i => FileSystem.GetFiles(i.FullName));
  1146. extras.AddRange(LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1147. .OfType<Video>()
  1148. .Select(item =>
  1149. {
  1150. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1151. if (LibraryManager.GetItemById(item.Id) is Video dbItem)
  1152. {
  1153. item = dbItem;
  1154. }
  1155. // Use some hackery to get the extra type based on foldername
  1156. item.ExtraType = Enum.TryParse(extraFolderName.Replace(" ", string.Empty), true, out ExtraType extraType)
  1157. ? extraType
  1158. : Model.Entities.ExtraType.Unknown;
  1159. return item;
  1160. // Sort them so that the list can be easily compared for changes
  1161. }).OrderBy(i => i.Path));
  1162. }
  1163. return extras.ToArray();
  1164. }
  1165. public Task RefreshMetadata(CancellationToken cancellationToken)
  1166. {
  1167. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  1168. }
  1169. protected virtual void TriggerOnRefreshStart()
  1170. {
  1171. }
  1172. protected virtual void TriggerOnRefreshComplete()
  1173. {
  1174. }
  1175. /// <summary>
  1176. /// Overrides the base implementation to refresh metadata for local trailers.
  1177. /// </summary>
  1178. /// <param name="options">The options.</param>
  1179. /// <param name="cancellationToken">The cancellation token.</param>
  1180. /// <returns>true if a provider reports we changed.</returns>
  1181. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  1182. {
  1183. TriggerOnRefreshStart();
  1184. var requiresSave = false;
  1185. if (SupportsOwnedItems)
  1186. {
  1187. try
  1188. {
  1189. var files = IsFileProtocol ?
  1190. GetFileSystemChildren(options.DirectoryService).ToList() :
  1191. new List<FileSystemMetadata>();
  1192. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  1193. await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh
  1194. if (ownedItemsChanged)
  1195. {
  1196. requiresSave = true;
  1197. }
  1198. }
  1199. catch (Exception ex)
  1200. {
  1201. Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name);
  1202. }
  1203. }
  1204. try
  1205. {
  1206. var refreshOptions = requiresSave
  1207. ? new MetadataRefreshOptions(options)
  1208. {
  1209. ForceSave = true
  1210. }
  1211. : options;
  1212. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1213. }
  1214. finally
  1215. {
  1216. TriggerOnRefreshComplete();
  1217. }
  1218. }
  1219. [JsonIgnore]
  1220. protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol;
  1221. [JsonIgnore]
  1222. public virtual bool SupportsPeople => false;
  1223. [JsonIgnore]
  1224. public virtual bool SupportsThemeMedia => false;
  1225. /// <summary>
  1226. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1227. /// Returns true or false indicating if changes were found.
  1228. /// </summary>
  1229. /// <param name="options"></param>
  1230. /// <param name="fileSystemChildren"></param>
  1231. /// <param name="cancellationToken"></param>
  1232. /// <returns></returns>
  1233. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1234. {
  1235. var themeSongsChanged = false;
  1236. var themeVideosChanged = false;
  1237. var extrasChanged = false;
  1238. var localTrailersChanged = false;
  1239. if (IsFileProtocol && SupportsOwnedItems)
  1240. {
  1241. if (SupportsThemeMedia)
  1242. {
  1243. if (!IsInMixedFolder)
  1244. {
  1245. themeSongsChanged = await RefreshThemeSongs(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1246. themeVideosChanged = await RefreshThemeVideos(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1247. extrasChanged = await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1248. }
  1249. }
  1250. var hasTrailers = this as IHasTrailers;
  1251. if (hasTrailers != null)
  1252. {
  1253. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1254. }
  1255. }
  1256. return themeSongsChanged || themeVideosChanged || extrasChanged || localTrailersChanged;
  1257. }
  1258. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1259. {
  1260. var path = ContainingFolderPath;
  1261. return directoryService.GetFileSystemEntries(path);
  1262. }
  1263. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1264. {
  1265. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService);
  1266. var newItemIds = newItems.Select(i => i.Id);
  1267. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  1268. var ownerId = item.Id;
  1269. var tasks = newItems.Select(i =>
  1270. {
  1271. var subOptions = new MetadataRefreshOptions(options);
  1272. if (i.ExtraType != Model.Entities.ExtraType.Trailer ||
  1273. i.OwnerId != ownerId ||
  1274. !i.ParentId.Equals(Guid.Empty))
  1275. {
  1276. i.ExtraType = Model.Entities.ExtraType.Trailer;
  1277. i.OwnerId = ownerId;
  1278. i.ParentId = Guid.Empty;
  1279. subOptions.ForceSave = true;
  1280. }
  1281. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1282. });
  1283. await Task.WhenAll(tasks).ConfigureAwait(false);
  1284. item.LocalTrailerIds = newItemIds.ToArray();
  1285. return itemsChanged;
  1286. }
  1287. private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1288. {
  1289. var extras = LoadExtras(fileSystemChildren, options.DirectoryService);
  1290. var themeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1291. var themeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1292. var newExtras = new BaseItem[extras.Length + themeVideos.Length + themeSongs.Length];
  1293. extras.CopyTo(newExtras, 0);
  1294. themeVideos.CopyTo(newExtras, extras.Length);
  1295. themeSongs.CopyTo(newExtras, extras.Length + themeVideos.Length);
  1296. var newExtraIds = newExtras.Select(i => i.Id).ToArray();
  1297. var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
  1298. if (extrasChanged)
  1299. {
  1300. var ownerId = item.Id;
  1301. var tasks = newExtras.Select(i =>
  1302. {
  1303. var subOptions = new MetadataRefreshOptions(options);
  1304. if (i.OwnerId != ownerId || i.ParentId != Guid.Empty)
  1305. {
  1306. i.OwnerId = ownerId;
  1307. i.ParentId = Guid.Empty;
  1308. subOptions.ForceSave = true;
  1309. }
  1310. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1311. });
  1312. await Task.WhenAll(tasks).ConfigureAwait(false);
  1313. item.ExtraIds = newExtraIds;
  1314. }
  1315. return extrasChanged;
  1316. }
  1317. private async Task<bool> RefreshThemeVideos(BaseItem item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1318. {
  1319. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1320. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToArray();
  1321. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  1322. var ownerId = item.Id;
  1323. var tasks = newThemeVideos.Select(i =>
  1324. {
  1325. var subOptions = new MetadataRefreshOptions(options);
  1326. if (!i.ExtraType.HasValue ||
  1327. i.ExtraType.Value != Model.Entities.ExtraType.ThemeVideo ||
  1328. i.OwnerId != ownerId ||
  1329. !i.ParentId.Equals(Guid.Empty))
  1330. {
  1331. i.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1332. i.OwnerId = ownerId;
  1333. i.ParentId = Guid.Empty;
  1334. subOptions.ForceSave = true;
  1335. }
  1336. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1337. });
  1338. await Task.WhenAll(tasks).ConfigureAwait(false);
  1339. // They are expected to be sorted by SortName
  1340. item.ThemeVideoIds = newThemeVideos.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
  1341. return themeVideosChanged;
  1342. }
  1343. /// <summary>
  1344. /// Refreshes the theme songs.
  1345. /// </summary>
  1346. private async Task<bool> RefreshThemeSongs(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1347. {
  1348. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1349. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToArray();
  1350. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  1351. var ownerId = item.Id;
  1352. var tasks = newThemeSongs.Select(i =>
  1353. {
  1354. var subOptions = new MetadataRefreshOptions(options);
  1355. if (!i.ExtraType.HasValue ||
  1356. i.ExtraType.Value != Model.Entities.ExtraType.ThemeSong ||
  1357. i.OwnerId != ownerId ||
  1358. !i.ParentId.Equals(Guid.Empty))
  1359. {
  1360. i.ExtraType = Model.Entities.ExtraType.ThemeSong;
  1361. i.OwnerId = ownerId;
  1362. i.ParentId = Guid.Empty;
  1363. subOptions.ForceSave = true;
  1364. }
  1365. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1366. });
  1367. await Task.WhenAll(tasks).ConfigureAwait(false);
  1368. // They are expected to be sorted by SortName
  1369. item.ThemeSongIds = newThemeSongs.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
  1370. return themeSongsChanged;
  1371. }
  1372. /// <summary>
  1373. /// Gets or sets the provider ids.
  1374. /// </summary>
  1375. /// <value>The provider ids.</value>
  1376. [JsonIgnore]
  1377. public Dictionary<string, string> ProviderIds { get; set; }
  1378. [JsonIgnore]
  1379. public virtual Folder LatestItemsIndexContainer => null;
  1380. public virtual double GetDefaultPrimaryImageAspectRatio()
  1381. {
  1382. return 0;
  1383. }
  1384. public virtual string CreatePresentationUniqueKey()
  1385. {
  1386. return Id.ToString("N", CultureInfo.InvariantCulture);
  1387. }
  1388. [JsonIgnore]
  1389. public string PresentationUniqueKey { get; set; }
  1390. public string GetPresentationUniqueKey()
  1391. {
  1392. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1393. }
  1394. public virtual bool RequiresRefresh()
  1395. {
  1396. return false;
  1397. }
  1398. public virtual List<string> GetUserDataKeys()
  1399. {
  1400. var list = new List<string>();
  1401. if (SourceType == SourceType.Channel)
  1402. {
  1403. if (!string.IsNullOrEmpty(ExternalId))
  1404. {
  1405. list.Add(ExternalId);
  1406. }
  1407. }
  1408. list.Add(Id.ToString());
  1409. return list;
  1410. }
  1411. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1412. {
  1413. var updateType = ItemUpdateType.None;
  1414. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1415. {
  1416. IsInMixedFolder = newItem.IsInMixedFolder;
  1417. updateType |= ItemUpdateType.MetadataImport;
  1418. }
  1419. return updateType;
  1420. }
  1421. public void AfterMetadataRefresh()
  1422. {
  1423. _sortName = null;
  1424. }
  1425. /// <summary>
  1426. /// Gets the preferred metadata language.
  1427. /// </summary>
  1428. /// <returns>System.String.</returns>
  1429. public string GetPreferredMetadataLanguage()
  1430. {
  1431. string lang = PreferredMetadataLanguage;
  1432. if (string.IsNullOrEmpty(lang))
  1433. {
  1434. lang = GetParents()
  1435. .Select(i => i.PreferredMetadataLanguage)
  1436. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1437. }
  1438. if (string.IsNullOrEmpty(lang))
  1439. {
  1440. lang = LibraryManager.GetCollectionFolders(this)
  1441. .Select(i => i.PreferredMetadataLanguage)
  1442. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1443. }
  1444. if (string.IsNullOrEmpty(lang))
  1445. {
  1446. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1447. }
  1448. if (string.IsNullOrEmpty(lang))
  1449. {
  1450. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1451. }
  1452. return lang;
  1453. }
  1454. /// <summary>
  1455. /// Gets the preferred metadata language.
  1456. /// </summary>
  1457. /// <returns>System.String.</returns>
  1458. public string GetPreferredMetadataCountryCode()
  1459. {
  1460. string lang = PreferredMetadataCountryCode;
  1461. if (string.IsNullOrEmpty(lang))
  1462. {
  1463. lang = GetParents()
  1464. .Select(i => i.PreferredMetadataCountryCode)
  1465. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1466. }
  1467. if (string.IsNullOrEmpty(lang))
  1468. {
  1469. lang = LibraryManager.GetCollectionFolders(this)
  1470. .Select(i => i.PreferredMetadataCountryCode)
  1471. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1472. }
  1473. if (string.IsNullOrEmpty(lang))
  1474. {
  1475. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1476. }
  1477. if (string.IsNullOrEmpty(lang))
  1478. {
  1479. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1480. }
  1481. return lang;
  1482. }
  1483. public virtual bool IsSaveLocalMetadataEnabled()
  1484. {
  1485. if (SourceType == SourceType.Channel)
  1486. {
  1487. return false;
  1488. }
  1489. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1490. return libraryOptions.SaveLocalMetadata;
  1491. }
  1492. /// <summary>
  1493. /// Determines if a given user has access to this item.
  1494. /// </summary>
  1495. /// <param name="user">The user.</param>
  1496. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1497. /// <exception cref="ArgumentNullException">user</exception>
  1498. public bool IsParentalAllowed(User user)
  1499. {
  1500. if (user == null)
  1501. {
  1502. throw new ArgumentNullException(nameof(user));
  1503. }
  1504. if (!IsVisibleViaTags(user))
  1505. {
  1506. return false;
  1507. }
  1508. var maxAllowedRating = user.MaxParentalAgeRating;
  1509. if (maxAllowedRating == null)
  1510. {
  1511. return true;
  1512. }
  1513. var rating = CustomRatingForComparison;
  1514. if (string.IsNullOrEmpty(rating))
  1515. {
  1516. rating = OfficialRatingForComparison;
  1517. }
  1518. if (string.IsNullOrEmpty(rating))
  1519. {
  1520. return !GetBlockUnratedValue(user);
  1521. }
  1522. var value = LocalizationManager.GetRatingLevel(rating);
  1523. // Could not determine the integer value
  1524. if (!value.HasValue)
  1525. {
  1526. var isAllowed = !GetBlockUnratedValue(user);
  1527. if (!isAllowed)
  1528. {
  1529. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1530. }
  1531. return isAllowed;
  1532. }
  1533. return value.Value <= maxAllowedRating.Value;
  1534. }
  1535. public int? GetParentalRatingValue()
  1536. {
  1537. var rating = CustomRating;
  1538. if (string.IsNullOrEmpty(rating))
  1539. {
  1540. rating = OfficialRating;
  1541. }
  1542. if (string.IsNullOrEmpty(rating))
  1543. {
  1544. return null;
  1545. }
  1546. return LocalizationManager.GetRatingLevel(rating);
  1547. }
  1548. public int? GetInheritedParentalRatingValue()
  1549. {
  1550. var rating = CustomRatingForComparison;
  1551. if (string.IsNullOrEmpty(rating))
  1552. {
  1553. rating = OfficialRatingForComparison;
  1554. }
  1555. if (string.IsNullOrEmpty(rating))
  1556. {
  1557. return null;
  1558. }
  1559. return LocalizationManager.GetRatingLevel(rating);
  1560. }
  1561. public List<string> GetInheritedTags()
  1562. {
  1563. var list = new List<string>();
  1564. list.AddRange(Tags);
  1565. foreach (var parent in GetParents())
  1566. {
  1567. list.AddRange(parent.Tags);
  1568. }
  1569. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1570. }
  1571. private bool IsVisibleViaTags(User user)
  1572. {
  1573. if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1574. {
  1575. return false;
  1576. }
  1577. return true;
  1578. }
  1579. protected virtual bool IsAllowTagFilterEnforced()
  1580. {
  1581. return true;
  1582. }
  1583. public virtual UnratedItem GetBlockUnratedType()
  1584. {
  1585. if (SourceType == SourceType.Channel)
  1586. {
  1587. return UnratedItem.ChannelContent;
  1588. }
  1589. return UnratedItem.Other;
  1590. }
  1591. /// <summary>
  1592. /// Gets the block unrated value.
  1593. /// </summary>
  1594. /// <param name="user">The configuration.</param>
  1595. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1596. protected virtual bool GetBlockUnratedValue(User user)
  1597. {
  1598. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1599. // Special folders like series and albums will override this method.
  1600. if (IsFolder || this is IItemByName)
  1601. {
  1602. return false;
  1603. }
  1604. return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType().ToString());
  1605. }
  1606. /// <summary>
  1607. /// Determines if this folder should be visible to a given user.
  1608. /// Default is just parental allowed. Can be overridden for more functionality.
  1609. /// </summary>
  1610. /// <param name="user">The user.</param>
  1611. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1612. /// <exception cref="ArgumentNullException">user</exception>
  1613. public virtual bool IsVisible(User user)
  1614. {
  1615. if (user == null)
  1616. {
  1617. throw new ArgumentNullException(nameof(user));
  1618. }
  1619. return IsParentalAllowed(user);
  1620. }
  1621. public virtual bool IsVisibleStandalone(User user)
  1622. {
  1623. if (SourceType == SourceType.Channel)
  1624. {
  1625. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1626. }
  1627. return IsVisibleStandaloneInternal(user, true);
  1628. }
  1629. [JsonIgnore]
  1630. public virtual bool SupportsInheritedParentImages => false;
  1631. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1632. {
  1633. if (!IsVisible(user))
  1634. {
  1635. return false;
  1636. }
  1637. if (GetParents().Any(i => !i.IsVisible(user)))
  1638. {
  1639. return false;
  1640. }
  1641. if (checkFolders)
  1642. {
  1643. var topParent = GetParents().LastOrDefault() ?? this;
  1644. if (string.IsNullOrEmpty(topParent.Path))
  1645. {
  1646. return true;
  1647. }
  1648. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1649. if (itemCollectionFolders.Count > 0)
  1650. {
  1651. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1652. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1653. {
  1654. return false;
  1655. }
  1656. }
  1657. }
  1658. return true;
  1659. }
  1660. /// <summary>
  1661. /// Gets a value indicating whether this instance is folder.
  1662. /// </summary>
  1663. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1664. [JsonIgnore]
  1665. public virtual bool IsFolder => false;
  1666. [JsonIgnore]
  1667. public virtual bool IsDisplayedAsFolder => false;
  1668. public virtual string GetClientTypeName()
  1669. {
  1670. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1671. {
  1672. return "ChannelFolderItem";
  1673. }
  1674. return GetType().Name;
  1675. }
  1676. /// <summary>
  1677. /// Gets the linked child.
  1678. /// </summary>
  1679. /// <param name="info">The info.</param>
  1680. /// <returns>BaseItem.</returns>
  1681. protected BaseItem GetLinkedChild(LinkedChild info)
  1682. {
  1683. // First get using the cached Id
  1684. if (info.ItemId.HasValue)
  1685. {
  1686. if (info.ItemId.Value.Equals(Guid.Empty))
  1687. {
  1688. return null;
  1689. }
  1690. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1691. if (itemById != null)
  1692. {
  1693. return itemById;
  1694. }
  1695. }
  1696. var item = FindLinkedChild(info);
  1697. // If still null, log
  1698. if (item == null)
  1699. {
  1700. // Don't keep searching over and over
  1701. info.ItemId = Guid.Empty;
  1702. }
  1703. else
  1704. {
  1705. // Cache the id for next time
  1706. info.ItemId = item.Id;
  1707. }
  1708. return item;
  1709. }
  1710. private BaseItem FindLinkedChild(LinkedChild info)
  1711. {
  1712. var path = info.Path;
  1713. if (!string.IsNullOrEmpty(path))
  1714. {
  1715. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1716. var itemByPath = LibraryManager.FindByPath(path, null);
  1717. if (itemByPath == null)
  1718. {
  1719. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1720. }
  1721. return itemByPath;
  1722. }
  1723. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1724. {
  1725. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1726. if (item == null)
  1727. {
  1728. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1729. }
  1730. return item;
  1731. }
  1732. return null;
  1733. }
  1734. [JsonIgnore]
  1735. public virtual bool EnableRememberingTrackSelections => true;
  1736. /// <summary>
  1737. /// Adds a studio to the item.
  1738. /// </summary>
  1739. /// <param name="name">The name.</param>
  1740. /// <exception cref="ArgumentNullException"></exception>
  1741. public void AddStudio(string name)
  1742. {
  1743. if (string.IsNullOrEmpty(name))
  1744. {
  1745. throw new ArgumentNullException(nameof(name));
  1746. }
  1747. var current = Studios;
  1748. if (!current.Contains(name, StringComparer.OrdinalIgnoreCase))
  1749. {
  1750. int curLen = current.Length;
  1751. if (curLen == 0)
  1752. {
  1753. Studios = new[] { name };
  1754. }
  1755. else
  1756. {
  1757. var newArr = new string[curLen + 1];
  1758. current.CopyTo(newArr, 0);
  1759. newArr[curLen] = name;
  1760. Studios = newArr;
  1761. }
  1762. }
  1763. }
  1764. public void SetStudios(IEnumerable<string> names)
  1765. {
  1766. Studios = names.Distinct().ToArray();
  1767. }
  1768. /// <summary>
  1769. /// Adds a genre to the item.
  1770. /// </summary>
  1771. /// <param name="name">The name.</param>
  1772. /// <exception cref="ArgumentNullException"></exception>
  1773. public void AddGenre(string name)
  1774. {
  1775. if (string.IsNullOrEmpty(name))
  1776. {
  1777. throw new ArgumentNullException(nameof(name));
  1778. }
  1779. var genres = Genres;
  1780. if (!genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1781. {
  1782. var list = genres.ToList();
  1783. list.Add(name);
  1784. Genres = list.ToArray();
  1785. }
  1786. }
  1787. /// <summary>
  1788. /// Marks the played.
  1789. /// </summary>
  1790. /// <param name="user">The user.</param>
  1791. /// <param name="datePlayed">The date played.</param>
  1792. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1793. /// <returns>Task.</returns>
  1794. /// <exception cref="ArgumentNullException"></exception>
  1795. public virtual void MarkPlayed(
  1796. User user,
  1797. DateTime? datePlayed,
  1798. bool resetPosition)
  1799. {
  1800. if (user == null)
  1801. {
  1802. throw new ArgumentNullException(nameof(user));
  1803. }
  1804. var data = UserDataManager.GetUserData(user, this);
  1805. if (datePlayed.HasValue)
  1806. {
  1807. // Increment
  1808. data.PlayCount++;
  1809. }
  1810. // Ensure it's at least one
  1811. data.PlayCount = Math.Max(data.PlayCount, 1);
  1812. if (resetPosition)
  1813. {
  1814. data.PlaybackPositionTicks = 0;
  1815. }
  1816. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1817. data.Played = true;
  1818. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1819. }
  1820. /// <summary>
  1821. /// Marks the unplayed.
  1822. /// </summary>
  1823. /// <param name="user">The user.</param>
  1824. /// <returns>Task.</returns>
  1825. /// <exception cref="ArgumentNullException"></exception>
  1826. public virtual void MarkUnplayed(User user)
  1827. {
  1828. if (user == null)
  1829. {
  1830. throw new ArgumentNullException(nameof(user));
  1831. }
  1832. var data = UserDataManager.GetUserData(user, this);
  1833. // I think it is okay to do this here.
  1834. // if this is only called when a user is manually forcing something to un-played
  1835. // then it probably is what we want to do...
  1836. data.PlayCount = 0;
  1837. data.PlaybackPositionTicks = 0;
  1838. data.LastPlayedDate = null;
  1839. data.Played = false;
  1840. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1841. }
  1842. /// <summary>
  1843. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1844. /// </summary>
  1845. public virtual void ChangedExternally()
  1846. {
  1847. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
  1848. }
  1849. /// <summary>
  1850. /// Gets an image.
  1851. /// </summary>
  1852. /// <param name="type">The type.</param>
  1853. /// <param name="imageIndex">Index of the image.</param>
  1854. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1855. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1856. public bool HasImage(ImageType type, int imageIndex)
  1857. {
  1858. return GetImageInfo(type, imageIndex) != null;
  1859. }
  1860. public void SetImage(ItemImageInfo image, int index)
  1861. {
  1862. if (image.Type == ImageType.Chapter)
  1863. {
  1864. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1865. }
  1866. var existingImage = GetImageInfo(image.Type, index);
  1867. if (existingImage != null)
  1868. {
  1869. existingImage.Path = image.Path;
  1870. existingImage.DateModified = image.DateModified;
  1871. existingImage.Width = image.Width;
  1872. existingImage.Height = image.Height;
  1873. existingImage.BlurHash = image.BlurHash;
  1874. }
  1875. else
  1876. {
  1877. var current = ImageInfos;
  1878. var currentCount = current.Length;
  1879. var newArr = new ItemImageInfo[currentCount + 1];
  1880. current.CopyTo(newArr, 0);
  1881. newArr[currentCount] = image;
  1882. ImageInfos = newArr;
  1883. }
  1884. }
  1885. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1886. {
  1887. if (type == ImageType.Chapter)
  1888. {
  1889. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1890. }
  1891. var image = GetImageInfo(type, index);
  1892. if (image == null)
  1893. {
  1894. ImageInfos = ImageInfos.Concat(new[] { GetImageInfo(file, type) }).ToArray();
  1895. }
  1896. else
  1897. {
  1898. var imageInfo = GetImageInfo(file, type);
  1899. image.Path = file.FullName;
  1900. image.DateModified = imageInfo.DateModified;
  1901. // reset these values
  1902. image.Width = 0;
  1903. image.Height = 0;
  1904. }
  1905. }
  1906. /// <summary>
  1907. /// Deletes the image.
  1908. /// </summary>
  1909. /// <param name="type">The type.</param>
  1910. /// <param name="index">The index.</param>
  1911. public async Task DeleteImageAsync(ImageType type, int index)
  1912. {
  1913. var info = GetImageInfo(type, index);
  1914. if (info == null)
  1915. {
  1916. // Nothing to do
  1917. return;
  1918. }
  1919. // Remove it from the item
  1920. RemoveImage(info);
  1921. if (info.IsLocalFile)
  1922. {
  1923. FileSystem.DeleteFile(info.Path);
  1924. }
  1925. await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  1926. }
  1927. public void RemoveImage(ItemImageInfo image)
  1928. {
  1929. RemoveImages(new List<ItemImageInfo> { image });
  1930. }
  1931. public void RemoveImages(List<ItemImageInfo> deletedImages)
  1932. {
  1933. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1934. }
  1935. public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1936. => LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken);
  1937. /// <summary>
  1938. /// Validates that images within the item are still on the filesystem.
  1939. /// </summary>
  1940. public bool ValidateImages(IDirectoryService directoryService)
  1941. {
  1942. var allFiles = ImageInfos
  1943. .Where(i => i.IsLocalFile)
  1944. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1945. .Distinct(StringComparer.OrdinalIgnoreCase)
  1946. .SelectMany(i => directoryService.GetFilePaths(i))
  1947. .ToList();
  1948. var deletedImages = ImageInfos
  1949. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1950. .ToList();
  1951. if (deletedImages.Count > 0)
  1952. {
  1953. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1954. }
  1955. return deletedImages.Count > 0;
  1956. }
  1957. /// <summary>
  1958. /// Gets the image path.
  1959. /// </summary>
  1960. /// <param name="imageType">Type of the image.</param>
  1961. /// <param name="imageIndex">Index of the image.</param>
  1962. /// <returns>System.String.</returns>
  1963. /// <exception cref="InvalidOperationException">
  1964. /// </exception>
  1965. /// <exception cref="ArgumentNullException">item</exception>
  1966. public string GetImagePath(ImageType imageType, int imageIndex)
  1967. => GetImageInfo(imageType, imageIndex)?.Path;
  1968. /// <summary>
  1969. /// Gets the image information.
  1970. /// </summary>
  1971. /// <param name="imageType">Type of the image.</param>
  1972. /// <param name="imageIndex">Index of the image.</param>
  1973. /// <returns>ItemImageInfo.</returns>
  1974. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1975. {
  1976. if (imageType == ImageType.Chapter)
  1977. {
  1978. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1979. if (chapter == null)
  1980. {
  1981. return null;
  1982. }
  1983. var path = chapter.ImagePath;
  1984. if (string.IsNullOrEmpty(path))
  1985. {
  1986. return null;
  1987. }
  1988. return new ItemImageInfo
  1989. {
  1990. Path = path,
  1991. DateModified = chapter.ImageDateModified,
  1992. Type = imageType
  1993. };
  1994. }
  1995. return GetImages(imageType)
  1996. .ElementAtOrDefault(imageIndex);
  1997. }
  1998. /// <summary>
  1999. /// Computes image index for given image or raises if no matching image found.
  2000. /// </summary>
  2001. /// <param name="image">Image to compute index for.</param>
  2002. /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
  2003. /// </exception>
  2004. /// <returns>Image index.</returns>
  2005. public int GetImageIndex(ItemImageInfo image)
  2006. {
  2007. if (image == null)
  2008. {
  2009. throw new ArgumentNullException(nameof(image));
  2010. }
  2011. if (image.Type == ImageType.Chapter)
  2012. {
  2013. var chapters = ItemRepository.GetChapters(this);
  2014. for (var i = 0; i < chapters.Count; i++)
  2015. {
  2016. if (chapters[i].ImagePath == image.Path)
  2017. {
  2018. return i;
  2019. }
  2020. }
  2021. throw new ArgumentException("No chapter index found for image path", image.Path);
  2022. }
  2023. var images = GetImages(image.Type).ToArray();
  2024. for (var i = 0; i < images.Length; i++)
  2025. {
  2026. if (images[i].Path == image.Path)
  2027. {
  2028. return i;
  2029. }
  2030. }
  2031. throw new ArgumentException("No image index found for image path", image.Path);
  2032. }
  2033. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  2034. {
  2035. if (imageType == ImageType.Chapter)
  2036. {
  2037. throw new ArgumentException("No image info for chapter images");
  2038. }
  2039. return ImageInfos.Where(i => i.Type == imageType);
  2040. }
  2041. /// <summary>
  2042. /// Adds the images.
  2043. /// </summary>
  2044. /// <param name="imageType">Type of the image.</param>
  2045. /// <param name="images">The images.</param>
  2046. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  2047. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images</exception>
  2048. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  2049. {
  2050. if (imageType == ImageType.Chapter)
  2051. {
  2052. throw new ArgumentException("Cannot call AddImages with chapter images");
  2053. }
  2054. var existingImages = GetImages(imageType)
  2055. .ToList();
  2056. var newImageList = new List<FileSystemMetadata>();
  2057. var imageAdded = false;
  2058. var imageUpdated = false;
  2059. foreach (var newImage in images)
  2060. {
  2061. if (newImage == null)
  2062. {
  2063. throw new ArgumentException("null image found in list");
  2064. }
  2065. var existing = existingImages
  2066. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  2067. if (existing == null)
  2068. {
  2069. newImageList.Add(newImage);
  2070. imageAdded = true;
  2071. }
  2072. else
  2073. {
  2074. if (existing.IsLocalFile)
  2075. {
  2076. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  2077. // If date changed then we need to reset saved image dimensions
  2078. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  2079. {
  2080. existing.Width = 0;
  2081. existing.Height = 0;
  2082. imageUpdated = true;
  2083. }
  2084. existing.DateModified = newDateModified;
  2085. }
  2086. }
  2087. }
  2088. if (imageAdded || images.Count != existingImages.Count)
  2089. {
  2090. var newImagePaths = images.Select(i => i.FullName).ToList();
  2091. var deleted = existingImages
  2092. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
  2093. .ToList();
  2094. if (deleted.Count > 0)
  2095. {
  2096. ImageInfos = ImageInfos.Except(deleted).ToArray();
  2097. }
  2098. }
  2099. if (newImageList.Count > 0)
  2100. {
  2101. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  2102. }
  2103. return imageUpdated || newImageList.Count > 0;
  2104. }
  2105. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  2106. {
  2107. return new ItemImageInfo
  2108. {
  2109. Path = file.FullName,
  2110. Type = type,
  2111. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  2112. };
  2113. }
  2114. /// <summary>
  2115. /// Gets the file system path to delete when the item is to be deleted.
  2116. /// </summary>
  2117. /// <returns></returns>
  2118. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  2119. {
  2120. return new[] {
  2121. new FileSystemMetadata
  2122. {
  2123. FullName = Path,
  2124. IsDirectory = IsFolder
  2125. }
  2126. }.Concat(GetLocalMetadataFilesToDelete());
  2127. }
  2128. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  2129. {
  2130. if (IsFolder || !IsInMixedFolder)
  2131. {
  2132. return new List<FileSystemMetadata>();
  2133. }
  2134. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  2135. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
  2136. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  2137. .ToList();
  2138. }
  2139. public bool AllowsMultipleImages(ImageType type)
  2140. {
  2141. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  2142. }
  2143. public Task SwapImagesAsync(ImageType type, int index1, int index2)
  2144. {
  2145. if (!AllowsMultipleImages(type))
  2146. {
  2147. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  2148. }
  2149. var info1 = GetImageInfo(type, index1);
  2150. var info2 = GetImageInfo(type, index2);
  2151. if (info1 == null || info2 == null)
  2152. {
  2153. // Nothing to do
  2154. return Task.CompletedTask;
  2155. }
  2156. if (!info1.IsLocalFile || !info2.IsLocalFile)
  2157. {
  2158. // TODO: Not supported yet
  2159. return Task.CompletedTask;
  2160. }
  2161. var path1 = info1.Path;
  2162. var path2 = info2.Path;
  2163. FileSystem.SwapFiles(path1, path2);
  2164. // Refresh these values
  2165. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  2166. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  2167. info1.Width = 0;
  2168. info1.Height = 0;
  2169. info2.Width = 0;
  2170. info2.Height = 0;
  2171. return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2172. }
  2173. public virtual bool IsPlayed(User user)
  2174. {
  2175. var userdata = UserDataManager.GetUserData(user, this);
  2176. return userdata != null && userdata.Played;
  2177. }
  2178. public bool IsFavoriteOrLiked(User user)
  2179. {
  2180. var userdata = UserDataManager.GetUserData(user, this);
  2181. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  2182. }
  2183. public virtual bool IsUnplayed(User user)
  2184. {
  2185. if (user == null)
  2186. {
  2187. throw new ArgumentNullException(nameof(user));
  2188. }
  2189. var userdata = UserDataManager.GetUserData(user, this);
  2190. return userdata == null || !userdata.Played;
  2191. }
  2192. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  2193. {
  2194. return GetItemLookupInfo<ItemLookupInfo>();
  2195. }
  2196. protected T GetItemLookupInfo<T>()
  2197. where T : ItemLookupInfo, new()
  2198. {
  2199. return new T
  2200. {
  2201. Path = Path,
  2202. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  2203. MetadataLanguage = GetPreferredMetadataLanguage(),
  2204. Name = GetNameForMetadataLookup(),
  2205. ProviderIds = ProviderIds,
  2206. IndexNumber = IndexNumber,
  2207. ParentIndexNumber = ParentIndexNumber,
  2208. Year = ProductionYear,
  2209. PremiereDate = PremiereDate
  2210. };
  2211. }
  2212. protected virtual string GetNameForMetadataLookup()
  2213. {
  2214. return Name;
  2215. }
  2216. /// <summary>
  2217. /// This is called before any metadata refresh and returns true if changes were made.
  2218. /// </summary>
  2219. public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata)
  2220. {
  2221. _sortName = null;
  2222. var hasChanges = false;
  2223. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  2224. {
  2225. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  2226. hasChanges = true;
  2227. }
  2228. return hasChanges;
  2229. }
  2230. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  2231. {
  2232. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  2233. {
  2234. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  2235. }
  2236. return path;
  2237. }
  2238. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  2239. {
  2240. if (RunTimeTicks.HasValue)
  2241. {
  2242. double pct = RunTimeTicks.Value;
  2243. if (pct > 0)
  2244. {
  2245. pct = userData.PlaybackPositionTicks / pct;
  2246. if (pct > 0)
  2247. {
  2248. dto.PlayedPercentage = 100 * pct;
  2249. }
  2250. }
  2251. }
  2252. }
  2253. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2254. {
  2255. var newOptions = new MetadataRefreshOptions(options);
  2256. newOptions.SearchResult = null;
  2257. var item = this;
  2258. if (copyTitleMetadata)
  2259. {
  2260. // Take some data from the main item, for querying purposes
  2261. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2262. {
  2263. newOptions.ForceSave = true;
  2264. ownedItem.Genres = item.Genres;
  2265. }
  2266. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2267. {
  2268. newOptions.ForceSave = true;
  2269. ownedItem.Studios = item.Studios;
  2270. }
  2271. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2272. {
  2273. newOptions.ForceSave = true;
  2274. ownedItem.ProductionLocations = item.ProductionLocations;
  2275. }
  2276. if (item.CommunityRating != ownedItem.CommunityRating)
  2277. {
  2278. ownedItem.CommunityRating = item.CommunityRating;
  2279. newOptions.ForceSave = true;
  2280. }
  2281. if (item.CriticRating != ownedItem.CriticRating)
  2282. {
  2283. ownedItem.CriticRating = item.CriticRating;
  2284. newOptions.ForceSave = true;
  2285. }
  2286. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2287. {
  2288. ownedItem.Overview = item.Overview;
  2289. newOptions.ForceSave = true;
  2290. }
  2291. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2292. {
  2293. ownedItem.OfficialRating = item.OfficialRating;
  2294. newOptions.ForceSave = true;
  2295. }
  2296. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2297. {
  2298. ownedItem.CustomRating = item.CustomRating;
  2299. newOptions.ForceSave = true;
  2300. }
  2301. }
  2302. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2303. }
  2304. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2305. {
  2306. var newOptions = new MetadataRefreshOptions(options);
  2307. newOptions.SearchResult = null;
  2308. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2309. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2310. var video = LibraryManager.GetItemById(id) as Video;
  2311. if (video == null)
  2312. {
  2313. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2314. newOptions.ForceSave = true;
  2315. }
  2316. // var parentId = Id;
  2317. // if (!video.IsOwnedItem || video.ParentId != parentId)
  2318. //{
  2319. // video.IsOwnedItem = true;
  2320. // video.ParentId = parentId;
  2321. // newOptions.ForceSave = true;
  2322. //}
  2323. if (video == null)
  2324. {
  2325. return Task.FromResult(true);
  2326. }
  2327. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2328. }
  2329. public string GetEtag(User user)
  2330. {
  2331. var list = GetEtagValues(user);
  2332. return string.Join("|", list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  2333. }
  2334. protected virtual List<string> GetEtagValues(User user)
  2335. {
  2336. return new List<string>
  2337. {
  2338. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2339. };
  2340. }
  2341. public virtual IEnumerable<Guid> GetAncestorIds()
  2342. {
  2343. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2344. }
  2345. public BaseItem GetTopParent()
  2346. {
  2347. if (IsTopParent)
  2348. {
  2349. return this;
  2350. }
  2351. return GetParents().FirstOrDefault(parent => parent.IsTopParent);
  2352. }
  2353. [JsonIgnore]
  2354. public virtual bool IsTopParent
  2355. {
  2356. get
  2357. {
  2358. if (this is BasePluginFolder || this is Channel)
  2359. {
  2360. return true;
  2361. }
  2362. if (this is IHasCollectionType view)
  2363. {
  2364. if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2365. {
  2366. return true;
  2367. }
  2368. }
  2369. if (GetParent() is AggregateFolder)
  2370. {
  2371. return true;
  2372. }
  2373. return false;
  2374. }
  2375. }
  2376. [JsonIgnore]
  2377. public virtual bool SupportsAncestors => true;
  2378. [JsonIgnore]
  2379. public virtual bool StopRefreshIfLocalMetadataFound => true;
  2380. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2381. {
  2382. return new[] { Id };
  2383. }
  2384. public virtual List<ExternalUrl> GetRelatedUrls()
  2385. {
  2386. return new List<ExternalUrl>();
  2387. }
  2388. public virtual double? GetRefreshProgress()
  2389. {
  2390. return null;
  2391. }
  2392. public virtual ItemUpdateType OnMetadataChanged()
  2393. {
  2394. var updateType = ItemUpdateType.None;
  2395. var item = this;
  2396. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2397. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2398. {
  2399. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2400. updateType |= ItemUpdateType.MetadataImport;
  2401. }
  2402. return updateType;
  2403. }
  2404. /// <summary>
  2405. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2406. /// </summary>
  2407. /// <returns></returns>
  2408. public bool UpdateRatingToItems(IList<BaseItem> children)
  2409. {
  2410. var currentOfficialRating = OfficialRating;
  2411. // Gather all possible ratings
  2412. var ratings = children
  2413. .Select(i => i.OfficialRating)
  2414. .Where(i => !string.IsNullOrEmpty(i))
  2415. .Distinct(StringComparer.OrdinalIgnoreCase)
  2416. .Select(i => new Tuple<string, int?>(i, LocalizationManager.GetRatingLevel(i)))
  2417. .OrderBy(i => i.Item2 ?? 1000)
  2418. .Select(i => i.Item1);
  2419. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2420. return !string.Equals(currentOfficialRating ?? string.Empty, OfficialRating ?? string.Empty,
  2421. StringComparison.OrdinalIgnoreCase);
  2422. }
  2423. public IEnumerable<BaseItem> GetThemeSongs()
  2424. {
  2425. return ThemeSongIds.Select(LibraryManager.GetItemById);
  2426. }
  2427. public IEnumerable<BaseItem> GetThemeVideos()
  2428. {
  2429. return ThemeVideoIds.Select(LibraryManager.GetItemById);
  2430. }
  2431. /// <summary>
  2432. /// Gets or sets the remote trailers.
  2433. /// </summary>
  2434. /// <value>The remote trailers.</value>
  2435. public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
  2436. /// <summary>
  2437. /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
  2438. /// </summary>
  2439. /// <returns>An enumerable containing the items.</returns>
  2440. public IEnumerable<BaseItem> GetExtras()
  2441. {
  2442. return ExtraIds
  2443. .Select(LibraryManager.GetItemById)
  2444. .Where(i => i != null)
  2445. .OrderBy(i => i.SortName);
  2446. }
  2447. /// <summary>
  2448. /// Get all extras with specific types that are associated with this item.
  2449. /// </summary>
  2450. /// <param name="extraTypes">The types of extras to retrieve.</param>
  2451. /// <returns>An enumerable containing the extras.</returns>
  2452. public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
  2453. {
  2454. return ExtraIds
  2455. .Select(LibraryManager.GetItemById)
  2456. .Where(i => i != null)
  2457. .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value));
  2458. }
  2459. public IEnumerable<BaseItem> GetTrailers()
  2460. {
  2461. if (this is IHasTrailers)
  2462. {
  2463. return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
  2464. }
  2465. else
  2466. {
  2467. return Array.Empty<BaseItem>();
  2468. }
  2469. }
  2470. public virtual bool IsHD => Height >= 720;
  2471. public bool IsShortcut { get; set; }
  2472. public string ShortcutPath { get; set; }
  2473. public int Width { get; set; }
  2474. public int Height { get; set; }
  2475. public Guid[] ExtraIds { get; set; }
  2476. public virtual long GetRunTimeTicksForPlayState()
  2477. {
  2478. return RunTimeTicks ?? 0;
  2479. }
  2480. /// <summary>
  2481. /// Extra types that should be counted and displayed as "Special Features" in the UI.
  2482. /// </summary>
  2483. public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
  2484. {
  2485. Model.Entities.ExtraType.Unknown,
  2486. Model.Entities.ExtraType.BehindTheScenes,
  2487. Model.Entities.ExtraType.Clip,
  2488. Model.Entities.ExtraType.DeletedScene,
  2489. Model.Entities.ExtraType.Interview,
  2490. Model.Entities.ExtraType.Sample,
  2491. Model.Entities.ExtraType.Scene
  2492. };
  2493. public virtual bool SupportsExternalTransfer => false;
  2494. /// <inheritdoc />
  2495. public override bool Equals(object obj)
  2496. {
  2497. return obj is BaseItem baseItem && this.Equals(baseItem);
  2498. }
  2499. /// <inheritdoc />
  2500. public bool Equals(BaseItem item) => Object.Equals(Id, item?.Id);
  2501. /// <inheritdoc />
  2502. public override int GetHashCode() => HashCode.Combine(Id);
  2503. }
  2504. }