BaseItem.cs 76 KB

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