BaseItem.cs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605
  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 false; }
  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. existingImage.Width = image.Width;
  1631. existingImage.Height = image.Height;
  1632. }
  1633. else
  1634. {
  1635. var currentCount = ImageInfos.Length;
  1636. var newList = ImageInfos.ToArray(currentCount + 1);
  1637. newList[currentCount] = image;
  1638. ImageInfos = newList;
  1639. }
  1640. }
  1641. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1642. {
  1643. if (type == ImageType.Chapter)
  1644. {
  1645. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1646. }
  1647. var image = GetImageInfo(type, index);
  1648. if (image == null)
  1649. {
  1650. var currentCount = ImageInfos.Length;
  1651. var newList = ImageInfos.ToArray(currentCount + 1);
  1652. newList[currentCount] = GetImageInfo(file, type);
  1653. ImageInfos = newList;
  1654. }
  1655. else
  1656. {
  1657. var imageInfo = GetImageInfo(file, type);
  1658. image.Path = file.FullName;
  1659. image.DateModified = imageInfo.DateModified;
  1660. // reset these values
  1661. image.Width = 0;
  1662. image.Height = 0;
  1663. }
  1664. }
  1665. /// <summary>
  1666. /// Deletes the image.
  1667. /// </summary>
  1668. /// <param name="type">The type.</param>
  1669. /// <param name="index">The index.</param>
  1670. /// <returns>Task.</returns>
  1671. public void DeleteImage(ImageType type, int index)
  1672. {
  1673. var info = GetImageInfo(type, index);
  1674. if (info == null)
  1675. {
  1676. // Nothing to do
  1677. return;
  1678. }
  1679. // Remove it from the item
  1680. RemoveImage(info);
  1681. if (info.IsLocalFile)
  1682. {
  1683. FileSystem.DeleteFile(info.Path);
  1684. }
  1685. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1686. }
  1687. public void RemoveImage(ItemImageInfo image)
  1688. {
  1689. RemoveImages(new List<ItemImageInfo> { image });
  1690. }
  1691. public void RemoveImages(List<ItemImageInfo> deletedImages)
  1692. {
  1693. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1694. }
  1695. public virtual void UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1696. {
  1697. LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1698. }
  1699. /// <summary>
  1700. /// Validates that images within the item are still on the file system
  1701. /// </summary>
  1702. public bool ValidateImages(IDirectoryService directoryService)
  1703. {
  1704. var allFiles = ImageInfos
  1705. .Where(i => i.IsLocalFile)
  1706. .Select(i => FileSystem.GetDirectoryName(i.Path))
  1707. .Distinct(StringComparer.OrdinalIgnoreCase)
  1708. .SelectMany(i => FileSystem.GetFilePaths(i))
  1709. .ToList();
  1710. var deletedImages = ImageInfos
  1711. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1712. .ToList();
  1713. if (deletedImages.Count > 0)
  1714. {
  1715. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1716. }
  1717. return deletedImages.Count > 0;
  1718. }
  1719. /// <summary>
  1720. /// Gets the image path.
  1721. /// </summary>
  1722. /// <param name="imageType">Type of the image.</param>
  1723. /// <param name="imageIndex">Index of the image.</param>
  1724. /// <returns>System.String.</returns>
  1725. /// <exception cref="System.InvalidOperationException">
  1726. /// </exception>
  1727. /// <exception cref="System.ArgumentNullException">item</exception>
  1728. public string GetImagePath(ImageType imageType, int imageIndex)
  1729. {
  1730. var info = GetImageInfo(imageType, imageIndex);
  1731. return info == null ? null : info.Path;
  1732. }
  1733. /// <summary>
  1734. /// Gets the image information.
  1735. /// </summary>
  1736. /// <param name="imageType">Type of the image.</param>
  1737. /// <param name="imageIndex">Index of the image.</param>
  1738. /// <returns>ItemImageInfo.</returns>
  1739. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1740. {
  1741. if (imageType == ImageType.Chapter)
  1742. {
  1743. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1744. if (chapter == null)
  1745. {
  1746. return null;
  1747. }
  1748. var path = chapter.ImagePath;
  1749. if (string.IsNullOrWhiteSpace(path))
  1750. {
  1751. return null;
  1752. }
  1753. return new ItemImageInfo
  1754. {
  1755. Path = path,
  1756. DateModified = chapter.ImageDateModified,
  1757. Type = imageType
  1758. };
  1759. }
  1760. return GetImages(imageType)
  1761. .ElementAtOrDefault(imageIndex);
  1762. }
  1763. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1764. {
  1765. if (imageType == ImageType.Chapter)
  1766. {
  1767. throw new ArgumentException("No image info for chapter images");
  1768. }
  1769. return ImageInfos.Where(i => i.Type == imageType);
  1770. }
  1771. /// <summary>
  1772. /// Adds the images.
  1773. /// </summary>
  1774. /// <param name="imageType">Type of the image.</param>
  1775. /// <param name="images">The images.</param>
  1776. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1777. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1778. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1779. {
  1780. if (imageType == ImageType.Chapter)
  1781. {
  1782. throw new ArgumentException("Cannot call AddImages with chapter images");
  1783. }
  1784. var existingImages = GetImages(imageType)
  1785. .ToList();
  1786. var newImageList = new List<FileSystemMetadata>();
  1787. var imageAdded = false;
  1788. var imageUpdated = false;
  1789. foreach (var newImage in images)
  1790. {
  1791. if (newImage == null)
  1792. {
  1793. throw new ArgumentException("null image found in list");
  1794. }
  1795. var existing = existingImages
  1796. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1797. if (existing == null)
  1798. {
  1799. newImageList.Add(newImage);
  1800. imageAdded = true;
  1801. }
  1802. else
  1803. {
  1804. if (existing.IsLocalFile)
  1805. {
  1806. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1807. // If date changed then we need to reset saved image dimensions
  1808. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  1809. {
  1810. existing.Width = 0;
  1811. existing.Height = 0;
  1812. imageUpdated = true;
  1813. }
  1814. existing.DateModified = newDateModified;
  1815. }
  1816. }
  1817. }
  1818. if (imageAdded || images.Count != existingImages.Count)
  1819. {
  1820. var newImagePaths = images.Select(i => i.FullName).ToList();
  1821. var deleted = existingImages
  1822. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1823. .ToList();
  1824. if (deleted.Count > 0)
  1825. {
  1826. ImageInfos = ImageInfos.Except(deleted).ToArray();
  1827. }
  1828. }
  1829. if (newImageList.Count > 0)
  1830. {
  1831. var currentCount = ImageInfos.Length;
  1832. var newList = ImageInfos.ToArray(currentCount + newImageList.Count);
  1833. foreach (var image in newImageList)
  1834. {
  1835. newList[currentCount] = GetImageInfo(image, imageType);
  1836. currentCount++;
  1837. }
  1838. ImageInfos = newList;
  1839. }
  1840. return imageUpdated || newImageList.Count > 0;
  1841. }
  1842. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1843. {
  1844. return new ItemImageInfo
  1845. {
  1846. Path = file.FullName,
  1847. Type = type,
  1848. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1849. };
  1850. }
  1851. /// <summary>
  1852. /// Gets the file system path to delete when the item is to be deleted
  1853. /// </summary>
  1854. /// <returns></returns>
  1855. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  1856. {
  1857. return new[] {
  1858. new FileSystemMetadata
  1859. {
  1860. FullName = Path,
  1861. IsDirectory = IsFolder
  1862. }
  1863. }.Concat(GetLocalMetadataFilesToDelete());
  1864. }
  1865. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  1866. {
  1867. if (IsFolder || !IsInMixedFolder)
  1868. {
  1869. return new List<FileSystemMetadata>();
  1870. }
  1871. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  1872. var extensions = new List<string> { ".nfo", ".xml", ".srt" };
  1873. extensions.AddRange(SupportedImageExtensions);
  1874. return FileSystem.GetFiles(FileSystem.GetDirectoryName(Path), extensions.ToArray(extensions.Count), false, false)
  1875. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  1876. .ToList();
  1877. }
  1878. public bool AllowsMultipleImages(ImageType type)
  1879. {
  1880. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1881. }
  1882. public void SwapImages(ImageType type, int index1, int index2)
  1883. {
  1884. if (!AllowsMultipleImages(type))
  1885. {
  1886. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1887. }
  1888. var info1 = GetImageInfo(type, index1);
  1889. var info2 = GetImageInfo(type, index2);
  1890. if (info1 == null || info2 == null)
  1891. {
  1892. // Nothing to do
  1893. return;
  1894. }
  1895. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1896. {
  1897. // TODO: Not supported yet
  1898. return;
  1899. }
  1900. var path1 = info1.Path;
  1901. var path2 = info2.Path;
  1902. FileSystem.SwapFiles(path1, path2);
  1903. // Refresh these values
  1904. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1905. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1906. info1.Width = 0;
  1907. info1.Height = 0;
  1908. info2.Width = 0;
  1909. info2.Height = 0;
  1910. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1911. }
  1912. public virtual bool IsPlayed(User user)
  1913. {
  1914. var userdata = UserDataManager.GetUserData(user, this);
  1915. return userdata != null && userdata.Played;
  1916. }
  1917. public bool IsFavoriteOrLiked(User user)
  1918. {
  1919. var userdata = UserDataManager.GetUserData(user, this);
  1920. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1921. }
  1922. public virtual bool IsUnplayed(User user)
  1923. {
  1924. if (user == null)
  1925. {
  1926. throw new ArgumentNullException("user");
  1927. }
  1928. var userdata = UserDataManager.GetUserData(user, this);
  1929. return userdata == null || !userdata.Played;
  1930. }
  1931. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1932. {
  1933. return GetItemLookupInfo<ItemLookupInfo>();
  1934. }
  1935. protected T GetItemLookupInfo<T>()
  1936. where T : ItemLookupInfo, new()
  1937. {
  1938. return new T
  1939. {
  1940. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1941. MetadataLanguage = GetPreferredMetadataLanguage(),
  1942. Name = GetNameForMetadataLookup(),
  1943. ProviderIds = ProviderIds,
  1944. IndexNumber = IndexNumber,
  1945. ParentIndexNumber = ParentIndexNumber,
  1946. Year = ProductionYear,
  1947. PremiereDate = PremiereDate
  1948. };
  1949. }
  1950. protected virtual string GetNameForMetadataLookup()
  1951. {
  1952. return Name;
  1953. }
  1954. /// <summary>
  1955. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1956. /// </summary>
  1957. public virtual bool BeforeMetadataRefresh()
  1958. {
  1959. _sortName = null;
  1960. var hasChanges = false;
  1961. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1962. {
  1963. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1964. hasChanges = true;
  1965. }
  1966. return hasChanges;
  1967. }
  1968. protected static string GetMappedPath(BaseItem item, string path, LocationType locationType)
  1969. {
  1970. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1971. {
  1972. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  1973. }
  1974. return path;
  1975. }
  1976. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, ItemFields[] fields)
  1977. {
  1978. if (RunTimeTicks.HasValue)
  1979. {
  1980. double pct = RunTimeTicks.Value;
  1981. if (pct > 0)
  1982. {
  1983. pct = userData.PlaybackPositionTicks / pct;
  1984. if (pct > 0)
  1985. {
  1986. dto.PlayedPercentage = 100 * pct;
  1987. }
  1988. }
  1989. }
  1990. }
  1991. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  1992. {
  1993. var newOptions = new MetadataRefreshOptions(options);
  1994. newOptions.SearchResult = null;
  1995. var item = this;
  1996. if (copyTitleMetadata)
  1997. {
  1998. // Take some data from the main item, for querying purposes
  1999. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2000. {
  2001. newOptions.ForceSave = true;
  2002. ownedItem.Genres = item.Genres.ToList();
  2003. }
  2004. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2005. {
  2006. newOptions.ForceSave = true;
  2007. ownedItem.Studios = item.Studios;
  2008. }
  2009. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2010. {
  2011. newOptions.ForceSave = true;
  2012. ownedItem.ProductionLocations = item.ProductionLocations;
  2013. }
  2014. if (item.CommunityRating != ownedItem.CommunityRating)
  2015. {
  2016. ownedItem.CommunityRating = item.CommunityRating;
  2017. newOptions.ForceSave = true;
  2018. }
  2019. if (item.CriticRating != ownedItem.CriticRating)
  2020. {
  2021. ownedItem.CriticRating = item.CriticRating;
  2022. newOptions.ForceSave = true;
  2023. }
  2024. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2025. {
  2026. ownedItem.Overview = item.Overview;
  2027. newOptions.ForceSave = true;
  2028. }
  2029. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2030. {
  2031. ownedItem.OfficialRating = item.OfficialRating;
  2032. newOptions.ForceSave = true;
  2033. }
  2034. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2035. {
  2036. ownedItem.CustomRating = item.CustomRating;
  2037. newOptions.ForceSave = true;
  2038. }
  2039. }
  2040. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2041. }
  2042. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2043. {
  2044. var newOptions = new MetadataRefreshOptions(options);
  2045. newOptions.SearchResult = null;
  2046. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2047. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2048. var video = LibraryManager.GetItemById(id) as Video;
  2049. if (video == null)
  2050. {
  2051. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2052. newOptions.ForceSave = true;
  2053. }
  2054. //var parentId = Id;
  2055. //if (!video.IsOwnedItem || video.ParentId != parentId)
  2056. //{
  2057. // video.IsOwnedItem = true;
  2058. // video.ParentId = parentId;
  2059. // newOptions.ForceSave = true;
  2060. //}
  2061. if (video == null)
  2062. {
  2063. return Task.FromResult(true);
  2064. }
  2065. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2066. }
  2067. public string GetEtag(User user)
  2068. {
  2069. var list = GetEtagValues(user);
  2070. return string.Join("|", list.ToArray(list.Count)).GetMD5().ToString("N");
  2071. }
  2072. protected virtual List<string> GetEtagValues(User user)
  2073. {
  2074. return new List<string>
  2075. {
  2076. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2077. };
  2078. }
  2079. public virtual IEnumerable<Guid> GetAncestorIds()
  2080. {
  2081. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2082. }
  2083. public BaseItem GetTopParent()
  2084. {
  2085. if (IsTopParent)
  2086. {
  2087. return this;
  2088. }
  2089. foreach (var parent in GetParents())
  2090. {
  2091. if (parent.IsTopParent)
  2092. {
  2093. return parent;
  2094. }
  2095. }
  2096. return null;
  2097. }
  2098. [IgnoreDataMember]
  2099. public virtual bool IsTopParent
  2100. {
  2101. get
  2102. {
  2103. if (this is BasePluginFolder || this is Channel)
  2104. {
  2105. return true;
  2106. }
  2107. var view = this as UserView;
  2108. if (view != null)
  2109. {
  2110. if (string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2111. {
  2112. return true;
  2113. }
  2114. if (string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  2115. {
  2116. return true;
  2117. }
  2118. }
  2119. if (GetParent() is AggregateFolder)
  2120. {
  2121. return true;
  2122. }
  2123. return false;
  2124. }
  2125. }
  2126. [IgnoreDataMember]
  2127. public virtual bool SupportsAncestors
  2128. {
  2129. get
  2130. {
  2131. return true;
  2132. }
  2133. }
  2134. [IgnoreDataMember]
  2135. public virtual bool StopRefreshIfLocalMetadataFound
  2136. {
  2137. get
  2138. {
  2139. return true;
  2140. }
  2141. }
  2142. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2143. {
  2144. return new[] { Id };
  2145. }
  2146. public virtual Task Delete(DeleteOptions options)
  2147. {
  2148. return LibraryManager.DeleteItem(this, options);
  2149. }
  2150. public virtual List<ExternalUrl> GetRelatedUrls()
  2151. {
  2152. return new List<ExternalUrl>();
  2153. }
  2154. public virtual double? GetRefreshProgress()
  2155. {
  2156. return null;
  2157. }
  2158. public virtual ItemUpdateType OnMetadataChanged()
  2159. {
  2160. var updateType = ItemUpdateType.None;
  2161. var item = this;
  2162. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2163. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2164. {
  2165. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2166. updateType |= ItemUpdateType.MetadataImport;
  2167. }
  2168. return updateType;
  2169. }
  2170. }
  2171. }