BaseItem.cs 66 KB

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