BaseItem.cs 66 KB

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