BaseItem.cs 74 KB

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