BaseItem.cs 67 KB

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