BaseItem.cs 75 KB

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