BaseItem.cs 77 KB

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