BaseItem.cs 75 KB

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