BaseItem.cs 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Channels;
  3. using MediaBrowser.Controller.Collections;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.Localization;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Controller.Providers;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Library;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Users;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Runtime.Serialization;
  23. using System.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using CommonIO;
  27. using MediaBrowser.Controller.Sorting;
  28. using MediaBrowser.Model.LiveTv;
  29. namespace MediaBrowser.Controller.Entities
  30. {
  31. /// <summary>
  32. /// Class BaseItem
  33. /// </summary>
  34. public abstract class BaseItem : IHasProviderIds, ILibraryItem, IHasImages, IHasUserData, IHasMetadata, IHasLookupInfo<ItemLookupInfo>
  35. {
  36. protected BaseItem()
  37. {
  38. Tags = new List<string>();
  39. Genres = new List<string>();
  40. Studios = new List<string>();
  41. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  42. LockedFields = new List<MetadataFields>();
  43. ImageInfos = new List<ItemImageInfo>();
  44. }
  45. /// <summary>
  46. /// The supported image extensions
  47. /// </summary>
  48. public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
  49. public static readonly List<string> SupportedImageExtensionsList = SupportedImageExtensions.ToList();
  50. /// <summary>
  51. /// The trailer folder name
  52. /// </summary>
  53. public static string TrailerFolderName = "trailers";
  54. public static string ThemeSongsFolderName = "theme-music";
  55. public static string ThemeSongFilename = "theme";
  56. public static string ThemeVideosFolderName = "backdrops";
  57. [IgnoreDataMember]
  58. public string PreferredMetadataCountryCode { get; set; }
  59. [IgnoreDataMember]
  60. public string PreferredMetadataLanguage { get; set; }
  61. public List<ItemImageInfo> ImageInfos { get; set; }
  62. /// <summary>
  63. /// Gets or sets the channel identifier.
  64. /// </summary>
  65. /// <value>The channel identifier.</value>
  66. [IgnoreDataMember]
  67. public string ChannelId { get; set; }
  68. [IgnoreDataMember]
  69. public virtual bool SupportsAddingToPlaylist
  70. {
  71. get
  72. {
  73. return false;
  74. }
  75. }
  76. [IgnoreDataMember]
  77. public virtual bool AlwaysScanInternalMetadataPath
  78. {
  79. get { return false; }
  80. }
  81. /// <summary>
  82. /// Gets a value indicating whether this instance is in mixed folder.
  83. /// </summary>
  84. /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
  85. [IgnoreDataMember]
  86. public bool IsInMixedFolder { get; set; }
  87. [IgnoreDataMember]
  88. public virtual bool SupportsRemoteImageDownloading
  89. {
  90. get
  91. {
  92. return true;
  93. }
  94. }
  95. private string _name;
  96. /// <summary>
  97. /// Gets or sets the name.
  98. /// </summary>
  99. /// <value>The name.</value>
  100. [IgnoreDataMember]
  101. public virtual string Name
  102. {
  103. get
  104. {
  105. return _name;
  106. }
  107. set
  108. {
  109. _name = value;
  110. // lazy load this again
  111. _sortName = null;
  112. }
  113. }
  114. /// <summary>
  115. /// Gets or sets the id.
  116. /// </summary>
  117. /// <value>The id.</value>
  118. [IgnoreDataMember]
  119. public Guid Id { get; set; }
  120. /// <summary>
  121. /// Gets or sets a value indicating whether this instance is hd.
  122. /// </summary>
  123. /// <value><c>true</c> if this instance is hd; otherwise, <c>false</c>.</value>
  124. [IgnoreDataMember]
  125. public bool? IsHD { get; set; }
  126. /// <summary>
  127. /// Gets or sets the audio.
  128. /// </summary>
  129. /// <value>The audio.</value>
  130. [IgnoreDataMember]
  131. public ProgramAudio? Audio { get; set; }
  132. /// <summary>
  133. /// Return the id that should be used to key display prefs for this item.
  134. /// Default is based on the type for everything except actual generic folders.
  135. /// </summary>
  136. /// <value>The display prefs id.</value>
  137. [IgnoreDataMember]
  138. public virtual Guid DisplayPreferencesId
  139. {
  140. get
  141. {
  142. var thisType = GetType();
  143. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  144. }
  145. }
  146. /// <summary>
  147. /// Gets or sets the path.
  148. /// </summary>
  149. /// <value>The path.</value>
  150. [IgnoreDataMember]
  151. public virtual string Path { get; set; }
  152. [IgnoreDataMember]
  153. public bool IsOffline { get; set; }
  154. [IgnoreDataMember]
  155. public virtual SourceType SourceType { get; set; }
  156. /// <summary>
  157. /// Returns the folder containing the item.
  158. /// If the item is a folder, it returns the folder itself
  159. /// </summary>
  160. [IgnoreDataMember]
  161. public virtual string ContainingFolderPath
  162. {
  163. get
  164. {
  165. if (IsFolder)
  166. {
  167. return Path;
  168. }
  169. return System.IO.Path.GetDirectoryName(Path);
  170. }
  171. }
  172. /// <summary>
  173. /// Gets or sets the name of the service.
  174. /// </summary>
  175. /// <value>The name of the service.</value>
  176. [IgnoreDataMember]
  177. public string ServiceName { get; set; }
  178. /// <summary>
  179. /// If this content came from an external service, the id of the content on that service
  180. /// </summary>
  181. [IgnoreDataMember]
  182. public string ExternalId
  183. {
  184. get { return this.GetProviderId("ProviderExternalId"); }
  185. set
  186. {
  187. this.SetProviderId("ProviderExternalId", value);
  188. }
  189. }
  190. /// <summary>
  191. /// Gets or sets the etag.
  192. /// </summary>
  193. /// <value>The etag.</value>
  194. [IgnoreDataMember]
  195. public string ExternalEtag { get; set; }
  196. [IgnoreDataMember]
  197. public virtual bool IsHidden
  198. {
  199. get
  200. {
  201. return false;
  202. }
  203. }
  204. [IgnoreDataMember]
  205. public virtual bool IsOwnedItem
  206. {
  207. get
  208. {
  209. // Local trailer, special feature, theme video, etc.
  210. // An item that belongs to another item but is not part of the Parent-Child tree
  211. return !IsFolder && ParentId == Guid.Empty && LocationType == LocationType.FileSystem;
  212. }
  213. }
  214. /// <summary>
  215. /// Gets or sets the type of the location.
  216. /// </summary>
  217. /// <value>The type of the location.</value>
  218. [IgnoreDataMember]
  219. public virtual LocationType LocationType
  220. {
  221. get
  222. {
  223. if (IsOffline)
  224. {
  225. return LocationType.Offline;
  226. }
  227. if (string.IsNullOrWhiteSpace(Path))
  228. {
  229. if (SourceType == SourceType.Channel)
  230. {
  231. return LocationType.Remote;
  232. }
  233. return LocationType.Virtual;
  234. }
  235. return FileSystem.IsPathFile(Path) ? LocationType.FileSystem : LocationType.Remote;
  236. }
  237. }
  238. [IgnoreDataMember]
  239. public virtual bool SupportsLocalMetadata
  240. {
  241. get
  242. {
  243. if (SourceType == SourceType.Channel)
  244. {
  245. return false;
  246. }
  247. var locationType = LocationType;
  248. return locationType != LocationType.Remote && locationType != LocationType.Virtual;
  249. }
  250. }
  251. [IgnoreDataMember]
  252. public virtual string FileNameWithoutExtension
  253. {
  254. get
  255. {
  256. if (LocationType == LocationType.FileSystem)
  257. {
  258. return System.IO.Path.GetFileNameWithoutExtension(Path);
  259. }
  260. return null;
  261. }
  262. }
  263. [IgnoreDataMember]
  264. public virtual bool EnableAlphaNumericSorting
  265. {
  266. get
  267. {
  268. return true;
  269. }
  270. }
  271. private List<Tuple<StringBuilder,bool>> GetSortChunks(string s1)
  272. {
  273. var list = new List<Tuple<StringBuilder, bool>>();
  274. int thisMarker = 0, thisNumericChunk = 0;
  275. while (thisMarker < s1.Length)
  276. {
  277. if (thisMarker >= s1.Length)
  278. {
  279. break;
  280. }
  281. char thisCh = s1[thisMarker];
  282. StringBuilder thisChunk = new StringBuilder();
  283. while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || SortHelper.InChunk(thisCh, thisChunk[0])))
  284. {
  285. thisChunk.Append(thisCh);
  286. thisMarker++;
  287. if (thisMarker < s1.Length)
  288. {
  289. thisCh = s1[thisMarker];
  290. }
  291. }
  292. var isNumeric = thisChunk.Length > 0 && char.IsDigit(thisChunk[0]);
  293. list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
  294. }
  295. return list;
  296. }
  297. /// <summary>
  298. /// This is just a helper for convenience
  299. /// </summary>
  300. /// <value>The primary image path.</value>
  301. [IgnoreDataMember]
  302. public string PrimaryImagePath
  303. {
  304. get { return this.GetImagePath(ImageType.Primary); }
  305. }
  306. public virtual bool IsInternetMetadataEnabled()
  307. {
  308. return ConfigurationManager.Configuration.EnableInternetProviders;
  309. }
  310. public virtual bool CanDelete()
  311. {
  312. if (SourceType == SourceType.Channel)
  313. {
  314. return false;
  315. }
  316. var locationType = LocationType;
  317. return locationType != LocationType.Remote &&
  318. locationType != LocationType.Virtual;
  319. }
  320. public virtual bool IsAuthorizedToDelete(User user)
  321. {
  322. return user.Policy.EnableContentDeletion;
  323. }
  324. public bool CanDelete(User user)
  325. {
  326. return CanDelete() && IsAuthorizedToDelete(user);
  327. }
  328. public virtual bool CanDownload()
  329. {
  330. return false;
  331. }
  332. public virtual bool IsAuthorizedToDownload(User user)
  333. {
  334. return user.Policy.EnableContentDownloading;
  335. }
  336. public bool CanDownload(User user)
  337. {
  338. return CanDownload() && IsAuthorizedToDownload(user);
  339. }
  340. /// <summary>
  341. /// Gets or sets the date created.
  342. /// </summary>
  343. /// <value>The date created.</value>
  344. [IgnoreDataMember]
  345. public DateTime DateCreated { get; set; }
  346. /// <summary>
  347. /// Gets or sets the date modified.
  348. /// </summary>
  349. /// <value>The date modified.</value>
  350. [IgnoreDataMember]
  351. public DateTime DateModified { get; set; }
  352. [IgnoreDataMember]
  353. public DateTime DateLastSaved { get; set; }
  354. [IgnoreDataMember]
  355. public DateTime DateLastRefreshed { get; set; }
  356. /// <summary>
  357. /// The logger
  358. /// </summary>
  359. public static ILogger Logger { get; set; }
  360. public static ILibraryManager LibraryManager { get; set; }
  361. public static IServerConfigurationManager ConfigurationManager { get; set; }
  362. public static IProviderManager ProviderManager { get; set; }
  363. public static ILocalizationManager LocalizationManager { get; set; }
  364. public static IItemRepository ItemRepository { get; set; }
  365. public static IFileSystem FileSystem { get; set; }
  366. public static IUserDataManager UserDataManager { get; set; }
  367. public static ILiveTvManager LiveTvManager { get; set; }
  368. public static IChannelManager ChannelManager { get; set; }
  369. public static ICollectionManager CollectionManager { get; set; }
  370. public static IImageProcessor ImageProcessor { get; set; }
  371. public static IMediaSourceManager MediaSourceManager { get; set; }
  372. /// <summary>
  373. /// Returns a <see cref="System.String" /> that represents this instance.
  374. /// </summary>
  375. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  376. public override string ToString()
  377. {
  378. return Name;
  379. }
  380. [IgnoreDataMember]
  381. public bool IsLocked { get; set; }
  382. /// <summary>
  383. /// Gets or sets the locked fields.
  384. /// </summary>
  385. /// <value>The locked fields.</value>
  386. [IgnoreDataMember]
  387. public List<MetadataFields> LockedFields { get; set; }
  388. /// <summary>
  389. /// Gets the type of the media.
  390. /// </summary>
  391. /// <value>The type of the media.</value>
  392. [IgnoreDataMember]
  393. public virtual string MediaType
  394. {
  395. get
  396. {
  397. return null;
  398. }
  399. }
  400. [IgnoreDataMember]
  401. public virtual IEnumerable<string> PhysicalLocations
  402. {
  403. get
  404. {
  405. var locationType = LocationType;
  406. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  407. {
  408. return new string[] { };
  409. }
  410. return new[] { Path };
  411. }
  412. }
  413. private string _forcedSortName;
  414. /// <summary>
  415. /// Gets or sets the name of the forced sort.
  416. /// </summary>
  417. /// <value>The name of the forced sort.</value>
  418. [IgnoreDataMember]
  419. public string ForcedSortName
  420. {
  421. get { return _forcedSortName; }
  422. set { _forcedSortName = value; _sortName = null; }
  423. }
  424. private string _sortName;
  425. /// <summary>
  426. /// Gets the name of the sort.
  427. /// </summary>
  428. /// <value>The name of the sort.</value>
  429. [IgnoreDataMember]
  430. public string SortName
  431. {
  432. get
  433. {
  434. if (_sortName == null)
  435. {
  436. if (!string.IsNullOrWhiteSpace(ForcedSortName))
  437. {
  438. _sortName = ModifySortChunks(ForcedSortName);
  439. }
  440. else
  441. {
  442. _sortName = CreateSortName();
  443. }
  444. }
  445. return _sortName;
  446. }
  447. set
  448. {
  449. _sortName = value;
  450. }
  451. }
  452. public string GetInternalMetadataPath()
  453. {
  454. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  455. return GetInternalMetadataPath(basePath);
  456. }
  457. protected virtual string GetInternalMetadataPath(string basePath)
  458. {
  459. if (SourceType == SourceType.Channel)
  460. {
  461. return System.IO.Path.Combine(basePath, "channels", ChannelId, Id.ToString("N"));
  462. }
  463. var idString = Id.ToString("N");
  464. basePath = System.IO.Path.Combine(basePath, "library");
  465. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  466. }
  467. /// <summary>
  468. /// Creates the name of the sort.
  469. /// </summary>
  470. /// <returns>System.String.</returns>
  471. protected virtual string CreateSortName()
  472. {
  473. if (Name == null) return null; //some items may not have name filled in properly
  474. if (!EnableAlphaNumericSorting)
  475. {
  476. return Name.TrimStart();
  477. }
  478. var sortable = Name.Trim().ToLower();
  479. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  480. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  481. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  482. {
  483. var searchLower = search.ToLower();
  484. // Remove from beginning if a space follows
  485. if (sortable.StartsWith(searchLower + " "))
  486. {
  487. sortable = sortable.Remove(0, searchLower.Length + 1);
  488. }
  489. // Remove from middle if surrounded by spaces
  490. sortable = sortable.Replace(" " + searchLower + " ", " ");
  491. // Remove from end if followed by a space
  492. if (sortable.EndsWith(" " + searchLower))
  493. {
  494. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  495. }
  496. }
  497. return ModifySortChunks(sortable);
  498. }
  499. private string ModifySortChunks(string name)
  500. {
  501. var chunks = GetSortChunks(name);
  502. var builder = new StringBuilder();
  503. foreach (var chunk in chunks)
  504. {
  505. var chunkBuilder = chunk.Item1;
  506. // This chunk is numeric
  507. if (chunk.Item2)
  508. {
  509. while (chunkBuilder.Length < 10)
  510. {
  511. chunkBuilder.Insert(0, '0');
  512. }
  513. }
  514. builder.Append(chunkBuilder);
  515. }
  516. //Logger.Debug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  517. return builder.ToString();
  518. }
  519. [IgnoreDataMember]
  520. public Guid ParentId { get; set; }
  521. /// <summary>
  522. /// Gets or sets the parent.
  523. /// </summary>
  524. /// <value>The parent.</value>
  525. [IgnoreDataMember]
  526. public Folder Parent
  527. {
  528. get { return GetParent() as Folder; }
  529. set
  530. {
  531. }
  532. }
  533. public void SetParent(Folder parent)
  534. {
  535. ParentId = parent == null ? Guid.Empty : parent.Id;
  536. }
  537. [IgnoreDataMember]
  538. public IEnumerable<Folder> Parents
  539. {
  540. get { return GetParents().OfType<Folder>(); }
  541. }
  542. public BaseItem GetParent()
  543. {
  544. if (ParentId != Guid.Empty)
  545. {
  546. return LibraryManager.GetItemById(ParentId);
  547. }
  548. return null;
  549. }
  550. public IEnumerable<BaseItem> GetParents()
  551. {
  552. var parent = GetParent();
  553. while (parent != null)
  554. {
  555. yield return parent;
  556. parent = parent.GetParent();
  557. }
  558. }
  559. /// <summary>
  560. /// Finds a parent of a given type
  561. /// </summary>
  562. /// <typeparam name="T"></typeparam>
  563. /// <returns>``0.</returns>
  564. public T FindParent<T>()
  565. where T : Folder
  566. {
  567. return GetParents().OfType<T>().FirstOrDefault();
  568. }
  569. [IgnoreDataMember]
  570. public virtual BaseItem DisplayParent
  571. {
  572. get { return GetParent(); }
  573. }
  574. /// <summary>
  575. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  576. /// </summary>
  577. /// <value>The premiere date.</value>
  578. [IgnoreDataMember]
  579. public DateTime? PremiereDate { get; set; }
  580. /// <summary>
  581. /// Gets or sets the end date.
  582. /// </summary>
  583. /// <value>The end date.</value>
  584. [IgnoreDataMember]
  585. public DateTime? EndDate { get; set; }
  586. /// <summary>
  587. /// Gets or sets the display type of the media.
  588. /// </summary>
  589. /// <value>The display type of the media.</value>
  590. [IgnoreDataMember]
  591. public string DisplayMediaType { get; set; }
  592. /// <summary>
  593. /// Gets or sets the official rating.
  594. /// </summary>
  595. /// <value>The official rating.</value>
  596. [IgnoreDataMember]
  597. public string OfficialRating { get; set; }
  598. /// <summary>
  599. /// Gets or sets the critic rating.
  600. /// </summary>
  601. /// <value>The critic rating.</value>
  602. public float? CriticRating { get; set; }
  603. /// <summary>
  604. /// Gets or sets the critic rating summary.
  605. /// </summary>
  606. /// <value>The critic rating summary.</value>
  607. public string CriticRatingSummary { get; set; }
  608. /// <summary>
  609. /// Gets or sets the official rating description.
  610. /// </summary>
  611. /// <value>The official rating description.</value>
  612. [IgnoreDataMember]
  613. public string OfficialRatingDescription { get; set; }
  614. /// <summary>
  615. /// Gets or sets the custom rating.
  616. /// </summary>
  617. /// <value>The custom rating.</value>
  618. [IgnoreDataMember]
  619. public string CustomRating { get; set; }
  620. /// <summary>
  621. /// Gets or sets the overview.
  622. /// </summary>
  623. /// <value>The overview.</value>
  624. [IgnoreDataMember]
  625. public string Overview { get; set; }
  626. /// <summary>
  627. /// Gets or sets the studios.
  628. /// </summary>
  629. /// <value>The studios.</value>
  630. [IgnoreDataMember]
  631. public List<string> Studios { get; set; }
  632. /// <summary>
  633. /// Gets or sets the genres.
  634. /// </summary>
  635. /// <value>The genres.</value>
  636. [IgnoreDataMember]
  637. public List<string> Genres { get; set; }
  638. /// <summary>
  639. /// Gets or sets the tags.
  640. /// </summary>
  641. /// <value>The tags.</value>
  642. [IgnoreDataMember]
  643. public List<string> Tags { get; set; }
  644. /// <summary>
  645. /// Gets or sets the home page URL.
  646. /// </summary>
  647. /// <value>The home page URL.</value>
  648. [IgnoreDataMember]
  649. public string HomePageUrl { get; set; }
  650. /// <summary>
  651. /// Gets or sets the community rating.
  652. /// </summary>
  653. /// <value>The community rating.</value>
  654. [IgnoreDataMember]
  655. public float? CommunityRating { get; set; }
  656. /// <summary>
  657. /// Gets or sets the community rating vote count.
  658. /// </summary>
  659. /// <value>The community rating vote count.</value>
  660. [IgnoreDataMember]
  661. public int? VoteCount { get; set; }
  662. /// <summary>
  663. /// Gets or sets the run time ticks.
  664. /// </summary>
  665. /// <value>The run time ticks.</value>
  666. [IgnoreDataMember]
  667. public long? RunTimeTicks { get; set; }
  668. /// <summary>
  669. /// Gets or sets the production year.
  670. /// </summary>
  671. /// <value>The production year.</value>
  672. [IgnoreDataMember]
  673. public int? ProductionYear { get; set; }
  674. /// <summary>
  675. /// If the item is part of a series, this is it's number in the series.
  676. /// This could be episode number, album track number, etc.
  677. /// </summary>
  678. /// <value>The index number.</value>
  679. [IgnoreDataMember]
  680. public int? IndexNumber { get; set; }
  681. /// <summary>
  682. /// For an episode this could be the season number, or for a song this could be the disc number.
  683. /// </summary>
  684. /// <value>The parent index number.</value>
  685. [IgnoreDataMember]
  686. public int? ParentIndexNumber { get; set; }
  687. [IgnoreDataMember]
  688. public string OfficialRatingForComparison
  689. {
  690. get
  691. {
  692. if (!string.IsNullOrWhiteSpace(OfficialRating))
  693. {
  694. return OfficialRating;
  695. }
  696. var parent = DisplayParent;
  697. if (parent != null)
  698. {
  699. return parent.OfficialRatingForComparison;
  700. }
  701. return null;
  702. }
  703. }
  704. [IgnoreDataMember]
  705. public string CustomRatingForComparison
  706. {
  707. get
  708. {
  709. if (!string.IsNullOrWhiteSpace(CustomRating))
  710. {
  711. return CustomRating;
  712. }
  713. var parent = DisplayParent;
  714. if (parent != null)
  715. {
  716. return parent.CustomRatingForComparison;
  717. }
  718. return null;
  719. }
  720. }
  721. /// <summary>
  722. /// Gets the play access.
  723. /// </summary>
  724. /// <param name="user">The user.</param>
  725. /// <returns>PlayAccess.</returns>
  726. public PlayAccess GetPlayAccess(User user)
  727. {
  728. if (!user.Policy.EnableMediaPlayback)
  729. {
  730. return PlayAccess.None;
  731. }
  732. //if (!user.IsParentalScheduleAllowed())
  733. //{
  734. // return PlayAccess.None;
  735. //}
  736. return PlayAccess.Full;
  737. }
  738. /// <summary>
  739. /// Loads the theme songs.
  740. /// </summary>
  741. /// <returns>List{Audio.Audio}.</returns>
  742. private IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  743. {
  744. var files = fileSystemChildren.Where(i => i.IsDirectory)
  745. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  746. .SelectMany(i => directoryService.GetFiles(i.FullName))
  747. .ToList();
  748. // Support plex/xbmc convention
  749. files.AddRange(fileSystemChildren
  750. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  751. );
  752. return LibraryManager.ResolvePaths(files, directoryService, null)
  753. .OfType<Audio.Audio>()
  754. .Select(audio =>
  755. {
  756. // Try to retrieve it from the db. If we don't find it, use the resolved version
  757. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  758. if (dbItem != null)
  759. {
  760. audio = dbItem;
  761. }
  762. audio.ExtraType = ExtraType.ThemeSong;
  763. return audio;
  764. // Sort them so that the list can be easily compared for changes
  765. }).OrderBy(i => i.Path).ToList();
  766. }
  767. /// <summary>
  768. /// Loads the video backdrops.
  769. /// </summary>
  770. /// <returns>List{Video}.</returns>
  771. private IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  772. {
  773. var files = fileSystemChildren.Where(i => i.IsDirectory)
  774. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  775. .SelectMany(i => directoryService.GetFiles(i.FullName));
  776. return LibraryManager.ResolvePaths(files, directoryService, null)
  777. .OfType<Video>()
  778. .Select(item =>
  779. {
  780. // Try to retrieve it from the db. If we don't find it, use the resolved version
  781. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  782. if (dbItem != null)
  783. {
  784. item = dbItem;
  785. }
  786. item.ExtraType = ExtraType.ThemeVideo;
  787. return item;
  788. // Sort them so that the list can be easily compared for changes
  789. }).OrderBy(i => i.Path).ToList();
  790. }
  791. public Task RefreshMetadata(CancellationToken cancellationToken)
  792. {
  793. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  794. }
  795. /// <summary>
  796. /// Overrides the base implementation to refresh metadata for local trailers
  797. /// </summary>
  798. /// <param name="options">The options.</param>
  799. /// <param name="cancellationToken">The cancellation token.</param>
  800. /// <returns>true if a provider reports we changed</returns>
  801. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  802. {
  803. var locationType = LocationType;
  804. var requiresSave = false;
  805. if (SupportsOwnedItems)
  806. {
  807. try
  808. {
  809. var files = locationType != LocationType.Remote && locationType != LocationType.Virtual ?
  810. GetFileSystemChildren(options.DirectoryService).ToList() :
  811. new List<FileSystemMetadata>();
  812. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  813. if (ownedItemsChanged)
  814. {
  815. requiresSave = true;
  816. }
  817. }
  818. catch (Exception ex)
  819. {
  820. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  821. }
  822. }
  823. var refreshOptions = requiresSave
  824. ? new MetadataRefreshOptions(options)
  825. {
  826. ForceSave = true
  827. }
  828. : options;
  829. var result = await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  830. return result;
  831. }
  832. [IgnoreDataMember]
  833. protected virtual bool SupportsOwnedItems
  834. {
  835. get { return IsFolder || GetParent() != null; }
  836. }
  837. [IgnoreDataMember]
  838. public virtual bool SupportsPeople
  839. {
  840. get { return true; }
  841. }
  842. /// <summary>
  843. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  844. /// Returns true or false indicating if changes were found.
  845. /// </summary>
  846. /// <param name="options"></param>
  847. /// <param name="fileSystemChildren"></param>
  848. /// <param name="cancellationToken"></param>
  849. /// <returns></returns>
  850. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  851. {
  852. var themeSongsChanged = false;
  853. var themeVideosChanged = false;
  854. var localTrailersChanged = false;
  855. if (LocationType == LocationType.FileSystem && GetParent() != null)
  856. {
  857. var hasThemeMedia = this as IHasThemeMedia;
  858. if (hasThemeMedia != null)
  859. {
  860. if (!IsInMixedFolder)
  861. {
  862. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  863. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  864. }
  865. }
  866. var hasTrailers = this as IHasTrailers;
  867. if (hasTrailers != null)
  868. {
  869. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  870. }
  871. }
  872. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  873. }
  874. protected virtual IEnumerable<FileSystemMetadata> GetFileSystemChildren(IDirectoryService directoryService)
  875. {
  876. var path = ContainingFolderPath;
  877. return directoryService.GetFileSystemEntries(path);
  878. }
  879. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  880. {
  881. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  882. var newItemIds = newItems.Select(i => i.Id).ToList();
  883. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  884. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  885. await Task.WhenAll(tasks).ConfigureAwait(false);
  886. item.LocalTrailerIds = newItemIds;
  887. return itemsChanged;
  888. }
  889. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  890. {
  891. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  892. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  893. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  894. var tasks = newThemeVideos.Select(i =>
  895. {
  896. var subOptions = new MetadataRefreshOptions(options);
  897. if (!i.IsThemeMedia)
  898. {
  899. i.ExtraType = ExtraType.ThemeVideo;
  900. subOptions.ForceSave = true;
  901. }
  902. return i.RefreshMetadata(subOptions, cancellationToken);
  903. });
  904. await Task.WhenAll(tasks).ConfigureAwait(false);
  905. item.ThemeVideoIds = newThemeVideoIds;
  906. return themeVideosChanged;
  907. }
  908. /// <summary>
  909. /// Refreshes the theme songs.
  910. /// </summary>
  911. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  912. {
  913. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  914. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  915. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  916. var tasks = newThemeSongs.Select(i =>
  917. {
  918. var subOptions = new MetadataRefreshOptions(options);
  919. if (!i.IsThemeMedia)
  920. {
  921. i.ExtraType = ExtraType.ThemeSong;
  922. subOptions.ForceSave = true;
  923. }
  924. return i.RefreshMetadata(subOptions, cancellationToken);
  925. });
  926. await Task.WhenAll(tasks).ConfigureAwait(false);
  927. item.ThemeSongIds = newThemeSongIds;
  928. return themeSongsChanged;
  929. }
  930. /// <summary>
  931. /// Gets or sets the provider ids.
  932. /// </summary>
  933. /// <value>The provider ids.</value>
  934. public Dictionary<string, string> ProviderIds { get; set; }
  935. [IgnoreDataMember]
  936. public virtual Folder LatestItemsIndexContainer
  937. {
  938. get { return null; }
  939. }
  940. private string _userDataKey;
  941. /// <summary>
  942. /// Gets the user data key.
  943. /// </summary>
  944. /// <returns>System.String.</returns>
  945. public string GetUserDataKey()
  946. {
  947. if (string.IsNullOrWhiteSpace(_userDataKey))
  948. {
  949. var key = CreateUserDataKey();
  950. _userDataKey = key;
  951. return key;
  952. }
  953. return _userDataKey;
  954. }
  955. protected virtual string CreateUserDataKey()
  956. {
  957. if (SourceType == SourceType.Channel)
  958. {
  959. if (!string.IsNullOrWhiteSpace(ExternalId))
  960. {
  961. return ExternalId;
  962. }
  963. }
  964. return Id.ToString();
  965. }
  966. internal virtual bool IsValidFromResolver(BaseItem newItem)
  967. {
  968. var current = this;
  969. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  970. }
  971. public void AfterMetadataRefresh()
  972. {
  973. _sortName = null;
  974. _userDataKey = null;
  975. }
  976. /// <summary>
  977. /// Gets the preferred metadata language.
  978. /// </summary>
  979. /// <returns>System.String.</returns>
  980. public string GetPreferredMetadataLanguage()
  981. {
  982. string lang = PreferredMetadataLanguage;
  983. if (string.IsNullOrWhiteSpace(lang))
  984. {
  985. lang = GetParents()
  986. .Select(i => i.PreferredMetadataLanguage)
  987. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  988. }
  989. if (string.IsNullOrWhiteSpace(lang))
  990. {
  991. lang = LibraryManager.GetCollectionFolders(this)
  992. .Select(i => i.PreferredMetadataLanguage)
  993. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  994. }
  995. if (string.IsNullOrWhiteSpace(lang))
  996. {
  997. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  998. }
  999. return lang;
  1000. }
  1001. /// <summary>
  1002. /// Gets the preferred metadata language.
  1003. /// </summary>
  1004. /// <returns>System.String.</returns>
  1005. public string GetPreferredMetadataCountryCode()
  1006. {
  1007. string lang = PreferredMetadataCountryCode;
  1008. if (string.IsNullOrWhiteSpace(lang))
  1009. {
  1010. lang = GetParents()
  1011. .Select(i => i.PreferredMetadataCountryCode)
  1012. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1013. }
  1014. if (string.IsNullOrWhiteSpace(lang))
  1015. {
  1016. lang = LibraryManager.GetCollectionFolders(this)
  1017. .Select(i => i.PreferredMetadataCountryCode)
  1018. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1019. }
  1020. if (string.IsNullOrWhiteSpace(lang))
  1021. {
  1022. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1023. }
  1024. return lang;
  1025. }
  1026. public virtual bool IsSaveLocalMetadataEnabled()
  1027. {
  1028. if (SourceType == SourceType.Channel)
  1029. {
  1030. return false;
  1031. }
  1032. return ConfigurationManager.Configuration.SaveLocalMeta;
  1033. }
  1034. /// <summary>
  1035. /// Determines if a given user has access to this item
  1036. /// </summary>
  1037. /// <param name="user">The user.</param>
  1038. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1039. /// <exception cref="System.ArgumentNullException">user</exception>
  1040. public bool IsParentalAllowed(User user)
  1041. {
  1042. if (user == null)
  1043. {
  1044. throw new ArgumentNullException("user");
  1045. }
  1046. if (!IsVisibleViaTags(user))
  1047. {
  1048. return false;
  1049. }
  1050. var maxAllowedRating = user.Policy.MaxParentalRating;
  1051. if (maxAllowedRating == null)
  1052. {
  1053. return true;
  1054. }
  1055. var rating = CustomRatingForComparison;
  1056. if (string.IsNullOrWhiteSpace(rating))
  1057. {
  1058. rating = OfficialRatingForComparison;
  1059. }
  1060. if (string.IsNullOrWhiteSpace(rating))
  1061. {
  1062. return !GetBlockUnratedValue(user.Policy);
  1063. }
  1064. var value = LocalizationManager.GetRatingLevel(rating);
  1065. // Could not determine the integer value
  1066. if (!value.HasValue)
  1067. {
  1068. var isAllowed = !GetBlockUnratedValue(user.Policy);
  1069. if (!isAllowed)
  1070. {
  1071. Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1072. }
  1073. return isAllowed;
  1074. }
  1075. return value.Value <= maxAllowedRating.Value;
  1076. }
  1077. public int? GetParentalRatingValue()
  1078. {
  1079. var rating = CustomRating;
  1080. if (string.IsNullOrWhiteSpace(rating))
  1081. {
  1082. rating = OfficialRating;
  1083. }
  1084. if (string.IsNullOrWhiteSpace(rating))
  1085. {
  1086. return null;
  1087. }
  1088. return LocalizationManager.GetRatingLevel(rating);
  1089. }
  1090. public int? GetInheritedParentalRatingValue()
  1091. {
  1092. var rating = CustomRatingForComparison;
  1093. if (string.IsNullOrWhiteSpace(rating))
  1094. {
  1095. rating = OfficialRatingForComparison;
  1096. }
  1097. if (string.IsNullOrWhiteSpace(rating))
  1098. {
  1099. return null;
  1100. }
  1101. return LocalizationManager.GetRatingLevel(rating);
  1102. }
  1103. private bool IsVisibleViaTags(User user)
  1104. {
  1105. var hasTags = this as IHasTags;
  1106. if (hasTags != null)
  1107. {
  1108. var policy = user.Policy;
  1109. if (policy.BlockedTags.Any(i => hasTags.Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1110. {
  1111. return false;
  1112. }
  1113. }
  1114. return true;
  1115. }
  1116. protected virtual bool IsAllowTagFilterEnforced()
  1117. {
  1118. return true;
  1119. }
  1120. public virtual UnratedItem GetBlockUnratedType()
  1121. {
  1122. if (SourceType == SourceType.Channel)
  1123. {
  1124. return UnratedItem.ChannelContent;
  1125. }
  1126. return UnratedItem.Other;
  1127. }
  1128. /// <summary>
  1129. /// Gets the block unrated value.
  1130. /// </summary>
  1131. /// <param name="config">The configuration.</param>
  1132. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1133. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  1134. {
  1135. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1136. // Special folders like series and albums will override this method.
  1137. if (IsFolder)
  1138. {
  1139. return false;
  1140. }
  1141. if (this is IItemByName)
  1142. {
  1143. return false;
  1144. }
  1145. return config.BlockUnratedItems.Contains(GetBlockUnratedType());
  1146. }
  1147. /// <summary>
  1148. /// Determines if this folder should be visible to a given user.
  1149. /// Default is just parental allowed. Can be overridden for more functionality.
  1150. /// </summary>
  1151. /// <param name="user">The user.</param>
  1152. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1153. /// <exception cref="System.ArgumentNullException">user</exception>
  1154. public virtual bool IsVisible(User user)
  1155. {
  1156. if (user == null)
  1157. {
  1158. throw new ArgumentNullException("user");
  1159. }
  1160. return IsParentalAllowed(user);
  1161. }
  1162. public virtual bool IsVisibleStandalone(User user)
  1163. {
  1164. if (SourceType == SourceType.Channel)
  1165. {
  1166. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1167. }
  1168. return IsVisibleStandaloneInternal(user, true);
  1169. }
  1170. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1171. {
  1172. if (!IsVisible(user))
  1173. {
  1174. return false;
  1175. }
  1176. if (GetParents().Any(i => !i.IsVisible(user)))
  1177. {
  1178. return false;
  1179. }
  1180. if (checkFolders)
  1181. {
  1182. var topParent = GetParents().LastOrDefault() ?? this;
  1183. if (string.IsNullOrWhiteSpace(topParent.Path))
  1184. {
  1185. return true;
  1186. }
  1187. var userCollectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  1188. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id);
  1189. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1190. {
  1191. return false;
  1192. }
  1193. }
  1194. return true;
  1195. }
  1196. /// <summary>
  1197. /// Gets a value indicating whether this instance is folder.
  1198. /// </summary>
  1199. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1200. [IgnoreDataMember]
  1201. public virtual bool IsFolder
  1202. {
  1203. get
  1204. {
  1205. return false;
  1206. }
  1207. }
  1208. public virtual string GetClientTypeName()
  1209. {
  1210. if (IsFolder && SourceType == SourceType.Channel)
  1211. {
  1212. return "ChannelFolderItem";
  1213. }
  1214. return GetType().Name;
  1215. }
  1216. /// <summary>
  1217. /// Gets the linked child.
  1218. /// </summary>
  1219. /// <param name="info">The info.</param>
  1220. /// <returns>BaseItem.</returns>
  1221. protected BaseItem GetLinkedChild(LinkedChild info)
  1222. {
  1223. // First get using the cached Id
  1224. if (info.ItemId.HasValue)
  1225. {
  1226. if (info.ItemId.Value == Guid.Empty)
  1227. {
  1228. return null;
  1229. }
  1230. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1231. if (itemById != null)
  1232. {
  1233. return itemById;
  1234. }
  1235. }
  1236. var item = FindLinkedChild(info);
  1237. // If still null, log
  1238. if (item == null)
  1239. {
  1240. // Don't keep searching over and over
  1241. info.ItemId = Guid.Empty;
  1242. }
  1243. else
  1244. {
  1245. // Cache the id for next time
  1246. info.ItemId = item.Id;
  1247. }
  1248. return item;
  1249. }
  1250. private BaseItem FindLinkedChild(LinkedChild info)
  1251. {
  1252. if (!string.IsNullOrEmpty(info.Path))
  1253. {
  1254. var itemByPath = LibraryManager.FindByPath(info.Path);
  1255. if (itemByPath == null)
  1256. {
  1257. Logger.Warn("Unable to find linked item at path {0}", info.Path);
  1258. }
  1259. return itemByPath;
  1260. }
  1261. return null;
  1262. }
  1263. /// <summary>
  1264. /// Adds a studio to the item
  1265. /// </summary>
  1266. /// <param name="name">The name.</param>
  1267. /// <exception cref="System.ArgumentNullException"></exception>
  1268. public void AddStudio(string name)
  1269. {
  1270. if (string.IsNullOrWhiteSpace(name))
  1271. {
  1272. throw new ArgumentNullException("name");
  1273. }
  1274. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1275. {
  1276. Studios.Add(name);
  1277. }
  1278. }
  1279. /// <summary>
  1280. /// Adds a genre to the item
  1281. /// </summary>
  1282. /// <param name="name">The name.</param>
  1283. /// <exception cref="System.ArgumentNullException"></exception>
  1284. public void AddGenre(string name)
  1285. {
  1286. if (string.IsNullOrWhiteSpace(name))
  1287. {
  1288. throw new ArgumentNullException("name");
  1289. }
  1290. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1291. {
  1292. Genres.Add(name);
  1293. }
  1294. }
  1295. /// <summary>
  1296. /// Marks the played.
  1297. /// </summary>
  1298. /// <param name="user">The user.</param>
  1299. /// <param name="datePlayed">The date played.</param>
  1300. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1301. /// <returns>Task.</returns>
  1302. /// <exception cref="System.ArgumentNullException"></exception>
  1303. public virtual async Task MarkPlayed(User user,
  1304. DateTime? datePlayed,
  1305. bool resetPosition)
  1306. {
  1307. if (user == null)
  1308. {
  1309. throw new ArgumentNullException();
  1310. }
  1311. var key = GetUserDataKey();
  1312. var data = UserDataManager.GetUserData(user.Id, key);
  1313. if (datePlayed.HasValue)
  1314. {
  1315. // Incremenet
  1316. data.PlayCount++;
  1317. }
  1318. // Ensure it's at least one
  1319. data.PlayCount = Math.Max(data.PlayCount, 1);
  1320. if (resetPosition)
  1321. {
  1322. data.PlaybackPositionTicks = 0;
  1323. }
  1324. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1325. data.Played = true;
  1326. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1327. }
  1328. /// <summary>
  1329. /// Marks the unplayed.
  1330. /// </summary>
  1331. /// <param name="user">The user.</param>
  1332. /// <returns>Task.</returns>
  1333. /// <exception cref="System.ArgumentNullException"></exception>
  1334. public virtual async Task MarkUnplayed(User user)
  1335. {
  1336. if (user == null)
  1337. {
  1338. throw new ArgumentNullException();
  1339. }
  1340. var key = GetUserDataKey();
  1341. var data = UserDataManager.GetUserData(user.Id, key);
  1342. //I think it is okay to do this here.
  1343. // if this is only called when a user is manually forcing something to un-played
  1344. // then it probably is what we want to do...
  1345. data.PlayCount = 0;
  1346. data.PlaybackPositionTicks = 0;
  1347. data.LastPlayedDate = null;
  1348. data.Played = false;
  1349. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1350. }
  1351. /// <summary>
  1352. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1353. /// </summary>
  1354. /// <returns>Task.</returns>
  1355. public virtual Task ChangedExternally()
  1356. {
  1357. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem));
  1358. return Task.FromResult(true);
  1359. }
  1360. /// <summary>
  1361. /// Gets an image
  1362. /// </summary>
  1363. /// <param name="type">The type.</param>
  1364. /// <param name="imageIndex">Index of the image.</param>
  1365. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1366. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1367. public bool HasImage(ImageType type, int imageIndex)
  1368. {
  1369. return GetImageInfo(type, imageIndex) != null;
  1370. }
  1371. public void SetImage(ItemImageInfo image, int index)
  1372. {
  1373. if (image.Type == ImageType.Chapter)
  1374. {
  1375. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1376. }
  1377. var existingImage = GetImageInfo(image.Type, index);
  1378. if (existingImage != null)
  1379. {
  1380. ImageInfos.Remove(existingImage);
  1381. }
  1382. ImageInfos.Add(image);
  1383. }
  1384. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1385. {
  1386. if (type == ImageType.Chapter)
  1387. {
  1388. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1389. }
  1390. var image = GetImageInfo(type, index);
  1391. if (image == null)
  1392. {
  1393. ImageInfos.Add(GetImageInfo(file, type));
  1394. }
  1395. else
  1396. {
  1397. var imageInfo = GetImageInfo(file, type);
  1398. image.Path = file.FullName;
  1399. image.DateModified = imageInfo.DateModified;
  1400. image.IsPlaceholder = false;
  1401. }
  1402. }
  1403. /// <summary>
  1404. /// Deletes the image.
  1405. /// </summary>
  1406. /// <param name="type">The type.</param>
  1407. /// <param name="index">The index.</param>
  1408. /// <returns>Task.</returns>
  1409. public Task DeleteImage(ImageType type, int index)
  1410. {
  1411. var info = GetImageInfo(type, index);
  1412. if (info == null)
  1413. {
  1414. // Nothing to do
  1415. return Task.FromResult(true);
  1416. }
  1417. // Remove it from the item
  1418. RemoveImage(info);
  1419. if (info.IsLocalFile)
  1420. {
  1421. // Delete the source file
  1422. var currentFile = new FileInfo(info.Path);
  1423. // Deletion will fail if the file is hidden so remove the attribute first
  1424. if (currentFile.Exists)
  1425. {
  1426. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1427. {
  1428. currentFile.Attributes &= ~FileAttributes.Hidden;
  1429. }
  1430. FileSystem.DeleteFile(currentFile.FullName);
  1431. }
  1432. }
  1433. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1434. }
  1435. public void RemoveImage(ItemImageInfo image)
  1436. {
  1437. ImageInfos.Remove(image);
  1438. }
  1439. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1440. {
  1441. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1442. }
  1443. /// <summary>
  1444. /// Validates that images within the item are still on the file system
  1445. /// </summary>
  1446. public bool ValidateImages(IDirectoryService directoryService)
  1447. {
  1448. var allFiles = ImageInfos
  1449. .Where(i => i.IsLocalFile)
  1450. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1451. .Distinct(StringComparer.OrdinalIgnoreCase)
  1452. .SelectMany(directoryService.GetFiles)
  1453. .Select(i => i.FullName)
  1454. .ToList();
  1455. var deletedImages = ImageInfos
  1456. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1457. .ToList();
  1458. if (deletedImages.Count > 0)
  1459. {
  1460. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1461. }
  1462. return deletedImages.Count > 0;
  1463. }
  1464. /// <summary>
  1465. /// Gets the image path.
  1466. /// </summary>
  1467. /// <param name="imageType">Type of the image.</param>
  1468. /// <param name="imageIndex">Index of the image.</param>
  1469. /// <returns>System.String.</returns>
  1470. /// <exception cref="System.InvalidOperationException">
  1471. /// </exception>
  1472. /// <exception cref="System.ArgumentNullException">item</exception>
  1473. public string GetImagePath(ImageType imageType, int imageIndex)
  1474. {
  1475. var info = GetImageInfo(imageType, imageIndex);
  1476. return info == null ? null : info.Path;
  1477. }
  1478. /// <summary>
  1479. /// Gets the image information.
  1480. /// </summary>
  1481. /// <param name="imageType">Type of the image.</param>
  1482. /// <param name="imageIndex">Index of the image.</param>
  1483. /// <returns>ItemImageInfo.</returns>
  1484. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1485. {
  1486. if (imageType == ImageType.Chapter)
  1487. {
  1488. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1489. if (chapter == null)
  1490. {
  1491. return null;
  1492. }
  1493. var path = chapter.ImagePath;
  1494. if (string.IsNullOrWhiteSpace(path))
  1495. {
  1496. return null;
  1497. }
  1498. return new ItemImageInfo
  1499. {
  1500. Path = path,
  1501. DateModified = FileSystem.GetLastWriteTimeUtc(path),
  1502. Type = imageType
  1503. };
  1504. }
  1505. return GetImages(imageType)
  1506. .ElementAtOrDefault(imageIndex);
  1507. }
  1508. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1509. {
  1510. if (imageType == ImageType.Chapter)
  1511. {
  1512. throw new ArgumentException("No image info for chapter images");
  1513. }
  1514. return ImageInfos.Where(i => i.Type == imageType);
  1515. }
  1516. /// <summary>
  1517. /// Adds the images.
  1518. /// </summary>
  1519. /// <param name="imageType">Type of the image.</param>
  1520. /// <param name="images">The images.</param>
  1521. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1522. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1523. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1524. {
  1525. if (imageType == ImageType.Chapter)
  1526. {
  1527. throw new ArgumentException("Cannot call AddImages with chapter images");
  1528. }
  1529. var existingImages = GetImages(imageType)
  1530. .ToList();
  1531. var newImageList = new List<FileSystemMetadata>();
  1532. var imageAdded = false;
  1533. foreach (var newImage in images)
  1534. {
  1535. if (newImage == null)
  1536. {
  1537. throw new ArgumentException("null image found in list");
  1538. }
  1539. var existing = existingImages
  1540. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1541. if (existing == null)
  1542. {
  1543. newImageList.Add(newImage);
  1544. imageAdded = true;
  1545. }
  1546. else
  1547. {
  1548. if (existing.IsLocalFile)
  1549. {
  1550. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1551. }
  1552. }
  1553. }
  1554. if (imageAdded || images.Count != existingImages.Count)
  1555. {
  1556. var newImagePaths = images.Select(i => i.FullName).ToList();
  1557. var deleted = existingImages
  1558. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1559. .ToList();
  1560. ImageInfos = ImageInfos.Except(deleted).ToList();
  1561. }
  1562. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1563. return newImageList.Count > 0;
  1564. }
  1565. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1566. {
  1567. return new ItemImageInfo
  1568. {
  1569. Path = file.FullName,
  1570. Type = type,
  1571. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1572. };
  1573. }
  1574. /// <summary>
  1575. /// Gets the file system path to delete when the item is to be deleted
  1576. /// </summary>
  1577. /// <returns></returns>
  1578. public virtual IEnumerable<string> GetDeletePaths()
  1579. {
  1580. return new[] { Path };
  1581. }
  1582. public bool AllowsMultipleImages(ImageType type)
  1583. {
  1584. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1585. }
  1586. public Task SwapImages(ImageType type, int index1, int index2)
  1587. {
  1588. if (!AllowsMultipleImages(type))
  1589. {
  1590. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1591. }
  1592. var info1 = GetImageInfo(type, index1);
  1593. var info2 = GetImageInfo(type, index2);
  1594. if (info1 == null || info2 == null)
  1595. {
  1596. // Nothing to do
  1597. return Task.FromResult(true);
  1598. }
  1599. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1600. {
  1601. // TODO: Not supported yet
  1602. return Task.FromResult(true);
  1603. }
  1604. var path1 = info1.Path;
  1605. var path2 = info2.Path;
  1606. FileSystem.SwapFiles(path1, path2);
  1607. // Refresh these values
  1608. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1609. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1610. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1611. }
  1612. public virtual bool IsPlayed(User user)
  1613. {
  1614. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1615. return userdata != null && userdata.Played;
  1616. }
  1617. public bool IsFavoriteOrLiked(User user)
  1618. {
  1619. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1620. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1621. }
  1622. public virtual bool IsUnplayed(User user)
  1623. {
  1624. if (user == null)
  1625. {
  1626. throw new ArgumentNullException("user");
  1627. }
  1628. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1629. return userdata == null || !userdata.Played;
  1630. }
  1631. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1632. {
  1633. return GetItemLookupInfo<ItemLookupInfo>();
  1634. }
  1635. protected T GetItemLookupInfo<T>()
  1636. where T : ItemLookupInfo, new()
  1637. {
  1638. return new T
  1639. {
  1640. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1641. MetadataLanguage = GetPreferredMetadataLanguage(),
  1642. Name = Name,
  1643. ProviderIds = ProviderIds,
  1644. IndexNumber = IndexNumber,
  1645. ParentIndexNumber = ParentIndexNumber,
  1646. Year = ProductionYear,
  1647. PremiereDate = PremiereDate
  1648. };
  1649. }
  1650. /// <summary>
  1651. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1652. /// </summary>
  1653. public virtual bool BeforeMetadataRefresh()
  1654. {
  1655. _userDataKey = null;
  1656. _sortName = null;
  1657. var hasChanges = false;
  1658. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1659. {
  1660. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1661. hasChanges = true;
  1662. }
  1663. return hasChanges;
  1664. }
  1665. protected static string GetMappedPath(string path, LocationType locationType)
  1666. {
  1667. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1668. {
  1669. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1670. {
  1671. path = LibraryManager.SubstitutePath(path, map.From, map.To);
  1672. }
  1673. }
  1674. return path;
  1675. }
  1676. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1677. {
  1678. if (RunTimeTicks.HasValue)
  1679. {
  1680. double pct = RunTimeTicks.Value;
  1681. if (pct > 0)
  1682. {
  1683. pct = userData.PlaybackPositionTicks / pct;
  1684. if (pct > 0)
  1685. {
  1686. dto.PlayedPercentage = 100 * pct;
  1687. }
  1688. }
  1689. }
  1690. }
  1691. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1692. {
  1693. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1694. {
  1695. ImageRefreshMode = options.ImageRefreshMode,
  1696. MetadataRefreshMode = options.MetadataRefreshMode,
  1697. ReplaceAllMetadata = options.ReplaceAllMetadata
  1698. };
  1699. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1700. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1701. var video = LibraryManager.GetItemById(id) as Video;
  1702. if (video == null)
  1703. {
  1704. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  1705. newOptions.ForceSave = true;
  1706. }
  1707. if (video == null)
  1708. {
  1709. return Task.FromResult(true);
  1710. }
  1711. return video.RefreshMetadata(newOptions, cancellationToken);
  1712. }
  1713. public string GetEtag(User user)
  1714. {
  1715. return string.Join("|", GetEtagValues(user).ToArray()).GetMD5().ToString("N");
  1716. }
  1717. protected virtual List<string> GetEtagValues(User user)
  1718. {
  1719. return new List<string>
  1720. {
  1721. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  1722. };
  1723. }
  1724. public virtual IEnumerable<Guid> GetAncestorIds()
  1725. {
  1726. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  1727. }
  1728. public BaseItem GetTopParent()
  1729. {
  1730. if (IsTopParent)
  1731. {
  1732. return this;
  1733. }
  1734. return GetParents().FirstOrDefault(i => i.IsTopParent);
  1735. }
  1736. [IgnoreDataMember]
  1737. public virtual bool IsTopParent
  1738. {
  1739. get
  1740. {
  1741. if (GetParent() is AggregateFolder || this is BasePluginFolder)
  1742. {
  1743. return true;
  1744. }
  1745. var view = this as UserView;
  1746. if (view != null && string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  1747. {
  1748. return true;
  1749. }
  1750. if (view != null && string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  1751. {
  1752. return true;
  1753. }
  1754. return false;
  1755. }
  1756. }
  1757. [IgnoreDataMember]
  1758. public virtual bool SupportsAncestors
  1759. {
  1760. get
  1761. {
  1762. return true;
  1763. }
  1764. }
  1765. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  1766. {
  1767. return new[] { Id };
  1768. }
  1769. public virtual Task Delete(DeleteOptions options)
  1770. {
  1771. return LibraryManager.DeleteItem(this, options);
  1772. }
  1773. public virtual Task OnFileDeleted()
  1774. {
  1775. // Remove from database
  1776. return Delete(new DeleteOptions
  1777. {
  1778. DeleteFileLocation = false
  1779. });
  1780. }
  1781. }
  1782. }