BaseItem.cs 66 KB

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