BaseItem.cs 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051
  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. if (ownedItemsChanged)
  1194. {
  1195. requiresSave = true;
  1196. }
  1197. }
  1198. catch (Exception ex)
  1199. {
  1200. Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name);
  1201. }
  1202. }
  1203. try
  1204. {
  1205. var refreshOptions = requiresSave
  1206. ? new MetadataRefreshOptions(options)
  1207. {
  1208. ForceSave = true
  1209. }
  1210. : options;
  1211. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1212. }
  1213. finally
  1214. {
  1215. TriggerOnRefreshComplete();
  1216. }
  1217. }
  1218. [JsonIgnore]
  1219. protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol;
  1220. [JsonIgnore]
  1221. public virtual bool SupportsPeople => false;
  1222. [JsonIgnore]
  1223. public virtual bool SupportsThemeMedia => false;
  1224. /// <summary>
  1225. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1226. /// Returns true or false indicating if changes were found.
  1227. /// </summary>
  1228. /// <param name="options"></param>
  1229. /// <param name="fileSystemChildren"></param>
  1230. /// <param name="cancellationToken"></param>
  1231. /// <returns></returns>
  1232. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1233. {
  1234. var themeSongsChanged = false;
  1235. var themeVideosChanged = false;
  1236. var extrasChanged = false;
  1237. var localTrailersChanged = false;
  1238. if (IsFileProtocol && SupportsOwnedItems)
  1239. {
  1240. if (SupportsThemeMedia)
  1241. {
  1242. if (!IsInMixedFolder)
  1243. {
  1244. themeSongsChanged = await RefreshThemeSongs(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1245. themeVideosChanged = await RefreshThemeVideos(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1246. extrasChanged = await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1247. }
  1248. }
  1249. var hasTrailers = this as IHasTrailers;
  1250. if (hasTrailers != null)
  1251. {
  1252. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1253. }
  1254. }
  1255. return themeSongsChanged || themeVideosChanged || extrasChanged || localTrailersChanged;
  1256. }
  1257. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1258. {
  1259. var path = ContainingFolderPath;
  1260. return directoryService.GetFileSystemEntries(path);
  1261. }
  1262. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1263. {
  1264. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService);
  1265. var newItemIds = newItems.Select(i => i.Id);
  1266. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  1267. var ownerId = item.Id;
  1268. var tasks = newItems.Select(i =>
  1269. {
  1270. var subOptions = new MetadataRefreshOptions(options);
  1271. if (i.ExtraType != Model.Entities.ExtraType.Trailer ||
  1272. i.OwnerId != ownerId ||
  1273. !i.ParentId.Equals(Guid.Empty))
  1274. {
  1275. i.ExtraType = Model.Entities.ExtraType.Trailer;
  1276. i.OwnerId = ownerId;
  1277. i.ParentId = Guid.Empty;
  1278. subOptions.ForceSave = true;
  1279. }
  1280. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1281. });
  1282. await Task.WhenAll(tasks).ConfigureAwait(false);
  1283. item.LocalTrailerIds = newItemIds.ToArray();
  1284. return itemsChanged;
  1285. }
  1286. private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1287. {
  1288. var extras = LoadExtras(fileSystemChildren, options.DirectoryService);
  1289. var themeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1290. var themeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1291. var newExtras = new BaseItem[extras.Length + themeVideos.Length + themeSongs.Length];
  1292. extras.CopyTo(newExtras, 0);
  1293. themeVideos.CopyTo(newExtras, extras.Length);
  1294. themeSongs.CopyTo(newExtras, extras.Length + themeVideos.Length);
  1295. var newExtraIds = newExtras.Select(i => i.Id).ToArray();
  1296. var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
  1297. if (extrasChanged)
  1298. {
  1299. var ownerId = item.Id;
  1300. var tasks = newExtras.Select(i =>
  1301. {
  1302. var subOptions = new MetadataRefreshOptions(options);
  1303. if (i.OwnerId != ownerId || i.ParentId != Guid.Empty)
  1304. {
  1305. i.OwnerId = ownerId;
  1306. i.ParentId = Guid.Empty;
  1307. subOptions.ForceSave = true;
  1308. }
  1309. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1310. });
  1311. await Task.WhenAll(tasks).ConfigureAwait(false);
  1312. item.ExtraIds = newExtraIds;
  1313. }
  1314. return extrasChanged;
  1315. }
  1316. private async Task<bool> RefreshThemeVideos(BaseItem item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1317. {
  1318. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1319. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToArray();
  1320. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  1321. var ownerId = item.Id;
  1322. var tasks = newThemeVideos.Select(i =>
  1323. {
  1324. var subOptions = new MetadataRefreshOptions(options);
  1325. if (!i.ExtraType.HasValue ||
  1326. i.ExtraType.Value != Model.Entities.ExtraType.ThemeVideo ||
  1327. i.OwnerId != ownerId ||
  1328. !i.ParentId.Equals(Guid.Empty))
  1329. {
  1330. i.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1331. i.OwnerId = ownerId;
  1332. i.ParentId = Guid.Empty;
  1333. subOptions.ForceSave = true;
  1334. }
  1335. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1336. });
  1337. await Task.WhenAll(tasks).ConfigureAwait(false);
  1338. // They are expected to be sorted by SortName
  1339. item.ThemeVideoIds = newThemeVideos.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
  1340. return themeVideosChanged;
  1341. }
  1342. /// <summary>
  1343. /// Refreshes the theme songs.
  1344. /// </summary>
  1345. private async Task<bool> RefreshThemeSongs(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1346. {
  1347. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1348. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToArray();
  1349. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  1350. var ownerId = item.Id;
  1351. var tasks = newThemeSongs.Select(i =>
  1352. {
  1353. var subOptions = new MetadataRefreshOptions(options);
  1354. if (!i.ExtraType.HasValue ||
  1355. i.ExtraType.Value != Model.Entities.ExtraType.ThemeSong ||
  1356. i.OwnerId != ownerId ||
  1357. !i.ParentId.Equals(Guid.Empty))
  1358. {
  1359. i.ExtraType = Model.Entities.ExtraType.ThemeSong;
  1360. i.OwnerId = ownerId;
  1361. i.ParentId = Guid.Empty;
  1362. subOptions.ForceSave = true;
  1363. }
  1364. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1365. });
  1366. await Task.WhenAll(tasks).ConfigureAwait(false);
  1367. // They are expected to be sorted by SortName
  1368. item.ThemeSongIds = newThemeSongs.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
  1369. return themeSongsChanged;
  1370. }
  1371. /// <summary>
  1372. /// Gets or sets the provider ids.
  1373. /// </summary>
  1374. /// <value>The provider ids.</value>
  1375. [JsonIgnore]
  1376. public Dictionary<string, string> ProviderIds { get; set; }
  1377. [JsonIgnore]
  1378. public virtual Folder LatestItemsIndexContainer => null;
  1379. public virtual double GetDefaultPrimaryImageAspectRatio()
  1380. {
  1381. return 0;
  1382. }
  1383. public virtual string CreatePresentationUniqueKey()
  1384. {
  1385. return Id.ToString("N", CultureInfo.InvariantCulture);
  1386. }
  1387. [JsonIgnore]
  1388. public string PresentationUniqueKey { get; set; }
  1389. public string GetPresentationUniqueKey()
  1390. {
  1391. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1392. }
  1393. public virtual bool RequiresRefresh()
  1394. {
  1395. return false;
  1396. }
  1397. public virtual List<string> GetUserDataKeys()
  1398. {
  1399. var list = new List<string>();
  1400. if (SourceType == SourceType.Channel)
  1401. {
  1402. if (!string.IsNullOrEmpty(ExternalId))
  1403. {
  1404. list.Add(ExternalId);
  1405. }
  1406. }
  1407. list.Add(Id.ToString());
  1408. return list;
  1409. }
  1410. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1411. {
  1412. var updateType = ItemUpdateType.None;
  1413. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1414. {
  1415. IsInMixedFolder = newItem.IsInMixedFolder;
  1416. updateType |= ItemUpdateType.MetadataImport;
  1417. }
  1418. return updateType;
  1419. }
  1420. public void AfterMetadataRefresh()
  1421. {
  1422. _sortName = null;
  1423. }
  1424. /// <summary>
  1425. /// Gets the preferred metadata language.
  1426. /// </summary>
  1427. /// <returns>System.String.</returns>
  1428. public string GetPreferredMetadataLanguage()
  1429. {
  1430. string lang = PreferredMetadataLanguage;
  1431. if (string.IsNullOrEmpty(lang))
  1432. {
  1433. lang = GetParents()
  1434. .Select(i => i.PreferredMetadataLanguage)
  1435. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1436. }
  1437. if (string.IsNullOrEmpty(lang))
  1438. {
  1439. lang = LibraryManager.GetCollectionFolders(this)
  1440. .Select(i => i.PreferredMetadataLanguage)
  1441. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1442. }
  1443. if (string.IsNullOrEmpty(lang))
  1444. {
  1445. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1446. }
  1447. if (string.IsNullOrEmpty(lang))
  1448. {
  1449. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1450. }
  1451. return lang;
  1452. }
  1453. /// <summary>
  1454. /// Gets the preferred metadata language.
  1455. /// </summary>
  1456. /// <returns>System.String.</returns>
  1457. public string GetPreferredMetadataCountryCode()
  1458. {
  1459. string lang = PreferredMetadataCountryCode;
  1460. if (string.IsNullOrEmpty(lang))
  1461. {
  1462. lang = GetParents()
  1463. .Select(i => i.PreferredMetadataCountryCode)
  1464. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1465. }
  1466. if (string.IsNullOrEmpty(lang))
  1467. {
  1468. lang = LibraryManager.GetCollectionFolders(this)
  1469. .Select(i => i.PreferredMetadataCountryCode)
  1470. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1471. }
  1472. if (string.IsNullOrEmpty(lang))
  1473. {
  1474. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1475. }
  1476. if (string.IsNullOrEmpty(lang))
  1477. {
  1478. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1479. }
  1480. return lang;
  1481. }
  1482. public virtual bool IsSaveLocalMetadataEnabled()
  1483. {
  1484. if (SourceType == SourceType.Channel)
  1485. {
  1486. return false;
  1487. }
  1488. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1489. return libraryOptions.SaveLocalMetadata;
  1490. }
  1491. /// <summary>
  1492. /// Determines if a given user has access to this item.
  1493. /// </summary>
  1494. /// <param name="user">The user.</param>
  1495. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1496. /// <exception cref="ArgumentNullException">user</exception>
  1497. public bool IsParentalAllowed(User user)
  1498. {
  1499. if (user == null)
  1500. {
  1501. throw new ArgumentNullException(nameof(user));
  1502. }
  1503. if (!IsVisibleViaTags(user))
  1504. {
  1505. return false;
  1506. }
  1507. var maxAllowedRating = user.MaxParentalAgeRating;
  1508. if (maxAllowedRating == null)
  1509. {
  1510. return true;
  1511. }
  1512. var rating = CustomRatingForComparison;
  1513. if (string.IsNullOrEmpty(rating))
  1514. {
  1515. rating = OfficialRatingForComparison;
  1516. }
  1517. if (string.IsNullOrEmpty(rating))
  1518. {
  1519. return !GetBlockUnratedValue(user);
  1520. }
  1521. var value = LocalizationManager.GetRatingLevel(rating);
  1522. // Could not determine the integer value
  1523. if (!value.HasValue)
  1524. {
  1525. var isAllowed = !GetBlockUnratedValue(user);
  1526. if (!isAllowed)
  1527. {
  1528. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1529. }
  1530. return isAllowed;
  1531. }
  1532. return value.Value <= maxAllowedRating.Value;
  1533. }
  1534. public int? GetParentalRatingValue()
  1535. {
  1536. var rating = CustomRating;
  1537. if (string.IsNullOrEmpty(rating))
  1538. {
  1539. rating = OfficialRating;
  1540. }
  1541. if (string.IsNullOrEmpty(rating))
  1542. {
  1543. return null;
  1544. }
  1545. return LocalizationManager.GetRatingLevel(rating);
  1546. }
  1547. public int? GetInheritedParentalRatingValue()
  1548. {
  1549. var rating = CustomRatingForComparison;
  1550. if (string.IsNullOrEmpty(rating))
  1551. {
  1552. rating = OfficialRatingForComparison;
  1553. }
  1554. if (string.IsNullOrEmpty(rating))
  1555. {
  1556. return null;
  1557. }
  1558. return LocalizationManager.GetRatingLevel(rating);
  1559. }
  1560. public List<string> GetInheritedTags()
  1561. {
  1562. var list = new List<string>();
  1563. list.AddRange(Tags);
  1564. foreach (var parent in GetParents())
  1565. {
  1566. list.AddRange(parent.Tags);
  1567. }
  1568. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1569. }
  1570. private bool IsVisibleViaTags(User user)
  1571. {
  1572. if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1573. {
  1574. return false;
  1575. }
  1576. return true;
  1577. }
  1578. protected virtual bool IsAllowTagFilterEnforced()
  1579. {
  1580. return true;
  1581. }
  1582. public virtual UnratedItem GetBlockUnratedType()
  1583. {
  1584. if (SourceType == SourceType.Channel)
  1585. {
  1586. return UnratedItem.ChannelContent;
  1587. }
  1588. return UnratedItem.Other;
  1589. }
  1590. /// <summary>
  1591. /// Gets the block unrated value.
  1592. /// </summary>
  1593. /// <param name="user">The configuration.</param>
  1594. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1595. protected virtual bool GetBlockUnratedValue(User user)
  1596. {
  1597. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1598. // Special folders like series and albums will override this method.
  1599. if (IsFolder || this is IItemByName)
  1600. {
  1601. return false;
  1602. }
  1603. return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType().ToString());
  1604. }
  1605. /// <summary>
  1606. /// Determines if this folder should be visible to a given user.
  1607. /// Default is just parental allowed. Can be overridden for more functionality.
  1608. /// </summary>
  1609. /// <param name="user">The user.</param>
  1610. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1611. /// <exception cref="ArgumentNullException">user</exception>
  1612. public virtual bool IsVisible(User user)
  1613. {
  1614. if (user == null)
  1615. {
  1616. throw new ArgumentNullException(nameof(user));
  1617. }
  1618. return IsParentalAllowed(user);
  1619. }
  1620. public virtual bool IsVisibleStandalone(User user)
  1621. {
  1622. if (SourceType == SourceType.Channel)
  1623. {
  1624. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1625. }
  1626. return IsVisibleStandaloneInternal(user, true);
  1627. }
  1628. [JsonIgnore]
  1629. public virtual bool SupportsInheritedParentImages => false;
  1630. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1631. {
  1632. if (!IsVisible(user))
  1633. {
  1634. return false;
  1635. }
  1636. if (GetParents().Any(i => !i.IsVisible(user)))
  1637. {
  1638. return false;
  1639. }
  1640. if (checkFolders)
  1641. {
  1642. var topParent = GetParents().LastOrDefault() ?? this;
  1643. if (string.IsNullOrEmpty(topParent.Path))
  1644. {
  1645. return true;
  1646. }
  1647. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1648. if (itemCollectionFolders.Count > 0)
  1649. {
  1650. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1651. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1652. {
  1653. return false;
  1654. }
  1655. }
  1656. }
  1657. return true;
  1658. }
  1659. /// <summary>
  1660. /// Gets a value indicating whether this instance is folder.
  1661. /// </summary>
  1662. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1663. [JsonIgnore]
  1664. public virtual bool IsFolder => false;
  1665. [JsonIgnore]
  1666. public virtual bool IsDisplayedAsFolder => false;
  1667. public virtual string GetClientTypeName()
  1668. {
  1669. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1670. {
  1671. return "ChannelFolderItem";
  1672. }
  1673. return GetType().Name;
  1674. }
  1675. /// <summary>
  1676. /// Gets the linked child.
  1677. /// </summary>
  1678. /// <param name="info">The info.</param>
  1679. /// <returns>BaseItem.</returns>
  1680. protected BaseItem GetLinkedChild(LinkedChild info)
  1681. {
  1682. // First get using the cached Id
  1683. if (info.ItemId.HasValue)
  1684. {
  1685. if (info.ItemId.Value.Equals(Guid.Empty))
  1686. {
  1687. return null;
  1688. }
  1689. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1690. if (itemById != null)
  1691. {
  1692. return itemById;
  1693. }
  1694. }
  1695. var item = FindLinkedChild(info);
  1696. // If still null, log
  1697. if (item == null)
  1698. {
  1699. // Don't keep searching over and over
  1700. info.ItemId = Guid.Empty;
  1701. }
  1702. else
  1703. {
  1704. // Cache the id for next time
  1705. info.ItemId = item.Id;
  1706. }
  1707. return item;
  1708. }
  1709. private BaseItem FindLinkedChild(LinkedChild info)
  1710. {
  1711. var path = info.Path;
  1712. if (!string.IsNullOrEmpty(path))
  1713. {
  1714. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1715. var itemByPath = LibraryManager.FindByPath(path, null);
  1716. if (itemByPath == null)
  1717. {
  1718. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1719. }
  1720. return itemByPath;
  1721. }
  1722. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1723. {
  1724. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1725. if (item == null)
  1726. {
  1727. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1728. }
  1729. return item;
  1730. }
  1731. return null;
  1732. }
  1733. [JsonIgnore]
  1734. public virtual bool EnableRememberingTrackSelections => true;
  1735. /// <summary>
  1736. /// Adds a studio to the item.
  1737. /// </summary>
  1738. /// <param name="name">The name.</param>
  1739. /// <exception cref="ArgumentNullException"></exception>
  1740. public void AddStudio(string name)
  1741. {
  1742. if (string.IsNullOrEmpty(name))
  1743. {
  1744. throw new ArgumentNullException(nameof(name));
  1745. }
  1746. var current = Studios;
  1747. if (!current.Contains(name, StringComparer.OrdinalIgnoreCase))
  1748. {
  1749. int curLen = current.Length;
  1750. if (curLen == 0)
  1751. {
  1752. Studios = new[] { name };
  1753. }
  1754. else
  1755. {
  1756. var newArr = new string[curLen + 1];
  1757. current.CopyTo(newArr, 0);
  1758. newArr[curLen] = name;
  1759. Studios = newArr;
  1760. }
  1761. }
  1762. }
  1763. public void SetStudios(IEnumerable<string> names)
  1764. {
  1765. Studios = names.Distinct().ToArray();
  1766. }
  1767. /// <summary>
  1768. /// Adds a genre to the item.
  1769. /// </summary>
  1770. /// <param name="name">The name.</param>
  1771. /// <exception cref="ArgumentNullException"></exception>
  1772. public void AddGenre(string name)
  1773. {
  1774. if (string.IsNullOrEmpty(name))
  1775. {
  1776. throw new ArgumentNullException(nameof(name));
  1777. }
  1778. var genres = Genres;
  1779. if (!genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1780. {
  1781. var list = genres.ToList();
  1782. list.Add(name);
  1783. Genres = list.ToArray();
  1784. }
  1785. }
  1786. /// <summary>
  1787. /// Marks the played.
  1788. /// </summary>
  1789. /// <param name="user">The user.</param>
  1790. /// <param name="datePlayed">The date played.</param>
  1791. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1792. /// <returns>Task.</returns>
  1793. /// <exception cref="ArgumentNullException"></exception>
  1794. public virtual void MarkPlayed(
  1795. User user,
  1796. DateTime? datePlayed,
  1797. bool resetPosition)
  1798. {
  1799. if (user == null)
  1800. {
  1801. throw new ArgumentNullException(nameof(user));
  1802. }
  1803. var data = UserDataManager.GetUserData(user, this);
  1804. if (datePlayed.HasValue)
  1805. {
  1806. // Increment
  1807. data.PlayCount++;
  1808. }
  1809. // Ensure it's at least one
  1810. data.PlayCount = Math.Max(data.PlayCount, 1);
  1811. if (resetPosition)
  1812. {
  1813. data.PlaybackPositionTicks = 0;
  1814. }
  1815. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1816. data.Played = true;
  1817. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1818. }
  1819. /// <summary>
  1820. /// Marks the unplayed.
  1821. /// </summary>
  1822. /// <param name="user">The user.</param>
  1823. /// <returns>Task.</returns>
  1824. /// <exception cref="ArgumentNullException"></exception>
  1825. public virtual void MarkUnplayed(User user)
  1826. {
  1827. if (user == null)
  1828. {
  1829. throw new ArgumentNullException(nameof(user));
  1830. }
  1831. var data = UserDataManager.GetUserData(user, this);
  1832. // I think it is okay to do this here.
  1833. // if this is only called when a user is manually forcing something to un-played
  1834. // then it probably is what we want to do...
  1835. data.PlayCount = 0;
  1836. data.PlaybackPositionTicks = 0;
  1837. data.LastPlayedDate = null;
  1838. data.Played = false;
  1839. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1840. }
  1841. /// <summary>
  1842. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1843. /// </summary>
  1844. public virtual void ChangedExternally()
  1845. {
  1846. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
  1847. }
  1848. /// <summary>
  1849. /// Gets an image.
  1850. /// </summary>
  1851. /// <param name="type">The type.</param>
  1852. /// <param name="imageIndex">Index of the image.</param>
  1853. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1854. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1855. public bool HasImage(ImageType type, int imageIndex)
  1856. {
  1857. return GetImageInfo(type, imageIndex) != null;
  1858. }
  1859. public void SetImage(ItemImageInfo image, int index)
  1860. {
  1861. if (image.Type == ImageType.Chapter)
  1862. {
  1863. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1864. }
  1865. var existingImage = GetImageInfo(image.Type, index);
  1866. if (existingImage != null)
  1867. {
  1868. existingImage.Path = image.Path;
  1869. existingImage.DateModified = image.DateModified;
  1870. existingImage.Width = image.Width;
  1871. existingImage.Height = image.Height;
  1872. existingImage.BlurHash = image.BlurHash;
  1873. }
  1874. else
  1875. {
  1876. var current = ImageInfos;
  1877. var currentCount = current.Length;
  1878. var newArr = new ItemImageInfo[currentCount + 1];
  1879. current.CopyTo(newArr, 0);
  1880. newArr[currentCount] = image;
  1881. ImageInfos = newArr;
  1882. }
  1883. }
  1884. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1885. {
  1886. if (type == ImageType.Chapter)
  1887. {
  1888. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1889. }
  1890. var image = GetImageInfo(type, index);
  1891. if (image == null)
  1892. {
  1893. ImageInfos = ImageInfos.Concat(new[] { GetImageInfo(file, type) }).ToArray();
  1894. }
  1895. else
  1896. {
  1897. var imageInfo = GetImageInfo(file, type);
  1898. image.Path = file.FullName;
  1899. image.DateModified = imageInfo.DateModified;
  1900. // reset these values
  1901. image.Width = 0;
  1902. image.Height = 0;
  1903. }
  1904. }
  1905. /// <summary>
  1906. /// Deletes the image.
  1907. /// </summary>
  1908. /// <param name="type">The type.</param>
  1909. /// <param name="index">The index.</param>
  1910. public async Task DeleteImageAsync(ImageType type, int index)
  1911. {
  1912. var info = GetImageInfo(type, index);
  1913. if (info == null)
  1914. {
  1915. // Nothing to do
  1916. return;
  1917. }
  1918. // Remove it from the item
  1919. RemoveImage(info);
  1920. if (info.IsLocalFile)
  1921. {
  1922. FileSystem.DeleteFile(info.Path);
  1923. }
  1924. await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  1925. }
  1926. public void RemoveImage(ItemImageInfo image)
  1927. {
  1928. RemoveImages(new List<ItemImageInfo> { image });
  1929. }
  1930. public void RemoveImages(List<ItemImageInfo> deletedImages)
  1931. {
  1932. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1933. }
  1934. public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1935. => LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken);
  1936. /// <summary>
  1937. /// Validates that images within the item are still on the filesystem.
  1938. /// </summary>
  1939. public bool ValidateImages(IDirectoryService directoryService)
  1940. {
  1941. var allFiles = ImageInfos
  1942. .Where(i => i.IsLocalFile)
  1943. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1944. .Distinct(StringComparer.OrdinalIgnoreCase)
  1945. .SelectMany(i => directoryService.GetFilePaths(i))
  1946. .ToList();
  1947. var deletedImages = ImageInfos
  1948. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1949. .ToList();
  1950. if (deletedImages.Count > 0)
  1951. {
  1952. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1953. }
  1954. return deletedImages.Count > 0;
  1955. }
  1956. /// <summary>
  1957. /// Gets the image path.
  1958. /// </summary>
  1959. /// <param name="imageType">Type of the image.</param>
  1960. /// <param name="imageIndex">Index of the image.</param>
  1961. /// <returns>System.String.</returns>
  1962. /// <exception cref="InvalidOperationException">
  1963. /// </exception>
  1964. /// <exception cref="ArgumentNullException">item</exception>
  1965. public string GetImagePath(ImageType imageType, int imageIndex)
  1966. => GetImageInfo(imageType, imageIndex)?.Path;
  1967. /// <summary>
  1968. /// Gets the image information.
  1969. /// </summary>
  1970. /// <param name="imageType">Type of the image.</param>
  1971. /// <param name="imageIndex">Index of the image.</param>
  1972. /// <returns>ItemImageInfo.</returns>
  1973. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1974. {
  1975. if (imageType == ImageType.Chapter)
  1976. {
  1977. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1978. if (chapter == null)
  1979. {
  1980. return null;
  1981. }
  1982. var path = chapter.ImagePath;
  1983. if (string.IsNullOrEmpty(path))
  1984. {
  1985. return null;
  1986. }
  1987. return new ItemImageInfo
  1988. {
  1989. Path = path,
  1990. DateModified = chapter.ImageDateModified,
  1991. Type = imageType
  1992. };
  1993. }
  1994. return GetImages(imageType)
  1995. .ElementAtOrDefault(imageIndex);
  1996. }
  1997. /// <summary>
  1998. /// Computes image index for given image or raises if no matching image found.
  1999. /// </summary>
  2000. /// <param name="image">Image to compute index for.</param>
  2001. /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
  2002. /// </exception>
  2003. /// <returns>Image index.</returns>
  2004. public int GetImageIndex(ItemImageInfo image)
  2005. {
  2006. if (image == null)
  2007. {
  2008. throw new ArgumentNullException(nameof(image));
  2009. }
  2010. if (image.Type == ImageType.Chapter)
  2011. {
  2012. var chapters = ItemRepository.GetChapters(this);
  2013. for (var i = 0; i < chapters.Count; i++)
  2014. {
  2015. if (chapters[i].ImagePath == image.Path)
  2016. {
  2017. return i;
  2018. }
  2019. }
  2020. throw new ArgumentException("No chapter index found for image path", image.Path);
  2021. }
  2022. var images = GetImages(image.Type).ToArray();
  2023. for (var i = 0; i < images.Length; i++)
  2024. {
  2025. if (images[i].Path == image.Path)
  2026. {
  2027. return i;
  2028. }
  2029. }
  2030. throw new ArgumentException("No image index found for image path", image.Path);
  2031. }
  2032. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  2033. {
  2034. if (imageType == ImageType.Chapter)
  2035. {
  2036. throw new ArgumentException("No image info for chapter images");
  2037. }
  2038. return ImageInfos.Where(i => i.Type == imageType);
  2039. }
  2040. /// <summary>
  2041. /// Adds the images.
  2042. /// </summary>
  2043. /// <param name="imageType">Type of the image.</param>
  2044. /// <param name="images">The images.</param>
  2045. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  2046. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images</exception>
  2047. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  2048. {
  2049. if (imageType == ImageType.Chapter)
  2050. {
  2051. throw new ArgumentException("Cannot call AddImages with chapter images");
  2052. }
  2053. var existingImages = GetImages(imageType)
  2054. .ToList();
  2055. var newImageList = new List<FileSystemMetadata>();
  2056. var imageAdded = false;
  2057. var imageUpdated = false;
  2058. foreach (var newImage in images)
  2059. {
  2060. if (newImage == null)
  2061. {
  2062. throw new ArgumentException("null image found in list");
  2063. }
  2064. var existing = existingImages
  2065. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  2066. if (existing == null)
  2067. {
  2068. newImageList.Add(newImage);
  2069. imageAdded = true;
  2070. }
  2071. else
  2072. {
  2073. if (existing.IsLocalFile)
  2074. {
  2075. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  2076. // If date changed then we need to reset saved image dimensions
  2077. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  2078. {
  2079. existing.Width = 0;
  2080. existing.Height = 0;
  2081. imageUpdated = true;
  2082. }
  2083. existing.DateModified = newDateModified;
  2084. }
  2085. }
  2086. }
  2087. if (imageAdded || images.Count != existingImages.Count)
  2088. {
  2089. var newImagePaths = images.Select(i => i.FullName).ToList();
  2090. var deleted = existingImages
  2091. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
  2092. .ToList();
  2093. if (deleted.Count > 0)
  2094. {
  2095. ImageInfos = ImageInfos.Except(deleted).ToArray();
  2096. }
  2097. }
  2098. if (newImageList.Count > 0)
  2099. {
  2100. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  2101. }
  2102. return imageUpdated || newImageList.Count > 0;
  2103. }
  2104. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  2105. {
  2106. return new ItemImageInfo
  2107. {
  2108. Path = file.FullName,
  2109. Type = type,
  2110. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  2111. };
  2112. }
  2113. /// <summary>
  2114. /// Gets the file system path to delete when the item is to be deleted.
  2115. /// </summary>
  2116. /// <returns></returns>
  2117. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  2118. {
  2119. return new[] {
  2120. new FileSystemMetadata
  2121. {
  2122. FullName = Path,
  2123. IsDirectory = IsFolder
  2124. }
  2125. }.Concat(GetLocalMetadataFilesToDelete());
  2126. }
  2127. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  2128. {
  2129. if (IsFolder || !IsInMixedFolder)
  2130. {
  2131. return new List<FileSystemMetadata>();
  2132. }
  2133. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  2134. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
  2135. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  2136. .ToList();
  2137. }
  2138. public bool AllowsMultipleImages(ImageType type)
  2139. {
  2140. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  2141. }
  2142. public Task SwapImagesAsync(ImageType type, int index1, int index2)
  2143. {
  2144. if (!AllowsMultipleImages(type))
  2145. {
  2146. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  2147. }
  2148. var info1 = GetImageInfo(type, index1);
  2149. var info2 = GetImageInfo(type, index2);
  2150. if (info1 == null || info2 == null)
  2151. {
  2152. // Nothing to do
  2153. return Task.CompletedTask;
  2154. }
  2155. if (!info1.IsLocalFile || !info2.IsLocalFile)
  2156. {
  2157. // TODO: Not supported yet
  2158. return Task.CompletedTask;
  2159. }
  2160. var path1 = info1.Path;
  2161. var path2 = info2.Path;
  2162. FileSystem.SwapFiles(path1, path2);
  2163. // Refresh these values
  2164. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  2165. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  2166. info1.Width = 0;
  2167. info1.Height = 0;
  2168. info2.Width = 0;
  2169. info2.Height = 0;
  2170. return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2171. }
  2172. public virtual bool IsPlayed(User user)
  2173. {
  2174. var userdata = UserDataManager.GetUserData(user, this);
  2175. return userdata != null && userdata.Played;
  2176. }
  2177. public bool IsFavoriteOrLiked(User user)
  2178. {
  2179. var userdata = UserDataManager.GetUserData(user, this);
  2180. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  2181. }
  2182. public virtual bool IsUnplayed(User user)
  2183. {
  2184. if (user == null)
  2185. {
  2186. throw new ArgumentNullException(nameof(user));
  2187. }
  2188. var userdata = UserDataManager.GetUserData(user, this);
  2189. return userdata == null || !userdata.Played;
  2190. }
  2191. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  2192. {
  2193. return GetItemLookupInfo<ItemLookupInfo>();
  2194. }
  2195. protected T GetItemLookupInfo<T>()
  2196. where T : ItemLookupInfo, new()
  2197. {
  2198. return new T
  2199. {
  2200. Path = Path,
  2201. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  2202. MetadataLanguage = GetPreferredMetadataLanguage(),
  2203. Name = GetNameForMetadataLookup(),
  2204. ProviderIds = ProviderIds,
  2205. IndexNumber = IndexNumber,
  2206. ParentIndexNumber = ParentIndexNumber,
  2207. Year = ProductionYear,
  2208. PremiereDate = PremiereDate
  2209. };
  2210. }
  2211. protected virtual string GetNameForMetadataLookup()
  2212. {
  2213. return Name;
  2214. }
  2215. /// <summary>
  2216. /// This is called before any metadata refresh and returns true if changes were made.
  2217. /// </summary>
  2218. public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata)
  2219. {
  2220. _sortName = null;
  2221. var hasChanges = false;
  2222. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  2223. {
  2224. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  2225. hasChanges = true;
  2226. }
  2227. return hasChanges;
  2228. }
  2229. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  2230. {
  2231. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  2232. {
  2233. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  2234. }
  2235. return path;
  2236. }
  2237. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  2238. {
  2239. if (RunTimeTicks.HasValue)
  2240. {
  2241. double pct = RunTimeTicks.Value;
  2242. if (pct > 0)
  2243. {
  2244. pct = userData.PlaybackPositionTicks / pct;
  2245. if (pct > 0)
  2246. {
  2247. dto.PlayedPercentage = 100 * pct;
  2248. }
  2249. }
  2250. }
  2251. }
  2252. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2253. {
  2254. var newOptions = new MetadataRefreshOptions(options);
  2255. newOptions.SearchResult = null;
  2256. var item = this;
  2257. if (copyTitleMetadata)
  2258. {
  2259. // Take some data from the main item, for querying purposes
  2260. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2261. {
  2262. newOptions.ForceSave = true;
  2263. ownedItem.Genres = item.Genres;
  2264. }
  2265. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2266. {
  2267. newOptions.ForceSave = true;
  2268. ownedItem.Studios = item.Studios;
  2269. }
  2270. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2271. {
  2272. newOptions.ForceSave = true;
  2273. ownedItem.ProductionLocations = item.ProductionLocations;
  2274. }
  2275. if (item.CommunityRating != ownedItem.CommunityRating)
  2276. {
  2277. ownedItem.CommunityRating = item.CommunityRating;
  2278. newOptions.ForceSave = true;
  2279. }
  2280. if (item.CriticRating != ownedItem.CriticRating)
  2281. {
  2282. ownedItem.CriticRating = item.CriticRating;
  2283. newOptions.ForceSave = true;
  2284. }
  2285. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2286. {
  2287. ownedItem.Overview = item.Overview;
  2288. newOptions.ForceSave = true;
  2289. }
  2290. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2291. {
  2292. ownedItem.OfficialRating = item.OfficialRating;
  2293. newOptions.ForceSave = true;
  2294. }
  2295. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2296. {
  2297. ownedItem.CustomRating = item.CustomRating;
  2298. newOptions.ForceSave = true;
  2299. }
  2300. }
  2301. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2302. }
  2303. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2304. {
  2305. var newOptions = new MetadataRefreshOptions(options);
  2306. newOptions.SearchResult = null;
  2307. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2308. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2309. var video = LibraryManager.GetItemById(id) as Video;
  2310. if (video == null)
  2311. {
  2312. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2313. newOptions.ForceSave = true;
  2314. }
  2315. // var parentId = Id;
  2316. // if (!video.IsOwnedItem || video.ParentId != parentId)
  2317. //{
  2318. // video.IsOwnedItem = true;
  2319. // video.ParentId = parentId;
  2320. // newOptions.ForceSave = true;
  2321. //}
  2322. if (video == null)
  2323. {
  2324. return Task.FromResult(true);
  2325. }
  2326. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2327. }
  2328. public string GetEtag(User user)
  2329. {
  2330. var list = GetEtagValues(user);
  2331. return string.Join("|", list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  2332. }
  2333. protected virtual List<string> GetEtagValues(User user)
  2334. {
  2335. return new List<string>
  2336. {
  2337. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2338. };
  2339. }
  2340. public virtual IEnumerable<Guid> GetAncestorIds()
  2341. {
  2342. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2343. }
  2344. public BaseItem GetTopParent()
  2345. {
  2346. if (IsTopParent)
  2347. {
  2348. return this;
  2349. }
  2350. return GetParents().FirstOrDefault(parent => parent.IsTopParent);
  2351. }
  2352. [JsonIgnore]
  2353. public virtual bool IsTopParent
  2354. {
  2355. get
  2356. {
  2357. if (this is BasePluginFolder || this is Channel)
  2358. {
  2359. return true;
  2360. }
  2361. if (this is IHasCollectionType view)
  2362. {
  2363. if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2364. {
  2365. return true;
  2366. }
  2367. }
  2368. if (GetParent() is AggregateFolder)
  2369. {
  2370. return true;
  2371. }
  2372. return false;
  2373. }
  2374. }
  2375. [JsonIgnore]
  2376. public virtual bool SupportsAncestors => true;
  2377. [JsonIgnore]
  2378. public virtual bool StopRefreshIfLocalMetadataFound => true;
  2379. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2380. {
  2381. return new[] { Id };
  2382. }
  2383. public virtual List<ExternalUrl> GetRelatedUrls()
  2384. {
  2385. return new List<ExternalUrl>();
  2386. }
  2387. public virtual double? GetRefreshProgress()
  2388. {
  2389. return null;
  2390. }
  2391. public virtual ItemUpdateType OnMetadataChanged()
  2392. {
  2393. var updateType = ItemUpdateType.None;
  2394. var item = this;
  2395. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2396. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2397. {
  2398. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2399. updateType |= ItemUpdateType.MetadataImport;
  2400. }
  2401. return updateType;
  2402. }
  2403. /// <summary>
  2404. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2405. /// </summary>
  2406. /// <returns></returns>
  2407. public bool UpdateRatingToItems(IList<BaseItem> children)
  2408. {
  2409. var currentOfficialRating = OfficialRating;
  2410. // Gather all possible ratings
  2411. var ratings = children
  2412. .Select(i => i.OfficialRating)
  2413. .Where(i => !string.IsNullOrEmpty(i))
  2414. .Distinct(StringComparer.OrdinalIgnoreCase)
  2415. .Select(i => new Tuple<string, int?>(i, LocalizationManager.GetRatingLevel(i)))
  2416. .OrderBy(i => i.Item2 ?? 1000)
  2417. .Select(i => i.Item1);
  2418. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2419. return !string.Equals(currentOfficialRating ?? string.Empty, OfficialRating ?? string.Empty,
  2420. StringComparison.OrdinalIgnoreCase);
  2421. }
  2422. public IEnumerable<BaseItem> GetThemeSongs()
  2423. {
  2424. return ThemeSongIds.Select(LibraryManager.GetItemById);
  2425. }
  2426. public IEnumerable<BaseItem> GetThemeVideos()
  2427. {
  2428. return ThemeVideoIds.Select(LibraryManager.GetItemById);
  2429. }
  2430. /// <summary>
  2431. /// Gets or sets the remote trailers.
  2432. /// </summary>
  2433. /// <value>The remote trailers.</value>
  2434. public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
  2435. /// <summary>
  2436. /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
  2437. /// </summary>
  2438. /// <returns>An enumerable containing the items.</returns>
  2439. public IEnumerable<BaseItem> GetExtras()
  2440. {
  2441. return ExtraIds
  2442. .Select(LibraryManager.GetItemById)
  2443. .Where(i => i != null)
  2444. .OrderBy(i => i.SortName);
  2445. }
  2446. /// <summary>
  2447. /// Get all extras with specific types that are associated with this item.
  2448. /// </summary>
  2449. /// <param name="extraTypes">The types of extras to retrieve.</param>
  2450. /// <returns>An enumerable containing the extras.</returns>
  2451. public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
  2452. {
  2453. return ExtraIds
  2454. .Select(LibraryManager.GetItemById)
  2455. .Where(i => i != null)
  2456. .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value));
  2457. }
  2458. public IEnumerable<BaseItem> GetTrailers()
  2459. {
  2460. if (this is IHasTrailers)
  2461. {
  2462. return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
  2463. }
  2464. else
  2465. {
  2466. return Array.Empty<BaseItem>();
  2467. }
  2468. }
  2469. public virtual bool IsHD => Height >= 720;
  2470. public bool IsShortcut { get; set; }
  2471. public string ShortcutPath { get; set; }
  2472. public int Width { get; set; }
  2473. public int Height { get; set; }
  2474. public Guid[] ExtraIds { get; set; }
  2475. public virtual long GetRunTimeTicksForPlayState()
  2476. {
  2477. return RunTimeTicks ?? 0;
  2478. }
  2479. /// <summary>
  2480. /// Extra types that should be counted and displayed as "Special Features" in the UI.
  2481. /// </summary>
  2482. public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
  2483. {
  2484. Model.Entities.ExtraType.Unknown,
  2485. Model.Entities.ExtraType.BehindTheScenes,
  2486. Model.Entities.ExtraType.Clip,
  2487. Model.Entities.ExtraType.DeletedScene,
  2488. Model.Entities.ExtraType.Interview,
  2489. Model.Entities.ExtraType.Sample,
  2490. Model.Entities.ExtraType.Scene
  2491. };
  2492. public virtual bool SupportsExternalTransfer => false;
  2493. /// <inheritdoc />
  2494. public override bool Equals(object obj)
  2495. {
  2496. return obj is BaseItem baseItem && this.Equals(baseItem);
  2497. }
  2498. /// <inheritdoc />
  2499. public bool Equals(BaseItem item) => Object.Equals(Id, item?.Id);
  2500. /// <inheritdoc />
  2501. public override int GetHashCode() => HashCode.Combine(Id);
  2502. }
  2503. }