BaseItem.cs 76 KB

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