BaseItem.cs 89 KB

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