BaseItem.cs 76 KB

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