BaseItem.cs 75 KB

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