BaseItem.cs 80 KB

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