BaseItem.cs 79 KB

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