BaseItem.cs 76 KB

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