BaseItem.cs 67 KB

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