BaseItem.cs 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561
  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. return true;
  1138. }
  1139. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1140. {
  1141. var updateType = ItemUpdateType.None;
  1142. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1143. {
  1144. IsInMixedFolder = newItem.IsInMixedFolder;
  1145. updateType |= ItemUpdateType.MetadataImport;
  1146. }
  1147. return updateType;
  1148. }
  1149. public void AfterMetadataRefresh()
  1150. {
  1151. _sortName = null;
  1152. }
  1153. /// <summary>
  1154. /// Gets the preferred metadata language.
  1155. /// </summary>
  1156. /// <returns>System.String.</returns>
  1157. public string GetPreferredMetadataLanguage()
  1158. {
  1159. string lang = PreferredMetadataLanguage;
  1160. if (string.IsNullOrWhiteSpace(lang))
  1161. {
  1162. lang = GetParents()
  1163. .Select(i => i.PreferredMetadataLanguage)
  1164. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1165. }
  1166. if (string.IsNullOrWhiteSpace(lang))
  1167. {
  1168. lang = LibraryManager.GetCollectionFolders(this)
  1169. .Select(i => i.PreferredMetadataLanguage)
  1170. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1171. }
  1172. if (string.IsNullOrWhiteSpace(lang))
  1173. {
  1174. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1175. }
  1176. if (string.IsNullOrWhiteSpace(lang))
  1177. {
  1178. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1179. }
  1180. return lang;
  1181. }
  1182. /// <summary>
  1183. /// Gets the preferred metadata language.
  1184. /// </summary>
  1185. /// <returns>System.String.</returns>
  1186. public string GetPreferredMetadataCountryCode()
  1187. {
  1188. string lang = PreferredMetadataCountryCode;
  1189. if (string.IsNullOrWhiteSpace(lang))
  1190. {
  1191. lang = GetParents()
  1192. .Select(i => i.PreferredMetadataCountryCode)
  1193. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1194. }
  1195. if (string.IsNullOrWhiteSpace(lang))
  1196. {
  1197. lang = LibraryManager.GetCollectionFolders(this)
  1198. .Select(i => i.PreferredMetadataCountryCode)
  1199. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1200. }
  1201. if (string.IsNullOrWhiteSpace(lang))
  1202. {
  1203. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1204. }
  1205. if (string.IsNullOrWhiteSpace(lang))
  1206. {
  1207. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1208. }
  1209. return lang;
  1210. }
  1211. public virtual bool IsSaveLocalMetadataEnabled()
  1212. {
  1213. if (SourceType == SourceType.Channel)
  1214. {
  1215. return false;
  1216. }
  1217. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1218. return libraryOptions.SaveLocalMetadata;
  1219. }
  1220. /// <summary>
  1221. /// Determines if a given user has access to this item
  1222. /// </summary>
  1223. /// <param name="user">The user.</param>
  1224. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1225. /// <exception cref="System.ArgumentNullException">user</exception>
  1226. public bool IsParentalAllowed(User user)
  1227. {
  1228. if (user == null)
  1229. {
  1230. throw new ArgumentNullException("user");
  1231. }
  1232. if (!IsVisibleViaTags(user))
  1233. {
  1234. return false;
  1235. }
  1236. var maxAllowedRating = user.Policy.MaxParentalRating;
  1237. if (maxAllowedRating == null)
  1238. {
  1239. return true;
  1240. }
  1241. var rating = CustomRatingForComparison;
  1242. if (string.IsNullOrWhiteSpace(rating))
  1243. {
  1244. rating = OfficialRatingForComparison;
  1245. }
  1246. if (string.IsNullOrWhiteSpace(rating))
  1247. {
  1248. return !GetBlockUnratedValue(user.Policy);
  1249. }
  1250. var value = LocalizationManager.GetRatingLevel(rating);
  1251. // Could not determine the integer value
  1252. if (!value.HasValue)
  1253. {
  1254. var isAllowed = !GetBlockUnratedValue(user.Policy);
  1255. if (!isAllowed)
  1256. {
  1257. Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1258. }
  1259. return isAllowed;
  1260. }
  1261. return value.Value <= maxAllowedRating.Value;
  1262. }
  1263. public int? GetParentalRatingValue()
  1264. {
  1265. var rating = CustomRating;
  1266. if (string.IsNullOrWhiteSpace(rating))
  1267. {
  1268. rating = OfficialRating;
  1269. }
  1270. if (string.IsNullOrWhiteSpace(rating))
  1271. {
  1272. return null;
  1273. }
  1274. return LocalizationManager.GetRatingLevel(rating);
  1275. }
  1276. public int? GetInheritedParentalRatingValue()
  1277. {
  1278. var rating = CustomRatingForComparison;
  1279. if (string.IsNullOrWhiteSpace(rating))
  1280. {
  1281. rating = OfficialRatingForComparison;
  1282. }
  1283. if (string.IsNullOrWhiteSpace(rating))
  1284. {
  1285. return null;
  1286. }
  1287. return LocalizationManager.GetRatingLevel(rating);
  1288. }
  1289. public List<string> GetInheritedTags()
  1290. {
  1291. var list = new List<string>();
  1292. list.AddRange(Tags);
  1293. foreach (var parent in GetParents())
  1294. {
  1295. list.AddRange(parent.Tags);
  1296. }
  1297. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1298. }
  1299. private bool IsVisibleViaTags(User user)
  1300. {
  1301. var policy = user.Policy;
  1302. if (policy.BlockedTags.Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1303. {
  1304. return false;
  1305. }
  1306. return true;
  1307. }
  1308. protected virtual bool IsAllowTagFilterEnforced()
  1309. {
  1310. return true;
  1311. }
  1312. public virtual UnratedItem GetBlockUnratedType()
  1313. {
  1314. if (SourceType == SourceType.Channel)
  1315. {
  1316. return UnratedItem.ChannelContent;
  1317. }
  1318. return UnratedItem.Other;
  1319. }
  1320. /// <summary>
  1321. /// Gets the block unrated value.
  1322. /// </summary>
  1323. /// <param name="config">The configuration.</param>
  1324. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1325. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  1326. {
  1327. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1328. // Special folders like series and albums will override this method.
  1329. if (IsFolder)
  1330. {
  1331. return false;
  1332. }
  1333. if (this is IItemByName)
  1334. {
  1335. return false;
  1336. }
  1337. return config.BlockUnratedItems.Contains(GetBlockUnratedType());
  1338. }
  1339. /// <summary>
  1340. /// Determines if this folder should be visible to a given user.
  1341. /// Default is just parental allowed. Can be overridden for more functionality.
  1342. /// </summary>
  1343. /// <param name="user">The user.</param>
  1344. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1345. /// <exception cref="System.ArgumentNullException">user</exception>
  1346. public virtual bool IsVisible(User user)
  1347. {
  1348. if (user == null)
  1349. {
  1350. throw new ArgumentNullException("user");
  1351. }
  1352. return IsParentalAllowed(user);
  1353. }
  1354. public virtual bool IsVisibleStandalone(User user)
  1355. {
  1356. if (SourceType == SourceType.Channel)
  1357. {
  1358. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1359. }
  1360. return IsVisibleStandaloneInternal(user, true);
  1361. }
  1362. [IgnoreDataMember]
  1363. public virtual bool SupportsInheritedParentImages
  1364. {
  1365. get { return false; }
  1366. }
  1367. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1368. {
  1369. if (!IsVisible(user))
  1370. {
  1371. return false;
  1372. }
  1373. if (GetParents().Any(i => !i.IsVisible(user)))
  1374. {
  1375. return false;
  1376. }
  1377. if (checkFolders)
  1378. {
  1379. var topParent = GetParents().LastOrDefault() ?? this;
  1380. if (string.IsNullOrWhiteSpace(topParent.Path))
  1381. {
  1382. return true;
  1383. }
  1384. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1385. if (itemCollectionFolders.Count > 0)
  1386. {
  1387. var userCollectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  1388. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1389. {
  1390. return false;
  1391. }
  1392. }
  1393. }
  1394. return true;
  1395. }
  1396. /// <summary>
  1397. /// Gets a value indicating whether this instance is folder.
  1398. /// </summary>
  1399. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1400. [IgnoreDataMember]
  1401. public virtual bool IsFolder
  1402. {
  1403. get
  1404. {
  1405. return false;
  1406. }
  1407. }
  1408. [IgnoreDataMember]
  1409. public virtual bool IsDisplayedAsFolder
  1410. {
  1411. get
  1412. {
  1413. return false;
  1414. }
  1415. }
  1416. public virtual string GetClientTypeName()
  1417. {
  1418. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1419. {
  1420. return "ChannelFolderItem";
  1421. }
  1422. return GetType().Name;
  1423. }
  1424. /// <summary>
  1425. /// Gets the linked child.
  1426. /// </summary>
  1427. /// <param name="info">The info.</param>
  1428. /// <returns>BaseItem.</returns>
  1429. protected BaseItem GetLinkedChild(LinkedChild info)
  1430. {
  1431. // First get using the cached Id
  1432. if (info.ItemId.HasValue)
  1433. {
  1434. if (info.ItemId.Value == Guid.Empty)
  1435. {
  1436. return null;
  1437. }
  1438. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1439. if (itemById != null)
  1440. {
  1441. return itemById;
  1442. }
  1443. }
  1444. var item = FindLinkedChild(info);
  1445. // If still null, log
  1446. if (item == null)
  1447. {
  1448. // Don't keep searching over and over
  1449. info.ItemId = Guid.Empty;
  1450. }
  1451. else
  1452. {
  1453. // Cache the id for next time
  1454. info.ItemId = item.Id;
  1455. }
  1456. return item;
  1457. }
  1458. private BaseItem FindLinkedChild(LinkedChild info)
  1459. {
  1460. if (!string.IsNullOrWhiteSpace(info.Path))
  1461. {
  1462. var itemByPath = LibraryManager.FindByPath(info.Path, null);
  1463. if (itemByPath == null)
  1464. {
  1465. //Logger.Warn("Unable to find linked item at path {0}", info.Path);
  1466. }
  1467. return itemByPath;
  1468. }
  1469. return null;
  1470. }
  1471. [IgnoreDataMember]
  1472. public virtual bool EnableRememberingTrackSelections
  1473. {
  1474. get
  1475. {
  1476. return true;
  1477. }
  1478. }
  1479. /// <summary>
  1480. /// Adds a studio to the item
  1481. /// </summary>
  1482. /// <param name="name">The name.</param>
  1483. /// <exception cref="System.ArgumentNullException"></exception>
  1484. public void AddStudio(string name)
  1485. {
  1486. if (string.IsNullOrWhiteSpace(name))
  1487. {
  1488. throw new ArgumentNullException("name");
  1489. }
  1490. var current = Studios;
  1491. if (!current.Contains(name, StringComparer.OrdinalIgnoreCase))
  1492. {
  1493. if (current.Length == 0)
  1494. {
  1495. Studios = new[] { name };
  1496. }
  1497. else
  1498. {
  1499. var list = current.ToArray(current.Length + 1);
  1500. list[list.Length - 1] = name;
  1501. Studios = list;
  1502. }
  1503. }
  1504. }
  1505. public void SetStudios(IEnumerable<string> names)
  1506. {
  1507. Studios = names.Distinct().ToArray();
  1508. }
  1509. /// <summary>
  1510. /// Adds a genre to the item
  1511. /// </summary>
  1512. /// <param name="name">The name.</param>
  1513. /// <exception cref="System.ArgumentNullException"></exception>
  1514. public void AddGenre(string name)
  1515. {
  1516. if (string.IsNullOrWhiteSpace(name))
  1517. {
  1518. throw new ArgumentNullException("name");
  1519. }
  1520. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1521. {
  1522. Genres.Add(name);
  1523. }
  1524. }
  1525. /// <summary>
  1526. /// Marks the played.
  1527. /// </summary>
  1528. /// <param name="user">The user.</param>
  1529. /// <param name="datePlayed">The date played.</param>
  1530. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1531. /// <returns>Task.</returns>
  1532. /// <exception cref="System.ArgumentNullException"></exception>
  1533. public virtual void MarkPlayed(User user,
  1534. DateTime? datePlayed,
  1535. bool resetPosition)
  1536. {
  1537. if (user == null)
  1538. {
  1539. throw new ArgumentNullException();
  1540. }
  1541. var data = UserDataManager.GetUserData(user, this);
  1542. if (datePlayed.HasValue)
  1543. {
  1544. // Increment
  1545. data.PlayCount++;
  1546. }
  1547. // Ensure it's at least one
  1548. data.PlayCount = Math.Max(data.PlayCount, 1);
  1549. if (resetPosition)
  1550. {
  1551. data.PlaybackPositionTicks = 0;
  1552. }
  1553. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1554. data.Played = true;
  1555. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1556. }
  1557. /// <summary>
  1558. /// Marks the unplayed.
  1559. /// </summary>
  1560. /// <param name="user">The user.</param>
  1561. /// <returns>Task.</returns>
  1562. /// <exception cref="System.ArgumentNullException"></exception>
  1563. public virtual void MarkUnplayed(User user)
  1564. {
  1565. if (user == null)
  1566. {
  1567. throw new ArgumentNullException();
  1568. }
  1569. var data = UserDataManager.GetUserData(user, this);
  1570. //I think it is okay to do this here.
  1571. // if this is only called when a user is manually forcing something to un-played
  1572. // then it probably is what we want to do...
  1573. data.PlayCount = 0;
  1574. data.PlaybackPositionTicks = 0;
  1575. data.LastPlayedDate = null;
  1576. data.Played = false;
  1577. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1578. }
  1579. /// <summary>
  1580. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1581. /// </summary>
  1582. /// <returns>Task.</returns>
  1583. public virtual void ChangedExternally()
  1584. {
  1585. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem)
  1586. {
  1587. ValidateChildren = true,
  1588. }, RefreshPriority.High);
  1589. }
  1590. /// <summary>
  1591. /// Gets an image
  1592. /// </summary>
  1593. /// <param name="type">The type.</param>
  1594. /// <param name="imageIndex">Index of the image.</param>
  1595. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1596. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1597. public bool HasImage(ImageType type, int imageIndex)
  1598. {
  1599. return GetImageInfo(type, imageIndex) != null;
  1600. }
  1601. public void SetImage(ItemImageInfo image, int index)
  1602. {
  1603. if (image.Type == ImageType.Chapter)
  1604. {
  1605. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1606. }
  1607. var existingImage = GetImageInfo(image.Type, index);
  1608. if (existingImage != null)
  1609. {
  1610. existingImage.Path = image.Path;
  1611. existingImage.DateModified = image.DateModified;
  1612. }
  1613. else
  1614. {
  1615. var currentCount = ImageInfos.Length;
  1616. var newList = ImageInfos.ToArray(currentCount + 1);
  1617. newList[currentCount] = image;
  1618. ImageInfos = newList;
  1619. }
  1620. }
  1621. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1622. {
  1623. if (type == ImageType.Chapter)
  1624. {
  1625. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1626. }
  1627. var image = GetImageInfo(type, index);
  1628. if (image == null)
  1629. {
  1630. var currentCount = ImageInfos.Length;
  1631. var newList = ImageInfos.ToArray(currentCount + 1);
  1632. newList[currentCount] = GetImageInfo(file, type);
  1633. ImageInfos = newList;
  1634. }
  1635. else
  1636. {
  1637. var imageInfo = GetImageInfo(file, type);
  1638. image.Path = file.FullName;
  1639. image.DateModified = imageInfo.DateModified;
  1640. }
  1641. }
  1642. /// <summary>
  1643. /// Deletes the image.
  1644. /// </summary>
  1645. /// <param name="type">The type.</param>
  1646. /// <param name="index">The index.</param>
  1647. /// <returns>Task.</returns>
  1648. public void DeleteImage(ImageType type, int index)
  1649. {
  1650. var info = GetImageInfo(type, index);
  1651. if (info == null)
  1652. {
  1653. // Nothing to do
  1654. return;
  1655. }
  1656. // Remove it from the item
  1657. RemoveImage(info);
  1658. if (info.IsLocalFile)
  1659. {
  1660. FileSystem.DeleteFile(info.Path);
  1661. }
  1662. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1663. }
  1664. public void RemoveImage(ItemImageInfo image)
  1665. {
  1666. RemoveImages(new List<ItemImageInfo> { image });
  1667. }
  1668. public void RemoveImages(List<ItemImageInfo> deletedImages)
  1669. {
  1670. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1671. }
  1672. public virtual void UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1673. {
  1674. LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1675. }
  1676. /// <summary>
  1677. /// Validates that images within the item are still on the file system
  1678. /// </summary>
  1679. public bool ValidateImages(IDirectoryService directoryService)
  1680. {
  1681. var allFiles = ImageInfos
  1682. .Where(i => i.IsLocalFile)
  1683. .Select(i => FileSystem.GetDirectoryName(i.Path))
  1684. .Distinct(StringComparer.OrdinalIgnoreCase)
  1685. .SelectMany(i => FileSystem.GetFilePaths(i))
  1686. .ToList();
  1687. var deletedImages = ImageInfos
  1688. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1689. .ToList();
  1690. if (deletedImages.Count > 0)
  1691. {
  1692. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1693. }
  1694. return deletedImages.Count > 0;
  1695. }
  1696. /// <summary>
  1697. /// Gets the image path.
  1698. /// </summary>
  1699. /// <param name="imageType">Type of the image.</param>
  1700. /// <param name="imageIndex">Index of the image.</param>
  1701. /// <returns>System.String.</returns>
  1702. /// <exception cref="System.InvalidOperationException">
  1703. /// </exception>
  1704. /// <exception cref="System.ArgumentNullException">item</exception>
  1705. public string GetImagePath(ImageType imageType, int imageIndex)
  1706. {
  1707. var info = GetImageInfo(imageType, imageIndex);
  1708. return info == null ? null : info.Path;
  1709. }
  1710. /// <summary>
  1711. /// Gets the image information.
  1712. /// </summary>
  1713. /// <param name="imageType">Type of the image.</param>
  1714. /// <param name="imageIndex">Index of the image.</param>
  1715. /// <returns>ItemImageInfo.</returns>
  1716. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1717. {
  1718. if (imageType == ImageType.Chapter)
  1719. {
  1720. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1721. if (chapter == null)
  1722. {
  1723. return null;
  1724. }
  1725. var path = chapter.ImagePath;
  1726. if (string.IsNullOrWhiteSpace(path))
  1727. {
  1728. return null;
  1729. }
  1730. return new ItemImageInfo
  1731. {
  1732. Path = path,
  1733. DateModified = chapter.ImageDateModified,
  1734. Type = imageType
  1735. };
  1736. }
  1737. return GetImages(imageType)
  1738. .ElementAtOrDefault(imageIndex);
  1739. }
  1740. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1741. {
  1742. if (imageType == ImageType.Chapter)
  1743. {
  1744. throw new ArgumentException("No image info for chapter images");
  1745. }
  1746. return ImageInfos.Where(i => i.Type == imageType);
  1747. }
  1748. /// <summary>
  1749. /// Adds the images.
  1750. /// </summary>
  1751. /// <param name="imageType">Type of the image.</param>
  1752. /// <param name="images">The images.</param>
  1753. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1754. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1755. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1756. {
  1757. if (imageType == ImageType.Chapter)
  1758. {
  1759. throw new ArgumentException("Cannot call AddImages with chapter images");
  1760. }
  1761. var existingImages = GetImages(imageType)
  1762. .ToList();
  1763. var newImageList = new List<FileSystemMetadata>();
  1764. var imageAdded = false;
  1765. foreach (var newImage in images)
  1766. {
  1767. if (newImage == null)
  1768. {
  1769. throw new ArgumentException("null image found in list");
  1770. }
  1771. var existing = existingImages
  1772. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1773. if (existing == null)
  1774. {
  1775. newImageList.Add(newImage);
  1776. imageAdded = true;
  1777. }
  1778. else
  1779. {
  1780. if (existing.IsLocalFile)
  1781. {
  1782. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1783. }
  1784. }
  1785. }
  1786. if (imageAdded || images.Count != existingImages.Count)
  1787. {
  1788. var newImagePaths = images.Select(i => i.FullName).ToList();
  1789. var deleted = existingImages
  1790. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1791. .ToList();
  1792. if (deleted.Count > 0)
  1793. {
  1794. ImageInfos = ImageInfos.Except(deleted).ToArray();
  1795. }
  1796. }
  1797. if (newImageList.Count > 0)
  1798. {
  1799. var currentCount = ImageInfos.Length;
  1800. var newList = ImageInfos.ToArray(currentCount + newImageList.Count);
  1801. foreach (var image in newImageList)
  1802. {
  1803. newList[currentCount] = GetImageInfo(image, imageType);
  1804. currentCount++;
  1805. }
  1806. ImageInfos = newList;
  1807. }
  1808. return newImageList.Count > 0;
  1809. }
  1810. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1811. {
  1812. return new ItemImageInfo
  1813. {
  1814. Path = file.FullName,
  1815. Type = type,
  1816. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1817. };
  1818. }
  1819. /// <summary>
  1820. /// Gets the file system path to delete when the item is to be deleted
  1821. /// </summary>
  1822. /// <returns></returns>
  1823. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  1824. {
  1825. return new[] {
  1826. new FileSystemMetadata
  1827. {
  1828. FullName = Path,
  1829. IsDirectory = IsFolder
  1830. }
  1831. }.Concat(GetLocalMetadataFilesToDelete());
  1832. }
  1833. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  1834. {
  1835. if (IsFolder || !IsInMixedFolder)
  1836. {
  1837. return new List<FileSystemMetadata>();
  1838. }
  1839. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  1840. var extensions = new List<string> { ".nfo", ".xml", ".srt" };
  1841. extensions.AddRange(SupportedImageExtensions);
  1842. return FileSystem.GetFiles(FileSystem.GetDirectoryName(Path), extensions.ToArray(extensions.Count), false, false)
  1843. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  1844. .ToList();
  1845. }
  1846. public bool AllowsMultipleImages(ImageType type)
  1847. {
  1848. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1849. }
  1850. public void SwapImages(ImageType type, int index1, int index2)
  1851. {
  1852. if (!AllowsMultipleImages(type))
  1853. {
  1854. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1855. }
  1856. var info1 = GetImageInfo(type, index1);
  1857. var info2 = GetImageInfo(type, index2);
  1858. if (info1 == null || info2 == null)
  1859. {
  1860. // Nothing to do
  1861. return;
  1862. }
  1863. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1864. {
  1865. // TODO: Not supported yet
  1866. return;
  1867. }
  1868. var path1 = info1.Path;
  1869. var path2 = info2.Path;
  1870. FileSystem.SwapFiles(path1, path2);
  1871. // Refresh these values
  1872. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1873. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1874. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1875. }
  1876. public virtual bool IsPlayed(User user)
  1877. {
  1878. var userdata = UserDataManager.GetUserData(user, this);
  1879. return userdata != null && userdata.Played;
  1880. }
  1881. public bool IsFavoriteOrLiked(User user)
  1882. {
  1883. var userdata = UserDataManager.GetUserData(user, this);
  1884. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1885. }
  1886. public virtual bool IsUnplayed(User user)
  1887. {
  1888. if (user == null)
  1889. {
  1890. throw new ArgumentNullException("user");
  1891. }
  1892. var userdata = UserDataManager.GetUserData(user, this);
  1893. return userdata == null || !userdata.Played;
  1894. }
  1895. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1896. {
  1897. return GetItemLookupInfo<ItemLookupInfo>();
  1898. }
  1899. protected T GetItemLookupInfo<T>()
  1900. where T : ItemLookupInfo, new()
  1901. {
  1902. return new T
  1903. {
  1904. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1905. MetadataLanguage = GetPreferredMetadataLanguage(),
  1906. Name = GetNameForMetadataLookup(),
  1907. ProviderIds = ProviderIds,
  1908. IndexNumber = IndexNumber,
  1909. ParentIndexNumber = ParentIndexNumber,
  1910. Year = ProductionYear,
  1911. PremiereDate = PremiereDate
  1912. };
  1913. }
  1914. protected virtual string GetNameForMetadataLookup()
  1915. {
  1916. return Name;
  1917. }
  1918. /// <summary>
  1919. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1920. /// </summary>
  1921. public virtual bool BeforeMetadataRefresh()
  1922. {
  1923. _sortName = null;
  1924. var hasChanges = false;
  1925. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1926. {
  1927. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1928. hasChanges = true;
  1929. }
  1930. return hasChanges;
  1931. }
  1932. protected static string GetMappedPath(BaseItem item, string path, LocationType locationType)
  1933. {
  1934. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1935. {
  1936. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  1937. }
  1938. return path;
  1939. }
  1940. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, ItemFields[] fields)
  1941. {
  1942. if (RunTimeTicks.HasValue)
  1943. {
  1944. double pct = RunTimeTicks.Value;
  1945. if (pct > 0)
  1946. {
  1947. pct = userData.PlaybackPositionTicks / pct;
  1948. if (pct > 0)
  1949. {
  1950. dto.PlayedPercentage = 100 * pct;
  1951. }
  1952. }
  1953. }
  1954. }
  1955. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  1956. {
  1957. var newOptions = new MetadataRefreshOptions(options);
  1958. newOptions.SearchResult = null;
  1959. var item = this;
  1960. if (copyTitleMetadata)
  1961. {
  1962. // Take some data from the main item, for querying purposes
  1963. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  1964. {
  1965. newOptions.ForceSave = true;
  1966. ownedItem.Genres = item.Genres.ToList();
  1967. }
  1968. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  1969. {
  1970. newOptions.ForceSave = true;
  1971. ownedItem.Studios = item.Studios;
  1972. }
  1973. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  1974. {
  1975. newOptions.ForceSave = true;
  1976. ownedItem.ProductionLocations = item.ProductionLocations;
  1977. }
  1978. if (item.CommunityRating != ownedItem.CommunityRating)
  1979. {
  1980. ownedItem.CommunityRating = item.CommunityRating;
  1981. newOptions.ForceSave = true;
  1982. }
  1983. if (item.CriticRating != ownedItem.CriticRating)
  1984. {
  1985. ownedItem.CriticRating = item.CriticRating;
  1986. newOptions.ForceSave = true;
  1987. }
  1988. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  1989. {
  1990. ownedItem.Overview = item.Overview;
  1991. newOptions.ForceSave = true;
  1992. }
  1993. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  1994. {
  1995. ownedItem.OfficialRating = item.OfficialRating;
  1996. newOptions.ForceSave = true;
  1997. }
  1998. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  1999. {
  2000. ownedItem.CustomRating = item.CustomRating;
  2001. newOptions.ForceSave = true;
  2002. }
  2003. }
  2004. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2005. }
  2006. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2007. {
  2008. var newOptions = new MetadataRefreshOptions(options);
  2009. newOptions.SearchResult = null;
  2010. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2011. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2012. var video = LibraryManager.GetItemById(id) as Video;
  2013. if (video == null)
  2014. {
  2015. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2016. newOptions.ForceSave = true;
  2017. }
  2018. //var parentId = Id;
  2019. //if (!video.IsOwnedItem || video.ParentId != parentId)
  2020. //{
  2021. // video.IsOwnedItem = true;
  2022. // video.ParentId = parentId;
  2023. // newOptions.ForceSave = true;
  2024. //}
  2025. if (video == null)
  2026. {
  2027. return Task.FromResult(true);
  2028. }
  2029. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2030. }
  2031. public string GetEtag(User user)
  2032. {
  2033. var list = GetEtagValues(user);
  2034. return string.Join("|", list.ToArray(list.Count)).GetMD5().ToString("N");
  2035. }
  2036. protected virtual List<string> GetEtagValues(User user)
  2037. {
  2038. return new List<string>
  2039. {
  2040. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2041. };
  2042. }
  2043. public virtual IEnumerable<Guid> GetAncestorIds()
  2044. {
  2045. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2046. }
  2047. public BaseItem GetTopParent()
  2048. {
  2049. if (IsTopParent)
  2050. {
  2051. return this;
  2052. }
  2053. foreach (var parent in GetParents())
  2054. {
  2055. if (parent.IsTopParent)
  2056. {
  2057. return parent;
  2058. }
  2059. }
  2060. return null;
  2061. }
  2062. [IgnoreDataMember]
  2063. public virtual bool IsTopParent
  2064. {
  2065. get
  2066. {
  2067. if (this is BasePluginFolder || this is Channel)
  2068. {
  2069. return true;
  2070. }
  2071. var view = this as UserView;
  2072. if (view != null)
  2073. {
  2074. if (string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2075. {
  2076. return true;
  2077. }
  2078. if (string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  2079. {
  2080. return true;
  2081. }
  2082. }
  2083. if (GetParent() is AggregateFolder)
  2084. {
  2085. return true;
  2086. }
  2087. return false;
  2088. }
  2089. }
  2090. [IgnoreDataMember]
  2091. public virtual bool SupportsAncestors
  2092. {
  2093. get
  2094. {
  2095. return true;
  2096. }
  2097. }
  2098. [IgnoreDataMember]
  2099. public virtual bool StopRefreshIfLocalMetadataFound
  2100. {
  2101. get
  2102. {
  2103. return true;
  2104. }
  2105. }
  2106. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2107. {
  2108. return new[] { Id };
  2109. }
  2110. public virtual Task Delete(DeleteOptions options)
  2111. {
  2112. return LibraryManager.DeleteItem(this, options);
  2113. }
  2114. public virtual List<ExternalUrl> GetRelatedUrls()
  2115. {
  2116. return new List<ExternalUrl>();
  2117. }
  2118. public virtual double? GetRefreshProgress()
  2119. {
  2120. return null;
  2121. }
  2122. public virtual ItemUpdateType OnMetadataChanged()
  2123. {
  2124. var updateType = ItemUpdateType.None;
  2125. var item = this;
  2126. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2127. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2128. {
  2129. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2130. updateType |= ItemUpdateType.MetadataImport;
  2131. }
  2132. return updateType;
  2133. }
  2134. }
  2135. }