BaseItem.cs 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200
  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. [IgnoreDataMember]
  965. public virtual string PresentationUniqueKey
  966. {
  967. get { return Id.ToString("N"); }
  968. }
  969. private string _userDataKey;
  970. /// <summary>
  971. /// Gets the user data key.
  972. /// </summary>
  973. /// <returns>System.String.</returns>
  974. public string GetUserDataKey()
  975. {
  976. if (string.IsNullOrWhiteSpace(_userDataKey))
  977. {
  978. var key = GetUserDataKeys().First();
  979. _userDataKey = key;
  980. return key;
  981. }
  982. return _userDataKey;
  983. }
  984. public virtual List<string> GetUserDataKeys()
  985. {
  986. var list = new List<string>();
  987. if (SourceType == SourceType.Channel)
  988. {
  989. if (!string.IsNullOrWhiteSpace(ExternalId))
  990. {
  991. list.Add(ExternalId);
  992. }
  993. }
  994. list.Add(Id.ToString());
  995. return list;
  996. }
  997. internal virtual bool IsValidFromResolver(BaseItem newItem)
  998. {
  999. var current = this;
  1000. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  1001. }
  1002. public void AfterMetadataRefresh()
  1003. {
  1004. _sortName = null;
  1005. _userDataKey = null;
  1006. }
  1007. /// <summary>
  1008. /// Gets the preferred metadata language.
  1009. /// </summary>
  1010. /// <returns>System.String.</returns>
  1011. public string GetPreferredMetadataLanguage()
  1012. {
  1013. string lang = PreferredMetadataLanguage;
  1014. if (string.IsNullOrWhiteSpace(lang))
  1015. {
  1016. lang = GetParents()
  1017. .Select(i => i.PreferredMetadataLanguage)
  1018. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1019. }
  1020. if (string.IsNullOrWhiteSpace(lang))
  1021. {
  1022. lang = LibraryManager.GetCollectionFolders(this)
  1023. .Select(i => i.PreferredMetadataLanguage)
  1024. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1025. }
  1026. if (string.IsNullOrWhiteSpace(lang))
  1027. {
  1028. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1029. }
  1030. return lang;
  1031. }
  1032. /// <summary>
  1033. /// Gets the preferred metadata language.
  1034. /// </summary>
  1035. /// <returns>System.String.</returns>
  1036. public string GetPreferredMetadataCountryCode()
  1037. {
  1038. string lang = PreferredMetadataCountryCode;
  1039. if (string.IsNullOrWhiteSpace(lang))
  1040. {
  1041. lang = GetParents()
  1042. .Select(i => i.PreferredMetadataCountryCode)
  1043. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1044. }
  1045. if (string.IsNullOrWhiteSpace(lang))
  1046. {
  1047. lang = LibraryManager.GetCollectionFolders(this)
  1048. .Select(i => i.PreferredMetadataCountryCode)
  1049. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1050. }
  1051. if (string.IsNullOrWhiteSpace(lang))
  1052. {
  1053. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1054. }
  1055. return lang;
  1056. }
  1057. public virtual bool IsSaveLocalMetadataEnabled()
  1058. {
  1059. if (SourceType == SourceType.Channel)
  1060. {
  1061. return false;
  1062. }
  1063. return ConfigurationManager.Configuration.SaveLocalMeta;
  1064. }
  1065. /// <summary>
  1066. /// Determines if a given user has access to this item
  1067. /// </summary>
  1068. /// <param name="user">The user.</param>
  1069. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1070. /// <exception cref="System.ArgumentNullException">user</exception>
  1071. public bool IsParentalAllowed(User user)
  1072. {
  1073. if (user == null)
  1074. {
  1075. throw new ArgumentNullException("user");
  1076. }
  1077. if (!IsVisibleViaTags(user))
  1078. {
  1079. return false;
  1080. }
  1081. var maxAllowedRating = user.Policy.MaxParentalRating;
  1082. if (maxAllowedRating == null)
  1083. {
  1084. return true;
  1085. }
  1086. var rating = CustomRatingForComparison;
  1087. if (string.IsNullOrWhiteSpace(rating))
  1088. {
  1089. rating = OfficialRatingForComparison;
  1090. }
  1091. if (string.IsNullOrWhiteSpace(rating))
  1092. {
  1093. return !GetBlockUnratedValue(user.Policy);
  1094. }
  1095. var value = LocalizationManager.GetRatingLevel(rating);
  1096. // Could not determine the integer value
  1097. if (!value.HasValue)
  1098. {
  1099. var isAllowed = !GetBlockUnratedValue(user.Policy);
  1100. if (!isAllowed)
  1101. {
  1102. Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1103. }
  1104. return isAllowed;
  1105. }
  1106. return value.Value <= maxAllowedRating.Value;
  1107. }
  1108. public int? GetParentalRatingValue()
  1109. {
  1110. var rating = CustomRating;
  1111. if (string.IsNullOrWhiteSpace(rating))
  1112. {
  1113. rating = OfficialRating;
  1114. }
  1115. if (string.IsNullOrWhiteSpace(rating))
  1116. {
  1117. return null;
  1118. }
  1119. return LocalizationManager.GetRatingLevel(rating);
  1120. }
  1121. public int? GetInheritedParentalRatingValue()
  1122. {
  1123. var rating = CustomRatingForComparison;
  1124. if (string.IsNullOrWhiteSpace(rating))
  1125. {
  1126. rating = OfficialRatingForComparison;
  1127. }
  1128. if (string.IsNullOrWhiteSpace(rating))
  1129. {
  1130. return null;
  1131. }
  1132. return LocalizationManager.GetRatingLevel(rating);
  1133. }
  1134. public List<string> GetInheritedTags()
  1135. {
  1136. var list = new List<string>();
  1137. list.AddRange(Tags);
  1138. foreach (var parent in GetParents())
  1139. {
  1140. list.AddRange(parent.Tags);
  1141. }
  1142. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1143. }
  1144. private bool IsVisibleViaTags(User user)
  1145. {
  1146. var hasTags = this as IHasTags;
  1147. if (hasTags != null)
  1148. {
  1149. var policy = user.Policy;
  1150. if (policy.BlockedTags.Any(i => hasTags.Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1151. {
  1152. return false;
  1153. }
  1154. }
  1155. return true;
  1156. }
  1157. protected virtual bool IsAllowTagFilterEnforced()
  1158. {
  1159. return true;
  1160. }
  1161. public virtual UnratedItem GetBlockUnratedType()
  1162. {
  1163. if (SourceType == SourceType.Channel)
  1164. {
  1165. return UnratedItem.ChannelContent;
  1166. }
  1167. return UnratedItem.Other;
  1168. }
  1169. /// <summary>
  1170. /// Gets the block unrated value.
  1171. /// </summary>
  1172. /// <param name="config">The configuration.</param>
  1173. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1174. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  1175. {
  1176. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1177. // Special folders like series and albums will override this method.
  1178. if (IsFolder)
  1179. {
  1180. return false;
  1181. }
  1182. if (this is IItemByName)
  1183. {
  1184. return false;
  1185. }
  1186. return config.BlockUnratedItems.Contains(GetBlockUnratedType());
  1187. }
  1188. /// <summary>
  1189. /// Determines if this folder should be visible to a given user.
  1190. /// Default is just parental allowed. Can be overridden for more functionality.
  1191. /// </summary>
  1192. /// <param name="user">The user.</param>
  1193. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1194. /// <exception cref="System.ArgumentNullException">user</exception>
  1195. public virtual bool IsVisible(User user)
  1196. {
  1197. if (user == null)
  1198. {
  1199. throw new ArgumentNullException("user");
  1200. }
  1201. return IsParentalAllowed(user);
  1202. }
  1203. public virtual bool IsVisibleStandalone(User user)
  1204. {
  1205. if (SourceType == SourceType.Channel)
  1206. {
  1207. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1208. }
  1209. return IsVisibleStandaloneInternal(user, true);
  1210. }
  1211. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1212. {
  1213. if (!IsVisible(user))
  1214. {
  1215. return false;
  1216. }
  1217. if (GetParents().Any(i => !i.IsVisible(user)))
  1218. {
  1219. return false;
  1220. }
  1221. if (checkFolders)
  1222. {
  1223. var topParent = GetParents().LastOrDefault() ?? this;
  1224. if (string.IsNullOrWhiteSpace(topParent.Path))
  1225. {
  1226. return true;
  1227. }
  1228. var userCollectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  1229. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id);
  1230. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1231. {
  1232. return false;
  1233. }
  1234. }
  1235. return true;
  1236. }
  1237. /// <summary>
  1238. /// Gets a value indicating whether this instance is folder.
  1239. /// </summary>
  1240. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1241. [IgnoreDataMember]
  1242. public virtual bool IsFolder
  1243. {
  1244. get
  1245. {
  1246. return false;
  1247. }
  1248. }
  1249. public virtual string GetClientTypeName()
  1250. {
  1251. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1252. {
  1253. return "ChannelFolderItem";
  1254. }
  1255. return GetType().Name;
  1256. }
  1257. /// <summary>
  1258. /// Gets the linked child.
  1259. /// </summary>
  1260. /// <param name="info">The info.</param>
  1261. /// <returns>BaseItem.</returns>
  1262. protected BaseItem GetLinkedChild(LinkedChild info)
  1263. {
  1264. // First get using the cached Id
  1265. if (info.ItemId.HasValue)
  1266. {
  1267. if (info.ItemId.Value == Guid.Empty)
  1268. {
  1269. return null;
  1270. }
  1271. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1272. if (itemById != null)
  1273. {
  1274. return itemById;
  1275. }
  1276. }
  1277. var item = FindLinkedChild(info);
  1278. // If still null, log
  1279. if (item == null)
  1280. {
  1281. // Don't keep searching over and over
  1282. info.ItemId = Guid.Empty;
  1283. }
  1284. else
  1285. {
  1286. // Cache the id for next time
  1287. info.ItemId = item.Id;
  1288. }
  1289. return item;
  1290. }
  1291. private BaseItem FindLinkedChild(LinkedChild info)
  1292. {
  1293. if (!string.IsNullOrEmpty(info.Path))
  1294. {
  1295. var itemByPath = LibraryManager.FindByPath(info.Path, null);
  1296. if (itemByPath == null)
  1297. {
  1298. //Logger.Warn("Unable to find linked item at path {0}", info.Path);
  1299. }
  1300. return itemByPath;
  1301. }
  1302. return null;
  1303. }
  1304. [IgnoreDataMember]
  1305. public virtual bool EnableRememberingTrackSelections
  1306. {
  1307. get
  1308. {
  1309. return true;
  1310. }
  1311. }
  1312. /// <summary>
  1313. /// Adds a studio to the item
  1314. /// </summary>
  1315. /// <param name="name">The name.</param>
  1316. /// <exception cref="System.ArgumentNullException"></exception>
  1317. public void AddStudio(string name)
  1318. {
  1319. if (string.IsNullOrWhiteSpace(name))
  1320. {
  1321. throw new ArgumentNullException("name");
  1322. }
  1323. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1324. {
  1325. Studios.Add(name);
  1326. }
  1327. }
  1328. /// <summary>
  1329. /// Adds a genre to the item
  1330. /// </summary>
  1331. /// <param name="name">The name.</param>
  1332. /// <exception cref="System.ArgumentNullException"></exception>
  1333. public void AddGenre(string name)
  1334. {
  1335. if (string.IsNullOrWhiteSpace(name))
  1336. {
  1337. throw new ArgumentNullException("name");
  1338. }
  1339. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1340. {
  1341. Genres.Add(name);
  1342. }
  1343. }
  1344. /// <summary>
  1345. /// Marks the played.
  1346. /// </summary>
  1347. /// <param name="user">The user.</param>
  1348. /// <param name="datePlayed">The date played.</param>
  1349. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1350. /// <returns>Task.</returns>
  1351. /// <exception cref="System.ArgumentNullException"></exception>
  1352. public virtual async Task MarkPlayed(User user,
  1353. DateTime? datePlayed,
  1354. bool resetPosition)
  1355. {
  1356. if (user == null)
  1357. {
  1358. throw new ArgumentNullException();
  1359. }
  1360. var data = UserDataManager.GetUserData(user, this);
  1361. if (datePlayed.HasValue)
  1362. {
  1363. // Incremenet
  1364. data.PlayCount++;
  1365. }
  1366. // Ensure it's at least one
  1367. data.PlayCount = Math.Max(data.PlayCount, 1);
  1368. if (resetPosition)
  1369. {
  1370. data.PlaybackPositionTicks = 0;
  1371. }
  1372. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1373. data.Played = true;
  1374. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1375. }
  1376. /// <summary>
  1377. /// Marks the unplayed.
  1378. /// </summary>
  1379. /// <param name="user">The user.</param>
  1380. /// <returns>Task.</returns>
  1381. /// <exception cref="System.ArgumentNullException"></exception>
  1382. public virtual async Task MarkUnplayed(User user)
  1383. {
  1384. if (user == null)
  1385. {
  1386. throw new ArgumentNullException();
  1387. }
  1388. var data = UserDataManager.GetUserData(user, this);
  1389. //I think it is okay to do this here.
  1390. // if this is only called when a user is manually forcing something to un-played
  1391. // then it probably is what we want to do...
  1392. data.PlayCount = 0;
  1393. data.PlaybackPositionTicks = 0;
  1394. data.LastPlayedDate = null;
  1395. data.Played = false;
  1396. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1397. }
  1398. /// <summary>
  1399. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1400. /// </summary>
  1401. /// <returns>Task.</returns>
  1402. public virtual Task ChangedExternally()
  1403. {
  1404. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem));
  1405. return Task.FromResult(true);
  1406. }
  1407. /// <summary>
  1408. /// Gets an image
  1409. /// </summary>
  1410. /// <param name="type">The type.</param>
  1411. /// <param name="imageIndex">Index of the image.</param>
  1412. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1413. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1414. public bool HasImage(ImageType type, int imageIndex)
  1415. {
  1416. return GetImageInfo(type, imageIndex) != null;
  1417. }
  1418. public void SetImage(ItemImageInfo image, int index)
  1419. {
  1420. if (image.Type == ImageType.Chapter)
  1421. {
  1422. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1423. }
  1424. var existingImage = GetImageInfo(image.Type, index);
  1425. if (existingImage != null)
  1426. {
  1427. ImageInfos.Remove(existingImage);
  1428. }
  1429. ImageInfos.Add(image);
  1430. }
  1431. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1432. {
  1433. if (type == ImageType.Chapter)
  1434. {
  1435. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1436. }
  1437. var image = GetImageInfo(type, index);
  1438. if (image == null)
  1439. {
  1440. ImageInfos.Add(GetImageInfo(file, type));
  1441. }
  1442. else
  1443. {
  1444. var imageInfo = GetImageInfo(file, type);
  1445. image.Path = file.FullName;
  1446. image.DateModified = imageInfo.DateModified;
  1447. image.IsPlaceholder = false;
  1448. }
  1449. }
  1450. /// <summary>
  1451. /// Deletes the image.
  1452. /// </summary>
  1453. /// <param name="type">The type.</param>
  1454. /// <param name="index">The index.</param>
  1455. /// <returns>Task.</returns>
  1456. public Task DeleteImage(ImageType type, int index)
  1457. {
  1458. var info = GetImageInfo(type, index);
  1459. if (info == null)
  1460. {
  1461. // Nothing to do
  1462. return Task.FromResult(true);
  1463. }
  1464. // Remove it from the item
  1465. RemoveImage(info);
  1466. if (info.IsLocalFile)
  1467. {
  1468. // Delete the source file
  1469. var currentFile = new FileInfo(info.Path);
  1470. // Deletion will fail if the file is hidden so remove the attribute first
  1471. if (currentFile.Exists)
  1472. {
  1473. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1474. {
  1475. currentFile.Attributes &= ~FileAttributes.Hidden;
  1476. }
  1477. FileSystem.DeleteFile(currentFile.FullName);
  1478. }
  1479. }
  1480. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1481. }
  1482. public void RemoveImage(ItemImageInfo image)
  1483. {
  1484. ImageInfos.Remove(image);
  1485. }
  1486. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1487. {
  1488. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1489. }
  1490. /// <summary>
  1491. /// Validates that images within the item are still on the file system
  1492. /// </summary>
  1493. public bool ValidateImages(IDirectoryService directoryService)
  1494. {
  1495. var allFiles = ImageInfos
  1496. .Where(i => i.IsLocalFile)
  1497. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1498. .Distinct(StringComparer.OrdinalIgnoreCase)
  1499. .SelectMany(directoryService.GetFiles)
  1500. .Select(i => i.FullName)
  1501. .ToList();
  1502. var deletedImages = ImageInfos
  1503. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1504. .ToList();
  1505. if (deletedImages.Count > 0)
  1506. {
  1507. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1508. }
  1509. return deletedImages.Count > 0;
  1510. }
  1511. /// <summary>
  1512. /// Gets the image path.
  1513. /// </summary>
  1514. /// <param name="imageType">Type of the image.</param>
  1515. /// <param name="imageIndex">Index of the image.</param>
  1516. /// <returns>System.String.</returns>
  1517. /// <exception cref="System.InvalidOperationException">
  1518. /// </exception>
  1519. /// <exception cref="System.ArgumentNullException">item</exception>
  1520. public string GetImagePath(ImageType imageType, int imageIndex)
  1521. {
  1522. var info = GetImageInfo(imageType, imageIndex);
  1523. return info == null ? null : info.Path;
  1524. }
  1525. /// <summary>
  1526. /// Gets the image information.
  1527. /// </summary>
  1528. /// <param name="imageType">Type of the image.</param>
  1529. /// <param name="imageIndex">Index of the image.</param>
  1530. /// <returns>ItemImageInfo.</returns>
  1531. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1532. {
  1533. if (imageType == ImageType.Chapter)
  1534. {
  1535. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1536. if (chapter == null)
  1537. {
  1538. return null;
  1539. }
  1540. var path = chapter.ImagePath;
  1541. if (string.IsNullOrWhiteSpace(path))
  1542. {
  1543. return null;
  1544. }
  1545. return new ItemImageInfo
  1546. {
  1547. Path = path,
  1548. DateModified = FileSystem.GetLastWriteTimeUtc(path),
  1549. Type = imageType
  1550. };
  1551. }
  1552. return GetImages(imageType)
  1553. .ElementAtOrDefault(imageIndex);
  1554. }
  1555. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1556. {
  1557. if (imageType == ImageType.Chapter)
  1558. {
  1559. throw new ArgumentException("No image info for chapter images");
  1560. }
  1561. return ImageInfos.Where(i => i.Type == imageType);
  1562. }
  1563. /// <summary>
  1564. /// Adds the images.
  1565. /// </summary>
  1566. /// <param name="imageType">Type of the image.</param>
  1567. /// <param name="images">The images.</param>
  1568. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1569. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1570. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1571. {
  1572. if (imageType == ImageType.Chapter)
  1573. {
  1574. throw new ArgumentException("Cannot call AddImages with chapter images");
  1575. }
  1576. var existingImages = GetImages(imageType)
  1577. .ToList();
  1578. var newImageList = new List<FileSystemMetadata>();
  1579. var imageAdded = false;
  1580. foreach (var newImage in images)
  1581. {
  1582. if (newImage == null)
  1583. {
  1584. throw new ArgumentException("null image found in list");
  1585. }
  1586. var existing = existingImages
  1587. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1588. if (existing == null)
  1589. {
  1590. newImageList.Add(newImage);
  1591. imageAdded = true;
  1592. }
  1593. else
  1594. {
  1595. if (existing.IsLocalFile)
  1596. {
  1597. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1598. }
  1599. }
  1600. }
  1601. if (imageAdded || images.Count != existingImages.Count)
  1602. {
  1603. var newImagePaths = images.Select(i => i.FullName).ToList();
  1604. var deleted = existingImages
  1605. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1606. .ToList();
  1607. ImageInfos = ImageInfos.Except(deleted).ToList();
  1608. }
  1609. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1610. return newImageList.Count > 0;
  1611. }
  1612. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1613. {
  1614. return new ItemImageInfo
  1615. {
  1616. Path = file.FullName,
  1617. Type = type,
  1618. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1619. };
  1620. }
  1621. /// <summary>
  1622. /// Gets the file system path to delete when the item is to be deleted
  1623. /// </summary>
  1624. /// <returns></returns>
  1625. public virtual IEnumerable<string> GetDeletePaths()
  1626. {
  1627. return new[] { Path };
  1628. }
  1629. public bool AllowsMultipleImages(ImageType type)
  1630. {
  1631. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1632. }
  1633. public Task SwapImages(ImageType type, int index1, int index2)
  1634. {
  1635. if (!AllowsMultipleImages(type))
  1636. {
  1637. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1638. }
  1639. var info1 = GetImageInfo(type, index1);
  1640. var info2 = GetImageInfo(type, index2);
  1641. if (info1 == null || info2 == null)
  1642. {
  1643. // Nothing to do
  1644. return Task.FromResult(true);
  1645. }
  1646. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1647. {
  1648. // TODO: Not supported yet
  1649. return Task.FromResult(true);
  1650. }
  1651. var path1 = info1.Path;
  1652. var path2 = info2.Path;
  1653. FileSystem.SwapFiles(path1, path2);
  1654. // Refresh these values
  1655. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1656. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1657. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1658. }
  1659. public virtual bool IsPlayed(User user)
  1660. {
  1661. var userdata = UserDataManager.GetUserData(user, this);
  1662. return userdata != null && userdata.Played;
  1663. }
  1664. public bool IsFavoriteOrLiked(User user)
  1665. {
  1666. var userdata = UserDataManager.GetUserData(user, this);
  1667. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1668. }
  1669. public virtual bool IsUnplayed(User user)
  1670. {
  1671. if (user == null)
  1672. {
  1673. throw new ArgumentNullException("user");
  1674. }
  1675. var userdata = UserDataManager.GetUserData(user, this);
  1676. return userdata == null || !userdata.Played;
  1677. }
  1678. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1679. {
  1680. return GetItemLookupInfo<ItemLookupInfo>();
  1681. }
  1682. protected T GetItemLookupInfo<T>()
  1683. where T : ItemLookupInfo, new()
  1684. {
  1685. return new T
  1686. {
  1687. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1688. MetadataLanguage = GetPreferredMetadataLanguage(),
  1689. Name = Name,
  1690. ProviderIds = ProviderIds,
  1691. IndexNumber = IndexNumber,
  1692. ParentIndexNumber = ParentIndexNumber,
  1693. Year = ProductionYear,
  1694. PremiereDate = PremiereDate
  1695. };
  1696. }
  1697. /// <summary>
  1698. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1699. /// </summary>
  1700. public virtual bool BeforeMetadataRefresh()
  1701. {
  1702. _userDataKey = null;
  1703. _sortName = null;
  1704. var hasChanges = false;
  1705. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1706. {
  1707. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1708. hasChanges = true;
  1709. }
  1710. return hasChanges;
  1711. }
  1712. protected static string GetMappedPath(string path, LocationType locationType)
  1713. {
  1714. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1715. {
  1716. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1717. {
  1718. path = LibraryManager.SubstitutePath(path, map.From, map.To);
  1719. }
  1720. }
  1721. return path;
  1722. }
  1723. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1724. {
  1725. if (RunTimeTicks.HasValue)
  1726. {
  1727. double pct = RunTimeTicks.Value;
  1728. if (pct > 0)
  1729. {
  1730. pct = userData.PlaybackPositionTicks / pct;
  1731. if (pct > 0)
  1732. {
  1733. dto.PlayedPercentage = 100 * pct;
  1734. }
  1735. }
  1736. }
  1737. }
  1738. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1739. {
  1740. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1741. {
  1742. ImageRefreshMode = options.ImageRefreshMode,
  1743. MetadataRefreshMode = options.MetadataRefreshMode,
  1744. ReplaceAllMetadata = options.ReplaceAllMetadata
  1745. };
  1746. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1747. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1748. var video = LibraryManager.GetItemById(id) as Video;
  1749. if (video == null)
  1750. {
  1751. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  1752. newOptions.ForceSave = true;
  1753. }
  1754. if (video == null)
  1755. {
  1756. return Task.FromResult(true);
  1757. }
  1758. return video.RefreshMetadata(newOptions, cancellationToken);
  1759. }
  1760. public string GetEtag(User user)
  1761. {
  1762. return string.Join("|", GetEtagValues(user).ToArray()).GetMD5().ToString("N");
  1763. }
  1764. protected virtual List<string> GetEtagValues(User user)
  1765. {
  1766. return new List<string>
  1767. {
  1768. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  1769. };
  1770. }
  1771. public virtual IEnumerable<Guid> GetAncestorIds()
  1772. {
  1773. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  1774. }
  1775. public BaseItem GetTopParent()
  1776. {
  1777. if (IsTopParent)
  1778. {
  1779. return this;
  1780. }
  1781. return GetParents().FirstOrDefault(i => i.IsTopParent);
  1782. }
  1783. [IgnoreDataMember]
  1784. public virtual bool IsTopParent
  1785. {
  1786. get
  1787. {
  1788. if (GetParent() is AggregateFolder || this is BasePluginFolder)
  1789. {
  1790. return true;
  1791. }
  1792. var view = this as UserView;
  1793. if (view != null && string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  1794. {
  1795. return true;
  1796. }
  1797. if (view != null && string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  1798. {
  1799. return true;
  1800. }
  1801. return false;
  1802. }
  1803. }
  1804. [IgnoreDataMember]
  1805. public virtual bool SupportsAncestors
  1806. {
  1807. get
  1808. {
  1809. return true;
  1810. }
  1811. }
  1812. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  1813. {
  1814. return new[] { Id };
  1815. }
  1816. public virtual Task Delete(DeleteOptions options)
  1817. {
  1818. return LibraryManager.DeleteItem(this, options);
  1819. }
  1820. public virtual Task OnFileDeleted()
  1821. {
  1822. // Remove from database
  1823. return Delete(new DeleteOptions
  1824. {
  1825. DeleteFileLocation = false
  1826. });
  1827. }
  1828. }
  1829. }