BaseItem.cs 68 KB

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