Remove the old TVDB importer, and get add the remaining missing features to the new one.
This commit is contained in:
1 parent
671bd836d0
commit
0165cc6f56
9 files changed
+181
-921
No files matched your search
@@ -12,7 +12,6 @@
|
||||
|
||||
#import "SBiTunesStore.h"
|
||||
#import "SBTheMovieDB3.h"
|
||||
#import "SBTheTVDB.h"
|
||||
#import "Subler-Swift.h"
|
||||
|
||||
@interface SBMetadataImporter ()
|
||||
@@ -146,8 +145,8 @@
|
||||
userInfo:nil];
|
||||
}
|
||||
|
||||
- (NSArray<SBMetadataResult *> *)searchTVSeries:(NSString *)aSeriesName language:(NSString *)aLanguage {
|
||||
SBTheTVDB *searcher = [[SBTheTVDB alloc] init];
|
||||
- (NSArray<NSString *> *)searchTVSeries:(NSString *)aSeriesName language:(NSString *)aLanguage {
|
||||
TheTVDB *searcher = [[TheTVDB alloc] init];
|
||||
NSArray *a = [searcher searchTVSeries:aSeriesName language:[[NSUserDefaults standardUserDefaults] valueForKey:@"SBMetadataPreference|TV|TheTVDB|Language"]];
|
||||
return a;
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// TheTVDB.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Douglas Stebila on 2013-06-06.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SBMetadataImporter.h"
|
||||
|
||||
@interface SBTheTVDB : SBMetadataImporter
|
||||
@end
|
||||
@@ -1,507 +0,0 @@
|
||||
//
|
||||
// TheTVDB.m
|
||||
// Subler
|
||||
//
|
||||
// Created by Douglas Stebila on 2013-06-06.
|
||||
//
|
||||
//
|
||||
|
||||
#import <MP42Foundation/MP42Ratings.h>
|
||||
#import <MP42Foundation/MP42Languages.h>
|
||||
|
||||
#import "SBTheTVDB.h"
|
||||
#import "SBTheTVDBConnection.h"
|
||||
|
||||
#import "SBiTunesStore.h"
|
||||
|
||||
@implementation SBTheTVDB
|
||||
|
||||
#pragma mark - Public methods
|
||||
|
||||
- (NSArray<NSString *> *)languages
|
||||
{
|
||||
return SBTheTVDBConnection.defaultManager.languagues;
|
||||
}
|
||||
|
||||
- (SBMetadataImporterLanguageType)languageType
|
||||
{
|
||||
return SBMetadataImporterLanguageTypeISO;
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)searchTVSeries:(NSString *)seriesName language:(NSString *)language
|
||||
{
|
||||
NSMutableSet *results = [NSMutableSet set];
|
||||
|
||||
language = [MP42Languages.defaultManager extendedTagForLocalizedLang:language];
|
||||
|
||||
// search for series
|
||||
NSArray<NSDictionary *> *series = [SBTheTVDBConnection.defaultManager fetchSeries:[SBMetadataHelper urlEncoded:seriesName] language:language];
|
||||
|
||||
for (NSDictionary *s in series) {
|
||||
[results addObject:s[@"seriesName"]];
|
||||
}
|
||||
|
||||
// Fall back to english
|
||||
if (![language isEqualToString:@"en"]) {
|
||||
[results addObjectsFromArray:[self searchTVSeries:seriesName language:@"en"]];
|
||||
}
|
||||
|
||||
return results.allObjects;
|
||||
}
|
||||
|
||||
- (NSArray<SBMetadataResult *> *)searchTVSeries:(NSString *)seriesName language:(NSString *)language seasonNum:(NSString *)seasonNum episodeNum:(NSString *)episodeNum
|
||||
{
|
||||
if (!language) { language = @"en"; }
|
||||
|
||||
// search for series id
|
||||
NSSet<NSNumber *> *seriesIDs = [self searchSeriesID:seriesName language:language];
|
||||
|
||||
// fallback to English if no results are found
|
||||
if (!seriesIDs.count) {
|
||||
seriesIDs = [self searchSeriesID:seriesName language:@"en"];
|
||||
}
|
||||
|
||||
NSMutableArray<SBMetadataResult *> *results = [[NSMutableArray alloc] init];
|
||||
|
||||
for (NSDictionary *s in seriesIDs) {
|
||||
|
||||
NSNumber *seriesID = s[@"id"];
|
||||
|
||||
if (!seriesID || ![seriesID isKindOfClass:[NSNumber class]]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Series info
|
||||
NSDictionary *seriesInfo = [SBTheTVDBConnection.defaultManager fetchSeriesInfo:seriesID language:language];
|
||||
if (seriesInfo == nil) { continue; }
|
||||
|
||||
// Series actors
|
||||
NSArray<NSDictionary *> *seriesActors = [SBTheTVDBConnection.defaultManager fetchSeriesActors:seriesID language:language];
|
||||
|
||||
// Series episodes info
|
||||
NSArray<SBMetadataResult *> *localizedResults = [self loadTVEpisodes:seriesInfo actors:seriesActors
|
||||
seasonNum:seasonNum episodeNum:episodeNum language:language];
|
||||
|
||||
// Check for null values, it might happens if there isn't a localized version
|
||||
SBTheTVDBNullValues nullValues = [self checkForNull:localizedResults];
|
||||
|
||||
localizedResults = [localizedResults sortedArrayUsingFunction:sortSBMetadataResult context:NULL];
|
||||
|
||||
if (nullValues && ![language isEqualToString:@"en"]) {
|
||||
if (nullValues & SBTheTVDBNullValuesEpisodes) {
|
||||
NSArray<SBMetadataResult *> *englishResults = [self loadTVEpisodes:seriesInfo actors:seriesActors
|
||||
seasonNum:seasonNum episodeNum:episodeNum language:@"en"];
|
||||
|
||||
if (englishResults.count) {
|
||||
englishResults = [englishResults sortedArrayUsingFunction:sortSBMetadataResult context:NULL];
|
||||
[self merge:localizedResults with:englishResults];
|
||||
}
|
||||
}
|
||||
|
||||
if (nullValues & SBTheTVDBNullValuesSeries) {
|
||||
NSDictionary *englishSeriesInfo = [SBTheTVDBConnection.defaultManager fetchSeriesInfo:seriesID language:@"en"];
|
||||
|
||||
if (englishSeriesInfo) {
|
||||
[self merge:localizedResults withSeries:englishSeriesInfo];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[self removeNullValues:localizedResults];
|
||||
|
||||
[results addObjectsFromArray:localizedResults];
|
||||
}
|
||||
|
||||
return [results sortedArrayUsingFunction:sortSBMetadataResult context:NULL];
|
||||
}
|
||||
|
||||
#pragma mark - Sort
|
||||
|
||||
static NSInteger sortSBMetadataResult(SBMetadataResult *ep1, SBMetadataResult *ep2, void *context)
|
||||
{
|
||||
int v1 = [ep1[SBMetadataResultEpisodeNumber] intValue];
|
||||
int v2 = [ep2[SBMetadataResultEpisodeNumber] intValue];
|
||||
|
||||
int s1 = [ep1[SBMetadataResultSeason] intValue];
|
||||
int s2 = [ep2[SBMetadataResultSeason] intValue];
|
||||
|
||||
if (s1 == s2) {
|
||||
if (v1 < v2)
|
||||
return NSOrderedAscending;
|
||||
else if (v1 > v2)
|
||||
return NSOrderedDescending;
|
||||
}
|
||||
|
||||
if (s1 < s2)
|
||||
return NSOrderedAscending;
|
||||
else if (s1 > s2)
|
||||
return NSOrderedDescending;
|
||||
else
|
||||
return NSOrderedSame;
|
||||
}
|
||||
|
||||
#pragma mark - Series ID
|
||||
|
||||
- (BOOL)seriesResult:(NSDictionary *)s matchName:(NSString *)seriesName
|
||||
{
|
||||
NSString *resultName = s[@"seriesName"];
|
||||
|
||||
if (![resultName isKindOfClass:[NSString class]]) { return NO; }
|
||||
|
||||
if ([seriesName isEqualTo:s[@"seriesName"]]) {
|
||||
return YES;
|
||||
}
|
||||
else {
|
||||
NSArray<NSString *> *aliases = s[@"aliases"];
|
||||
|
||||
if ([aliases isKindOfClass:[NSArray class]]) {
|
||||
for (NSString *alias in aliases) {
|
||||
if ([alias isKindOfClass:[NSString class]] && [seriesName isEqualTo:alias]) {
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (NSSet<NSNumber *> *)searchSeriesID:(NSString *)seriesName language:(NSString *)language
|
||||
{
|
||||
NSMutableSet<NSDictionary *> *selectedSeries = [[NSMutableSet alloc] init];
|
||||
|
||||
// search for series id
|
||||
NSArray<NSDictionary *> *series = [SBTheTVDBConnection.defaultManager fetchSeries:[SBMetadataHelper urlEncoded:seriesName] language:language];
|
||||
|
||||
for (NSDictionary *s in series) {
|
||||
if ([self seriesResult:s matchName:seriesName]) {
|
||||
[selectedSeries addObject:s];
|
||||
}
|
||||
}
|
||||
|
||||
if (!selectedSeries.count && series.count) {
|
||||
[selectedSeries addObject:series.firstObject];
|
||||
}
|
||||
|
||||
return [selectedSeries copy];
|
||||
}
|
||||
|
||||
#pragma mark - Null values check
|
||||
|
||||
typedef NS_OPTIONS(NSUInteger, SBTheTVDBNullValues) {
|
||||
SBTheTVDBNullValuesEpisodes = 1 << 0,
|
||||
SBTheTVDBNullValuesSeries = 1 << 1,
|
||||
};
|
||||
|
||||
- (SBTheTVDBNullValues)checkForNull:(NSArray<SBMetadataResult *> *)results
|
||||
{
|
||||
NSNull *null = [NSNull null];
|
||||
SBTheTVDBNullValues nullValues = 0;
|
||||
|
||||
for (SBMetadataResult *result in results) {
|
||||
if ([result[SBMetadataResultSeriesName] isEqualTo:null]) {
|
||||
nullValues |= SBTheTVDBNullValuesSeries;
|
||||
}
|
||||
if ([result[SBMetadataResultName] isEqualTo:null]) {
|
||||
nullValues |= SBTheTVDBNullValuesEpisodes;
|
||||
}
|
||||
if ([result[SBMetadataResultLongDescription] isEqualTo:null]) {
|
||||
nullValues |= SBTheTVDBNullValuesEpisodes;
|
||||
}
|
||||
if ([result[SBMetadataResultSeriesDescription] isEqualTo:null]) {
|
||||
nullValues |= SBTheTVDBNullValuesSeries;
|
||||
}
|
||||
|
||||
if (nullValues & SBTheTVDBNullValuesEpisodes &&
|
||||
nullValues & SBTheTVDBNullValuesSeries) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return nullValues;
|
||||
}
|
||||
|
||||
- (void)removeNullValues:(NSArray<SBMetadataResult *> *)results
|
||||
{
|
||||
NSNull *null = [NSNull null];
|
||||
|
||||
for (SBMetadataResult *result in results) {
|
||||
if ([result[SBMetadataResultSeriesName] isEqualTo:null]) {
|
||||
result[SBMetadataResultSeriesName] = nil;
|
||||
}
|
||||
if ([result[SBMetadataResultName] isEqualTo:null]) {
|
||||
result[SBMetadataResultName] = nil;
|
||||
}
|
||||
if ([result[SBMetadataResultLongDescription] isEqualTo:null]) {
|
||||
result[SBMetadataResultLongDescription] = nil;
|
||||
}
|
||||
if ([result[SBMetadataResultDescription] isEqualTo:null]) {
|
||||
result[SBMetadataResultDescription] = nil;
|
||||
}
|
||||
if ([result[SBMetadataResultSeriesDescription] isEqualTo:null]) {
|
||||
result[SBMetadataResultSeriesDescription] = nil;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)merge:(NSArray<SBMetadataResult *> *)array with:(NSArray<SBMetadataResult *> *)array2
|
||||
{
|
||||
NSNull *null = [NSNull null];
|
||||
|
||||
if (array2.count != array.count) {
|
||||
return;
|
||||
}
|
||||
|
||||
NSUInteger index = 0;
|
||||
for (SBMetadataResult *target in array) {
|
||||
SBMetadataResult *source = array2[index];
|
||||
|
||||
if ([target[SBMetadataResultSeriesName] isEqualTo:null]) {
|
||||
target[SBMetadataResultSeriesName] = source[SBMetadataResultSeriesName];
|
||||
}
|
||||
if ([target[SBMetadataResultName] isEqualTo:null]) {
|
||||
target[SBMetadataResultName] = source[SBMetadataResultName];
|
||||
}
|
||||
if ([target[SBMetadataResultLongDescription] isEqualTo:null]) {
|
||||
target[SBMetadataResultLongDescription] = source[SBMetadataResultLongDescription];
|
||||
target[SBMetadataResultDescription] = source[SBMetadataResultDescription];
|
||||
}
|
||||
if ([target[SBMetadataResultSeriesDescription] isEqualTo:null]) {
|
||||
target[SBMetadataResultSeriesDescription] = source[SBMetadataResultSeriesDescription];
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
- (void)merge:(NSArray<SBMetadataResult *> *)array withSeries:(NSDictionary *)series
|
||||
{
|
||||
NSNull *null = [NSNull null];
|
||||
NSString *name = series[@"seriesName"];
|
||||
NSString *overview = series[@"overview"];
|
||||
|
||||
for (SBMetadataResult *target in array) {
|
||||
if ([target[SBMetadataResultSeriesName] isEqualTo:null]) {
|
||||
target[SBMetadataResultSeriesName] = name;
|
||||
}
|
||||
if ([target[SBMetadataResultSeriesDescription] isEqualTo:null]) {
|
||||
target[SBMetadataResultSeriesDescription] = overview;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Helpers
|
||||
|
||||
+ (nullable NSString *)cleanList:(nullable NSArray<NSString *> *)s
|
||||
{
|
||||
NSMutableString *result = [NSMutableString string];
|
||||
|
||||
if (s) {
|
||||
for (NSString *component in s) {
|
||||
if ([component isKindOfClass:[NSString class]]) {
|
||||
if (result.length) {
|
||||
[result appendString:@", "];
|
||||
}
|
||||
[result appendString:component];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result.length ? result : nil;
|
||||
}
|
||||
|
||||
+ (nullable NSString *)cleanActorsList:(nullable NSArray<NSDictionary *> *)s
|
||||
{
|
||||
NSMutableString *result = [NSMutableString string];
|
||||
|
||||
if (s) {
|
||||
for (NSDictionary *component in s) {
|
||||
if ([component isKindOfClass:[NSDictionary class]]) {
|
||||
NSString *nameComponent = component[@"name"];
|
||||
if ([nameComponent isKindOfClass:[NSString class]]) {
|
||||
if (result.length) {
|
||||
[result appendString:@", "];
|
||||
}
|
||||
[result appendString:component[@"name"]];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result.length ? result : nil;
|
||||
}
|
||||
|
||||
#pragma mark - Episodes
|
||||
|
||||
- (void)loadITunesArtwork:(SBMetadataResult *)metadata
|
||||
{
|
||||
NSMutableArray<SBRemoteImage *> *remoteArtworks = metadata.remoteArtworks.mutableCopy;
|
||||
|
||||
SBMetadataResult *iTunesMetadata = [SBiTunesStore quickiTunesSearchTV:metadata[SBMetadataResultSeriesName] episodeTitle:metadata[SBMetadataResultName]];
|
||||
|
||||
if (iTunesMetadata && iTunesMetadata.remoteArtworks.count) {
|
||||
[remoteArtworks addObjectsFromArray:iTunesMetadata.remoteArtworks];
|
||||
}
|
||||
|
||||
metadata.remoteArtworks = remoteArtworks;
|
||||
}
|
||||
|
||||
- (void)loadTVImages:(SBMetadataResult *)metadata type:(NSString *)type language:(NSString *)language
|
||||
{
|
||||
NSMutableArray<SBRemoteImage *> *remoteArtworks = metadata.remoteArtworks.mutableCopy;
|
||||
|
||||
// get additionals images
|
||||
NSArray *images = [SBTheTVDBConnection.defaultManager fetchSeriesImages:metadata[@"TheTVDB Series ID"] type:type language:language];
|
||||
|
||||
if (images.count == 0) {
|
||||
images = [SBTheTVDBConnection.defaultManager fetchSeriesImages:metadata[@"TheTVDB Series ID"] type:type language:@"en"];
|
||||
}
|
||||
|
||||
if (images && [images isKindOfClass:[NSArray class]]) {
|
||||
|
||||
for (NSDictionary *image in images) {
|
||||
NSURL *fileURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://thetvdb.com/banners/%@", image[@"fileName"]]];
|
||||
NSURL *thumbURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://thetvdb.com/banners/%@", image[@"thumbnail"]]];
|
||||
|
||||
BOOL toBeAdded = YES;
|
||||
|
||||
if ([type isEqualToString:@"season"]) {
|
||||
NSString *subKey = image[@"subKey"];
|
||||
NSString *season = [metadata[SBMetadataResultSeason] stringValue];
|
||||
if (subKey && [subKey isKindOfClass:[NSString class]] && ![subKey isEqualToString:season]) {
|
||||
toBeAdded = NO;
|
||||
}
|
||||
}
|
||||
if (toBeAdded) {
|
||||
SBRemoteImage *artwork = [SBRemoteImage remoteImageWithURL:fileURL
|
||||
thumbURL:thumbURL
|
||||
providerName:[NSString stringWithFormat:@"TheTVDB|%@", type]];
|
||||
[remoteArtworks addObject:artwork];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
metadata.remoteArtworks = remoteArtworks;
|
||||
}
|
||||
|
||||
- (SBMetadataResult *)loadTVMetadata:(SBMetadataResult *)metadata language:(NSString *)language
|
||||
{
|
||||
// Get additional episodes info
|
||||
NSNumber *episodesID = metadata[@"TheTVDB Episodes ID"];
|
||||
NSDictionary *episodesInfo = [SBTheTVDBConnection.defaultManager fetchEpisodesInfo:episodesID language:language];
|
||||
SBRemoteImage *artwork = nil;
|
||||
|
||||
if (episodesInfo) {
|
||||
metadata[SBMetadataResultDirector] = [SBTheTVDB cleanList:episodesInfo[@"directors"]];
|
||||
metadata[SBMetadataResultScreenwriters] = [SBTheTVDB cleanList:episodesInfo[@"writers"]];
|
||||
|
||||
NSString *actors = metadata[SBMetadataResultCast];
|
||||
NSString *gueststars = [SBTheTVDB cleanList:episodesInfo[@"guestStars"]];
|
||||
|
||||
if (actors.length && gueststars.length) {
|
||||
metadata[SBMetadataResultCast] = [NSString stringWithFormat:@"%@, %@", actors, gueststars];
|
||||
}
|
||||
else if (gueststars.length) {
|
||||
metadata[SBMetadataResultCast] = gueststars;
|
||||
}
|
||||
|
||||
// Episodes artwork
|
||||
NSString *artworkFilename = episodesInfo[@"filename"];
|
||||
if (artworkFilename && [artworkFilename isKindOfClass:[NSString class]] && artworkFilename.length) {
|
||||
NSURL *artworkURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://thetvdb.com/banners/%@", artworkFilename]];
|
||||
|
||||
artwork = [SBRemoteImage remoteImageWithURL:artworkURL
|
||||
thumbURL:artworkURL
|
||||
providerName:@"TheTVDB|episode"];
|
||||
}
|
||||
}
|
||||
|
||||
// get additionals images
|
||||
[self loadITunesArtwork:metadata];
|
||||
if (artwork) {
|
||||
NSMutableArray<SBRemoteImage *> *remoteArtworks = metadata.remoteArtworks.mutableCopy;
|
||||
[remoteArtworks addObject:artwork];
|
||||
metadata.remoteArtworks = remoteArtworks;
|
||||
}
|
||||
[self loadTVImages:metadata type:@"season" language:language];
|
||||
[self loadTVImages:metadata type:@"poster" language:language];
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
+ (SBMetadataResult *)metadataForEpisode:(NSDictionary *)episode series:(NSDictionary *)series actors:(NSArray *)actors
|
||||
{
|
||||
SBMetadataResult *metadata = [[SBMetadataResult alloc] init];
|
||||
|
||||
metadata.mediaKind = 10; // TV show
|
||||
|
||||
// TV Show
|
||||
metadata[@"TheTVDB Series ID"] = series[@"id"];
|
||||
metadata[SBMetadataResultSeriesName] = series[@"seriesName"];
|
||||
metadata[SBMetadataResultSeriesDescription] = series[@"overview"];
|
||||
metadata[SBMetadataResultGenre] = [SBTheTVDB cleanList:series[@"genre"]];
|
||||
|
||||
// Episode
|
||||
metadata[@"TheTVDB Episodes ID"] = episode[@"id"];
|
||||
metadata[SBMetadataResultName] = episode[@"episodeName"];
|
||||
metadata[SBMetadataResultReleaseDate] = episode[@"firstAired"];
|
||||
metadata[SBMetadataResultDescription] = episode[@"overview"];
|
||||
metadata[SBMetadataResultLongDescription] = episode[@"overview"];
|
||||
|
||||
NSString *ratingString = series[@"rating"];
|
||||
if (ratingString.length) {
|
||||
metadata[SBMetadataResultRating] = [[MP42Ratings defaultManager] ratingStringForiTunesCountry:@"USA"
|
||||
media:@"TV"
|
||||
ratingString:ratingString];
|
||||
}
|
||||
|
||||
metadata[SBMetadataResultNetwork] = series[@"network"];
|
||||
metadata[SBMetadataResultSeason] = episode[@"airedSeason"];
|
||||
|
||||
NSString *episodeID = [NSString stringWithFormat:@"%d%02d",
|
||||
[episode[@"airedSeason"] intValue],
|
||||
[episode[@"airedEpisodeNumber"] intValue]];
|
||||
|
||||
metadata[SBMetadataResultEpisodeID] = episodeID;
|
||||
metadata[SBMetadataResultEpisodeNumber] = episode[@"airedEpisodeNumber"];
|
||||
metadata[SBMetadataResultTrackNumber] = episode[@"airedEpisodeNumber"];
|
||||
|
||||
// Actors
|
||||
metadata[SBMetadataResultCast] = [SBTheTVDB cleanActorsList:actors];
|
||||
|
||||
// TheTVDB does not provide the following fields normally associated with TV shows in SBMetadataResult:
|
||||
// "Copyright", "Comments", "Producers", "Artist"
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
- (NSArray<SBMetadataResult *> *)loadTVEpisodes:(NSDictionary *)seriesInfo actors:(NSArray *)actors seasonNum:(NSString *)seasonNum episodeNum:(NSString *)episodeNum language:(NSString *)language
|
||||
{
|
||||
NSMutableArray *results = [[NSMutableArray alloc] init];
|
||||
NSNumber *seriesID = seriesInfo[@"id"];
|
||||
|
||||
NSArray<NSDictionary *> *episodes = [SBTheTVDBConnection.defaultManager fetchEpisodes:seriesID season:seasonNum number:episodeNum language:language];
|
||||
|
||||
for (NSDictionary *episode in episodes) {
|
||||
if (seasonNum && seasonNum.length) {
|
||||
NSString *episodeSeason = [episode[@"airedSeason"] stringValue];
|
||||
if ([episodeSeason isEqualToString:seasonNum]) {
|
||||
if (episodeNum && episodeNum.length) {
|
||||
NSString *episodeNumber = [episode[@"airedEpisodeNumber"] stringValue];
|
||||
if ([episodeNumber isEqualToString:episodeNum]) {
|
||||
[results addObject:[SBTheTVDB metadataForEpisode:episode series:seriesInfo actors:actors]];
|
||||
}
|
||||
} else {
|
||||
[results addObject:[SBTheTVDB metadataForEpisode:episode series:seriesInfo actors:actors]];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
[results addObject:[SBTheTVDB metadataForEpisode:episode series:seriesInfo actors:actors]];
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,30 +0,0 @@
|
||||
//
|
||||
// SBTheTVDBConnection.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 24/05/17.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SBTheTVDBConnection : NSObject
|
||||
|
||||
@property (class, readonly) SBTheTVDBConnection *defaultManager;
|
||||
|
||||
@property (nonatomic, readonly) NSArray<NSString *> *languagues;
|
||||
|
||||
- (NSArray<NSDictionary *> *)fetchSeries:(NSString *)seriesName language:(NSString *)language;
|
||||
- (nullable NSDictionary *)fetchSeriesInfo:(NSNumber *)seriesID language:(NSString *)language;
|
||||
- (NSArray<NSDictionary *> *)fetchSeriesActors:(NSNumber *)seriesID language:(NSString *)language;
|
||||
- (NSArray<NSDictionary *> *)fetchSeriesImages:(NSNumber *)seriesID type:(NSString *)type language:(NSString *)language;
|
||||
|
||||
- (NSArray<NSDictionary *> *)fetchEpisodes:(NSNumber *)seriesID season:(NSString *)season number:(NSString *)number language:(NSString *)language;
|
||||
- (nullable NSDictionary *)fetchEpisodesInfo:(NSNumber *)episodeID language:(NSString *)language;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
@@ -1,309 +0,0 @@
|
||||
//
|
||||
// SBTheTVDBConnection.m
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 24/05/17.
|
||||
//
|
||||
//
|
||||
|
||||
#import "SBTheTVDBConnection.h"
|
||||
|
||||
#import <MP42Foundation/MP42Ratings.h>
|
||||
#import <MP42Foundation/MP42Languages.h>
|
||||
|
||||
#import "SBMetadataHelper.h"
|
||||
|
||||
#define API_KEY @"3498815BE9484A62"
|
||||
|
||||
@interface SBTheTVDBConnection ()
|
||||
|
||||
@property (nonatomic, readwrite, nullable) NSString *token;
|
||||
@property (nonatomic, readwrite) NSTimeInterval tokenTimestamp;
|
||||
|
||||
@property (nonatomic, readwrite) NSArray<NSString *> *languagues;
|
||||
@property (nonatomic, readwrite) NSTimeInterval languagesTimestamp;
|
||||
|
||||
@property (nonatomic, readonly) dispatch_queue_t queue;
|
||||
@property (nonatomic, readonly) dispatch_queue_t tokenQueue;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SBTheTVDBConnection
|
||||
|
||||
+ (instancetype)defaultManager
|
||||
{
|
||||
static dispatch_once_t pred;
|
||||
static SBTheTVDBConnection *shared = nil;
|
||||
|
||||
dispatch_once(&pred, ^{
|
||||
shared = [[SBTheTVDBConnection alloc] init];
|
||||
});
|
||||
return shared;
|
||||
}
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_queue = dispatch_queue_create("org.subler.TheTVDBQueue", DISPATCH_QUEUE_SERIAL);
|
||||
_tokenQueue = dispatch_queue_create("org.subler.TheTVDBTokenQueue", DISPATCH_QUEUE_SERIAL);
|
||||
|
||||
_languagesTimestamp = [[NSUserDefaults.standardUserDefaults objectForKey:@"SBTheTVBDLanguagesArrayTimestamp"] doubleValue];
|
||||
|
||||
if (_languagesTimestamp + 60 * 60 * 24 * 30 > [NSDate timeIntervalSinceReferenceDate]) {
|
||||
_languagues = [NSUserDefaults.standardUserDefaults objectForKey:@"SBTheTVBDLanguagesArray"];
|
||||
}
|
||||
|
||||
_tokenTimestamp = [[NSUserDefaults.standardUserDefaults objectForKey:@"SBTheTVBDTokenTimestamp"] doubleValue];
|
||||
|
||||
if (_tokenTimestamp + 60 * 60 * 4 > [NSDate timeIntervalSinceReferenceDate]) {
|
||||
_token = [NSUserDefaults.standardUserDefaults objectForKey:@"SBTheTVBDToken"];
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)updateToken
|
||||
{
|
||||
NSDictionary *apiKey = @{@"apikey" : API_KEY};
|
||||
NSData *jsonApiKey = [NSJSONSerialization dataWithJSONObject:apiKey options:0 error:NULL];
|
||||
|
||||
NSDictionary *headerOptions = @{@"Content-Type" : @"application/json",
|
||||
@"Accept" : @"application/json"};
|
||||
|
||||
NSURL *url = [NSURL URLWithString:@"https://api.thetvdb.com/login"];
|
||||
NSData *data = [SBMetadataHelper downloadDataFromURL:url HTTPMethod:@"POST" HTTPBody:jsonApiKey headerOptions:headerOptions cachePolicy:SBCachePolicyDefault];
|
||||
|
||||
if (data) {
|
||||
id response = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
|
||||
if ([response isKindOfClass:[NSDictionary class]]) {
|
||||
NSString *token = response[@"token"];
|
||||
if ([token isKindOfClass:[NSString class]]) {
|
||||
_token = token;
|
||||
_tokenTimestamp = [NSDate timeIntervalSinceReferenceDate];
|
||||
[NSUserDefaults.standardUserDefaults setObject:token forKey:@"SBTheTVBDToken"];
|
||||
[NSUserDefaults.standardUserDefaults setObject:@(_tokenTimestamp)
|
||||
forKey:@"SBTheTVBDTokenTimestamp"];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)updateLanguages
|
||||
{
|
||||
NSURL *url = [NSURL URLWithString:@"https://api.thetvdb.com/languages"];
|
||||
NSData *languagesJSON = [self requestData:url language:@"en"];
|
||||
|
||||
NSDictionary *languagesDict = [NSJSONSerialization JSONObjectWithData:languagesJSON options:0 error:NULL];
|
||||
|
||||
if (languagesDict || [languagesDict isKindOfClass:[NSDictionary class]]) {
|
||||
|
||||
NSArray<NSDictionary *> *languagesArray = languagesDict[@"data"];
|
||||
|
||||
if (languagesArray || [languagesArray isKindOfClass:[NSArray class]]) {
|
||||
|
||||
MP42Languages *langManager = MP42Languages.defaultManager;
|
||||
NSMutableArray<NSString *> *result = [NSMutableArray array];
|
||||
|
||||
for (NSDictionary *lang in languagesArray) {
|
||||
if ([lang isKindOfClass:[NSDictionary class]]) {
|
||||
NSString *abbreviation = lang[@"abbreviation"];
|
||||
if (abbreviation && [abbreviation isKindOfClass:[NSString class]]) {
|
||||
[result addObject:[langManager extendedTagForISO_639_1:abbreviation]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_languagues = result;
|
||||
_languagesTimestamp = [NSDate timeIntervalSinceReferenceDate];
|
||||
[NSUserDefaults.standardUserDefaults setObject:result forKey:@"SBTheTVBDLanguagesArray"];
|
||||
[NSUserDefaults.standardUserDefaults setObject:@(_languagesTimestamp)
|
||||
forKey:@"SBTheTVBDLanguagesArrayTimestamp"];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)token
|
||||
{
|
||||
__block NSString *token = nil;
|
||||
|
||||
dispatch_sync(_tokenQueue, ^{
|
||||
|
||||
if (self->_tokenTimestamp + 60 * 60 * 4 < [NSDate timeIntervalSinceReferenceDate]
|
||||
|| self->_token == nil) {
|
||||
[self updateToken];
|
||||
}
|
||||
|
||||
token = self->_token;
|
||||
});
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)languagues
|
||||
{
|
||||
__block NSArray<NSString *> *languages = @[@"en"];
|
||||
|
||||
dispatch_sync(_queue, ^{
|
||||
|
||||
if (self->_languagues == nil) {
|
||||
[self updateLanguages];
|
||||
}
|
||||
|
||||
if (self->_languagues) {
|
||||
languages = self->_languagues;
|
||||
}
|
||||
});
|
||||
|
||||
return languages;
|
||||
}
|
||||
|
||||
- (NSData *)requestData:(NSURL *)url language:(NSString *)language
|
||||
{
|
||||
NSString *token = self.token;
|
||||
|
||||
if (token == nil) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSDictionary *headerOptions = @{@"Authorization" : [NSString stringWithFormat:@"Bearer %@", token],
|
||||
@"Content-Type" : @"application/json",
|
||||
@"Accept" : @"application/json",
|
||||
@"Accept-Language" : language};
|
||||
NSData *data = [SBMetadataHelper downloadDataFromURL:url HTTPMethod:@"GET" HTTPBody:nil headerOptions:headerOptions cachePolicy:SBCachePolicyDefault];
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
#pragma mark - wrapper
|
||||
|
||||
- (NSArray<NSDictionary *> *)fetchSeries:(NSString *)seriesName language:(NSString *)language
|
||||
{
|
||||
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/search/series?name=%@", seriesName]];
|
||||
NSData *seriesJSON = [self requestData:url language:language];
|
||||
|
||||
if (seriesJSON) {
|
||||
|
||||
NSDictionary *series = [NSJSONSerialization JSONObjectWithData:seriesJSON options:0 error:NULL];
|
||||
|
||||
if (series || [series isKindOfClass:[NSDictionary class]]) {
|
||||
|
||||
NSArray<NSDictionary *> *seriesArray = series[@"data"];
|
||||
|
||||
if ([seriesArray isKindOfClass:[NSArray class]] && seriesArray.count) {
|
||||
return seriesArray;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return @[];
|
||||
}
|
||||
|
||||
- (nullable NSDictionary *)fetchSeriesInfo:(NSNumber *)seriesID language:(NSString *)language
|
||||
{
|
||||
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/series/%@", seriesID]];
|
||||
NSData *seriesInfoJSON = [SBTheTVDBConnection.defaultManager requestData:url language:language];
|
||||
|
||||
if (!seriesInfoJSON) { return nil; }
|
||||
|
||||
NSDictionary *seriesInfo = [NSJSONSerialization JSONObjectWithData:seriesInfoJSON options:0 error:NULL];
|
||||
|
||||
if (!seriesInfo || ![seriesInfo isKindOfClass:[NSDictionary class]]) { return nil; }
|
||||
|
||||
seriesInfo = seriesInfo[@"data"];
|
||||
|
||||
if (!seriesInfo || ![seriesInfo isKindOfClass:[NSDictionary class]]) { return nil; }
|
||||
|
||||
return seriesInfo;
|
||||
|
||||
}
|
||||
|
||||
- (NSArray<NSDictionary *> *)fetchSeriesActors:(NSNumber *)seriesID language:(NSString *)language
|
||||
{
|
||||
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/series/%@/actors", seriesID]];
|
||||
NSData *seriesActorsJSON = [SBTheTVDBConnection.defaultManager requestData:url language:language];
|
||||
|
||||
if (!seriesActorsJSON) { return @[]; }
|
||||
|
||||
NSDictionary *seriesActorsDictionary = [NSJSONSerialization JSONObjectWithData:seriesActorsJSON options:0 error:NULL];
|
||||
|
||||
if (!seriesActorsDictionary || ![seriesActorsDictionary isKindOfClass:[NSDictionary class]]) { return @[]; }
|
||||
|
||||
NSArray<NSDictionary *> *seriesActors = seriesActorsDictionary[@"data"];
|
||||
|
||||
if (!seriesActors || ![seriesActors isKindOfClass:[NSArray class]]) { return @[]; }
|
||||
|
||||
return seriesActors;
|
||||
}
|
||||
|
||||
- (NSArray<NSDictionary *> *)fetchSeriesImages:(NSNumber *)seriesID type:(NSString *)type language:(NSString *)language;
|
||||
{
|
||||
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/series/%@/images/query?keyType=%@", seriesID, type]];
|
||||
NSData *imagesJSON = [SBTheTVDBConnection.defaultManager requestData:url language:language];
|
||||
|
||||
if (!imagesJSON) { return @[]; }
|
||||
|
||||
NSDictionary *imagesDictionary = [NSJSONSerialization JSONObjectWithData:imagesJSON options:0 error:NULL];
|
||||
|
||||
if (!imagesDictionary || ![imagesDictionary isKindOfClass:[NSDictionary class]]) { return @[]; }
|
||||
|
||||
NSArray<NSDictionary *> *imagesArray = imagesDictionary[@"data"];
|
||||
|
||||
if (!imagesArray || ![imagesArray isKindOfClass:[NSArray class]]) { return @[]; }
|
||||
|
||||
return imagesArray;
|
||||
}
|
||||
|
||||
- (NSArray<NSDictionary *> *)fetchEpisodes:(NSNumber *)seriesID season:(NSString *)season number:(NSString *)number language:(NSString *)language;
|
||||
{
|
||||
NSURL *url;
|
||||
if (season.length && number.length) {
|
||||
url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/series/%@/episodes/query?airedSeason=%@&airedEpisode=%@",
|
||||
seriesID, season, number]];
|
||||
} else if (season.length) {
|
||||
url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/series/%@/episodes/query?airedSeason=%@",
|
||||
seriesID, season]];
|
||||
}
|
||||
else {
|
||||
url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/series/%@/episodes", seriesID]];
|
||||
}
|
||||
|
||||
NSData *episodesJSON = [SBTheTVDBConnection.defaultManager requestData:url language:language];
|
||||
|
||||
if (!episodesJSON) { return @[]; }
|
||||
|
||||
NSDictionary *episodes = [NSJSONSerialization JSONObjectWithData:episodesJSON options:0 error:NULL];
|
||||
|
||||
if (!episodes || ![episodes isKindOfClass:[NSDictionary class]]) { return @[]; }
|
||||
|
||||
// Decode the individual episodes
|
||||
|
||||
NSArray<NSDictionary *> *episodesArray = episodes[@"data"];
|
||||
|
||||
if ([episodesArray isKindOfClass:[NSArray class]]) {
|
||||
return episodesArray;
|
||||
}
|
||||
|
||||
return @[];
|
||||
}
|
||||
|
||||
- (NSDictionary *)fetchEpisodesInfo:(NSNumber *)episodeID language:(NSString *)language;
|
||||
{
|
||||
NSURL *episodesUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.thetvdb.com/episodes/%@", episodeID]];
|
||||
NSData *episodesJSON = [SBTheTVDBConnection.defaultManager requestData:episodesUrl language:language];
|
||||
|
||||
if (!episodesJSON) { return nil; }
|
||||
|
||||
NSDictionary *episodesInfo = [NSJSONSerialization JSONObjectWithData:episodesJSON options:0 error:NULL];
|
||||
|
||||
if (!episodesInfo || ![episodesInfo isKindOfClass:[NSDictionary class]]) { return nil; }
|
||||
|
||||
episodesInfo = episodesInfo[@"data"];
|
||||
|
||||
if (!episodesInfo || ![episodesInfo isKindOfClass:[NSDictionary class]]) { return nil; }
|
||||
|
||||
return episodesInfo;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -15,7 +15,7 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
|
||||
override public var languageType: SBMetadataImporterLanguageType {
|
||||
get {
|
||||
return .ISO;
|
||||
return .ISO
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TV Series name search
|
||||
|
||||
override public func searchTVSeries(_ seriesName: String, language: String) -> [String] {
|
||||
var results: Set<String> = Set()
|
||||
|
||||
@@ -39,6 +41,8 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
return Array(results)
|
||||
}
|
||||
|
||||
// MARK: - TV Series ID search
|
||||
|
||||
private func match(series: SeriesSearchResult, name: String) -> Bool {
|
||||
if series.seriesName.caseInsensitiveCompare(name) == .orderedSame {
|
||||
return true
|
||||
@@ -59,6 +63,8 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
return series.filter { match(series: $0, name: seriesName) }.map { $0.id }
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func cleanList(actors: [Actor]) -> String {
|
||||
return actors.map { $0.name } .reduce("", { $0 + ($0.count > 0 ? ", " : "") + $1 })
|
||||
}
|
||||
@@ -133,6 +139,74 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
return filteredEpisodes.map { merge(episode: $0, info: info, actors: actors) }
|
||||
}
|
||||
|
||||
// MARK: - Nil values check
|
||||
|
||||
private struct NilValues : OptionSet {
|
||||
let rawValue: Int
|
||||
|
||||
static let episodesInfo = NilValues(rawValue: 1)
|
||||
static let seriesInfo = NilValues(rawValue: 2)
|
||||
}
|
||||
|
||||
private func checkMissingValues(results: [SBMetadataResult]) -> NilValues {
|
||||
|
||||
var options: NilValues = []
|
||||
|
||||
for result in results {
|
||||
if result[SBMetadataResultSeriesName] == nil {
|
||||
options.insert(.seriesInfo)
|
||||
}
|
||||
if result[SBMetadataResultName] == nil {
|
||||
options.insert(.episodesInfo)
|
||||
}
|
||||
if result[SBMetadataResultLongDescription] == nil {
|
||||
options.insert(.episodesInfo)
|
||||
}
|
||||
if result[SBMetadataResultSeriesDescription] == nil {
|
||||
options.insert(.seriesInfo)
|
||||
}
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
private func merge(enResults: [SBMetadataResult], results: [SBMetadataResult]) {
|
||||
if enResults.count != results.count { return }
|
||||
|
||||
for (index, result) in results.enumerated() {
|
||||
let enResult = enResults[index]
|
||||
|
||||
if result[SBMetadataResultSeriesName] == nil {
|
||||
result[SBMetadataResultSeriesName] = enResult[SBMetadataResultSeriesName]
|
||||
}
|
||||
if result[SBMetadataResultName] == nil {
|
||||
result[SBMetadataResultName] = enResult[SBMetadataResultName]
|
||||
}
|
||||
if result[SBMetadataResultLongDescription] == nil {
|
||||
result[SBMetadataResultLongDescription] = enResult[SBMetadataResultLongDescription]
|
||||
result[SBMetadataResultDescription] = enResult[SBMetadataResultDescription]
|
||||
}
|
||||
if result[SBMetadataResultSeriesDescription] == nil {
|
||||
result[SBMetadataResultSeriesDescription] = enResult[SBMetadataResultSeriesDescription]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func merge(info: SeriesInfo, results: [SBMetadataResult]) {
|
||||
let name = info.seriesName
|
||||
for result in results {
|
||||
result[SBMetadataResultSeriesName] = name
|
||||
}
|
||||
|
||||
if let overview = info.overview {
|
||||
for result in results {
|
||||
result[SBMetadataResultSeriesDescription] = overview
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TV Search
|
||||
|
||||
override public func searchTVSeries(_ seriesName: String, language: String, seasonNum: String, episodeNum: String) -> [SBMetadataResult] {
|
||||
|
||||
let seriesIDs: [Int] = {
|
||||
@@ -147,12 +221,28 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
let actors = session.fetch(actors: id, language: language)
|
||||
let episodes = loadEpisodes(info: info, actors: actors, season: seasonNum, episode: episodeNum, language: language)
|
||||
|
||||
let nilValues = checkMissingValues(results: episodes)
|
||||
|
||||
if language != TheTVDB.en {
|
||||
if nilValues.contains(.seriesInfo),
|
||||
let enInfo = session.fetch(seriesInfo: id, language: TheTVDB.en) {
|
||||
merge(info: enInfo, results: episodes)
|
||||
}
|
||||
|
||||
if nilValues.contains(.episodesInfo) {
|
||||
let enResults = loadEpisodes(info: info, actors: actors, season: seasonNum, episode: episodeNum, language: TheTVDB.en)
|
||||
merge(enResults: enResults, results: episodes)
|
||||
}
|
||||
}
|
||||
|
||||
results.append(contentsOf: episodes)
|
||||
}
|
||||
|
||||
return results.sorted(by: areInIncreasingOrder)
|
||||
}
|
||||
|
||||
// MARK: - Additional metadata
|
||||
|
||||
private func loadiTunesArtwork(_ metadata: SBMetadataResult) -> [SBRemoteImage] {
|
||||
guard let name = metadata[SBMetadataResultSeriesName] as? String,
|
||||
let episode = metadata[SBMetadataResultName] as? String,
|
||||
@@ -194,13 +284,13 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
var artworks: [SBRemoteImage] = Array()
|
||||
|
||||
if let info = session.fetch(episodeInfo: id, language: language) {
|
||||
metadata[SBMetadataResultDirector] = cleanList(names: info.directors);
|
||||
metadata[SBMetadataResultScreenwriters] = cleanList(names: info.writers);
|
||||
metadata[SBMetadataResultDirector] = cleanList(names: info.directors)
|
||||
metadata[SBMetadataResultScreenwriters] = cleanList(names: info.writers)
|
||||
|
||||
let guests = cleanList(names: info.guestStars)
|
||||
if let actors = metadata[SBMetadataResultCast] as? String {
|
||||
if actors.count > 0 && guests.count > 0 {
|
||||
metadata[SBMetadataResultCast] = actors + ", " + guests;
|
||||
metadata[SBMetadataResultCast] = actors + ", " + guests
|
||||
}
|
||||
} else if guests.count > 0 {
|
||||
metadata[SBMetadataResultCast] = guests
|
||||
@@ -222,7 +312,7 @@ final public class TheTVDB : SBMetadataImporter {
|
||||
artworks.append(contentsOf: posterImages)
|
||||
}
|
||||
|
||||
metadata.remoteArtworks = artworks;
|
||||
metadata.remoteArtworks = artworks
|
||||
|
||||
return metadata
|
||||
}
|
||||
|
||||
@@ -113,8 +113,29 @@ public class TheTVDBService {
|
||||
private let queue: DispatchQueue
|
||||
private let tokenQueue: DispatchQueue
|
||||
|
||||
private var languagesTimestamp: TimeInterval
|
||||
public var languages: [String]
|
||||
private let basePath = "https://api.thetvdb.com/"
|
||||
|
||||
private struct Languages {
|
||||
let data: [String]
|
||||
let timestamp: TimeInterval
|
||||
}
|
||||
|
||||
private var savedLanguages: Languages?
|
||||
|
||||
public var languages: [String] {
|
||||
get {
|
||||
if let result = savedLanguages, result.data.count > 0 {
|
||||
return result.data
|
||||
}
|
||||
else if let result = fetchLanguages() {
|
||||
savedLanguages = result
|
||||
UserDefaults.standard.set(result.data, forKey: "SBTheTVBDLanguagesArray")
|
||||
UserDefaults.standard.set(result.timestamp, forKey: "SBTheTVBDLanguagesArrayTimestamp")
|
||||
return result.data
|
||||
}
|
||||
return ["en"]
|
||||
}
|
||||
}
|
||||
|
||||
private struct Token {
|
||||
let key: String
|
||||
@@ -125,17 +146,19 @@ public class TheTVDBService {
|
||||
|
||||
private var token: Token? {
|
||||
get {
|
||||
var result: Token?
|
||||
var token: Token?
|
||||
tokenQueue.sync {
|
||||
if let token = savedToken {
|
||||
result = token
|
||||
if let result = savedToken, result.timestamp + 60 * 60 * 4 > Date.timeIntervalSinceReferenceDate {
|
||||
token = result
|
||||
}
|
||||
else if let token = login() {
|
||||
result = token
|
||||
savedToken = token
|
||||
else if let result = login() {
|
||||
UserDefaults.standard.set(result.key, forKey: "SBTheTVBDToken")
|
||||
UserDefaults.standard.set(result.timestamp, forKey: "SBTheTVBDTokenTimestamp")
|
||||
savedToken = result
|
||||
token = result
|
||||
}
|
||||
}
|
||||
return result
|
||||
return token
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,25 +166,32 @@ public class TheTVDBService {
|
||||
queue = DispatchQueue(label: "org.subler.TheTVDBQueue")
|
||||
tokenQueue = DispatchQueue(label: "org.subler.TheTVDBTokenQueue")
|
||||
|
||||
languagesTimestamp = UserDefaults.standard.double(forKey: "SBTheTVBDLanguagesArrayTimestamp")
|
||||
|
||||
if languagesTimestamp + 60 * 60 * 24 * 30 > Date.timeIntervalSinceReferenceDate {
|
||||
languages = UserDefaults.standard.object(forKey: "SBTheTVBDLanguagesArray") as! [String]
|
||||
if let languagesArray = UserDefaults.standard.object(forKey: "SBTheTVBDLanguagesArray") as? [String] {
|
||||
let timestamp = UserDefaults.standard.double(forKey: "SBTheTVBDLanguagesArrayTimestamp")
|
||||
if timestamp + 60 * 60 * 24 * 30 > Date.timeIntervalSinceReferenceDate {
|
||||
savedLanguages = Languages(data: languagesArray, timestamp: timestamp)
|
||||
}
|
||||
}
|
||||
else {
|
||||
languages = []
|
||||
|
||||
if let tokenKey = UserDefaults.standard.string(forKey: "SBTheTVBDToken") {
|
||||
let timestamp = UserDefaults.standard.double(forKey: "SBTheTVBDTokenTimestamp")
|
||||
if timestamp + 60 * 60 * 4 > Date.timeIntervalSinceReferenceDate {
|
||||
savedToken = Token(key: tokenKey, timestamp: timestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ApiKey : Codable {
|
||||
let apikey: String
|
||||
}
|
||||
|
||||
private struct TokenWrapper: Codable {
|
||||
let token: String
|
||||
}
|
||||
// MARK: - Login
|
||||
|
||||
private func login() -> Token? {
|
||||
struct ApiKey : Codable {
|
||||
let apikey: String
|
||||
}
|
||||
|
||||
struct TokenWrapper: Codable {
|
||||
let token: String
|
||||
}
|
||||
|
||||
guard let apikey = try? JSONEncoder().encode(ApiKey(apikey: "3498815BE9484A62")) else { return nil }
|
||||
guard let url = URL(string: "https://api.thetvdb.com/login") else { return nil }
|
||||
|
||||
@@ -178,20 +208,29 @@ public class TheTVDBService {
|
||||
return Token(key: responseToken.token, timestamp: Date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
|
||||
private struct Language: Codable {
|
||||
let abbreviation: String
|
||||
let englishName: String
|
||||
let id: Int
|
||||
let name: String
|
||||
// MARK: - Languages
|
||||
|
||||
private func fetchLanguages() -> Languages? {
|
||||
struct Language: Codable {
|
||||
let abbreviation: String
|
||||
let englishName: String
|
||||
let id: Int
|
||||
let name: String
|
||||
}
|
||||
|
||||
struct LanguageWrapper : Codable {
|
||||
let data: [Language]
|
||||
}
|
||||
|
||||
guard let url = URL(string: basePath + "languages"),
|
||||
let result = sendJSONRequest(url: url, language: "en", type: LanguageWrapper.self)
|
||||
else { return nil }
|
||||
|
||||
let langManager = MP42Languages.defaultManager
|
||||
return Languages(data: result.data.map { langManager.extendedTag(forISO_639_1:$0.abbreviation) }, timestamp: Date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
|
||||
private struct Languages : Codable {
|
||||
let data: [Language]
|
||||
}
|
||||
|
||||
private func fetchLanguages() {
|
||||
|
||||
}
|
||||
// MARK: - Data request
|
||||
|
||||
private func sendRequest(url: URL, language: String) -> Data? {
|
||||
guard let token = self.token else { return nil }
|
||||
@@ -212,13 +251,15 @@ public class TheTVDBService {
|
||||
return result
|
||||
}
|
||||
|
||||
// MARK: - Service call
|
||||
|
||||
public func fetch(series: String, language: String) -> [SeriesSearchResult] {
|
||||
struct SeriesSearchResultWrapper : Codable {
|
||||
let data: [SeriesSearchResult]
|
||||
}
|
||||
let encodedName = SBMetadataHelper.urlEncoded(series)
|
||||
|
||||
guard let url = URL(string: "https://api.thetvdb.com/search/series?name=" + encodedName),
|
||||
guard let url = URL(string: basePath + "search/series?name=" + encodedName),
|
||||
let result = sendJSONRequest(url: url, language: language, type: SeriesSearchResultWrapper.self)
|
||||
else { return [SeriesSearchResult]() }
|
||||
|
||||
@@ -230,7 +271,7 @@ public class TheTVDBService {
|
||||
let data: SeriesInfo
|
||||
}
|
||||
|
||||
guard let url = URL(string: "https://api.thetvdb.com/series/" + String(seriesID)),
|
||||
guard let url = URL(string: basePath + "series/" + String(seriesID)),
|
||||
let result = sendJSONRequest(url: url, language: language, type: SeriesInfoWrapper.self)
|
||||
else { return nil }
|
||||
|
||||
@@ -242,7 +283,7 @@ public class TheTVDBService {
|
||||
let data: [Actor]
|
||||
}
|
||||
|
||||
guard let url = URL(string: "https://api.thetvdb.com/series/" + String(seriesID) + "/actors"),
|
||||
guard let url = URL(string: basePath + "series/" + String(seriesID) + "/actors"),
|
||||
let result = sendJSONRequest(url: url, language: language, type: ActorsWrapper.self)
|
||||
else { return [] }
|
||||
|
||||
@@ -254,7 +295,7 @@ public class TheTVDBService {
|
||||
let data: [Image]
|
||||
}
|
||||
|
||||
guard let url = URL(string: "https://api.thetvdb.com/series/" + String(seriesID) + "/images/query?keyType=" + type),
|
||||
guard let url = URL(string: basePath + "series/" + String(seriesID) + "/images/query?keyType=" + type),
|
||||
let result = sendJSONRequest(url: url, language: language, type: ImagesWrapper.self)
|
||||
else { return [] }
|
||||
|
||||
@@ -264,11 +305,11 @@ public class TheTVDBService {
|
||||
private func episodesURL(seriesID: Int, season: String, episode: String) -> URL? {
|
||||
switch (season, episode) {
|
||||
case _ where season.count > 0 && episode.count > 0:
|
||||
return URL(string: "https://api.thetvdb.com/series/" + String(seriesID) + "/episodes/query?airedSeason=" + season + "&airedEpisode=" + episode)
|
||||
return URL(string: basePath + "series/" + String(seriesID) + "/episodes/query?airedSeason=" + season + "&airedEpisode=" + episode)
|
||||
case _ where season.count > 0:
|
||||
return URL(string: "https://api.thetvdb.com/series/" + String(seriesID) + "/episodes/query?airedSeason=" + season)
|
||||
return URL(string: basePath + "series/" + String(seriesID) + "/episodes/query?airedSeason=" + season)
|
||||
default:
|
||||
return URL(string: "https://api.thetvdb.com/series/" + String(seriesID) + "/episodes")
|
||||
return URL(string: basePath + "series/" + String(seriesID) + "/episodes")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +330,7 @@ public class TheTVDBService {
|
||||
let data: EpisodeInfo
|
||||
}
|
||||
|
||||
guard let url = URL(string: "https://api.thetvdb.com/episodes/" + String(episodeID)),
|
||||
guard let url = URL(string: basePath + "episodes/" + String(episodeID)),
|
||||
let result = sendJSONRequest(url: url, language: language, type: EpisodesInfoWrapper.self)
|
||||
else { return nil }
|
||||
|
||||
|
||||
@@ -6,4 +6,5 @@
|
||||
#import "SBMetadataImporter.h"
|
||||
#import "SBiTunesStore.h"
|
||||
#import <MP42Foundation/MP42Ratings.h>
|
||||
#import <MP42Foundation/MP42Languages.h>
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
A93DD7681DACCE930052749A /* SBComboBoxCellView.m in Sources */ = {isa = PBXBuildFile; fileRef = A93DD7671DACCE930052749A /* SBComboBoxCellView.m */; };
|
||||
A94721931D49DC0000858DD8 /* SBMetadataPrefsViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = A94721911D49DC0000858DD8 /* SBMetadataPrefsViewController.m */; };
|
||||
A94A6A591ED1C5CC00049F7D /* ParseFilename in Resources */ = {isa = PBXBuildFile; fileRef = A94A6A581ED1C5CA00049F7D /* ParseFilename */; };
|
||||
A95395D41ED5839300E578D8 /* SBTheTVDBConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = A95395D31ED5839300E578D8 /* SBTheTVDBConnection.m */; };
|
||||
A95B8DA91B09F37800F2F152 /* Subler_Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = A95B8DA81B09F37800F2F152 /* Subler_Tests.m */; };
|
||||
A960E96317D4B00900FC6ED9 /* SBImageBrowserView.m in Sources */ = {isa = PBXBuildFile; fileRef = A960E96217D4B00900FC6ED9 /* SBImageBrowserView.m */; };
|
||||
A961476313F567E10068F161 /* SBQueueController.m in Sources */ = {isa = PBXBuildFile; fileRef = A961476013F567E10068F161 /* SBQueueController.m */; };
|
||||
@@ -98,7 +97,6 @@
|
||||
CD56963212FAAD680029FADB /* SBArtworkSelector.m in Sources */ = {isa = PBXBuildFile; fileRef = CD56963112FAAD680029FADB /* SBArtworkSelector.m */; };
|
||||
CD71FEA312F1B5AF00F0A98D /* SBMetadataSearchController.m in Sources */ = {isa = PBXBuildFile; fileRef = CD71FEA212F1B5AF00F0A98D /* SBMetadataSearchController.m */; };
|
||||
CD71FEA612F1B62600F0A98D /* MetadataSearch.xib in Resources */ = {isa = PBXBuildFile; fileRef = CD71FEA412F1B62600F0A98D /* MetadataSearch.xib */; };
|
||||
CD71FF1D12F1C4A900F0A98D /* SBTheTVDB.m in Sources */ = {isa = PBXBuildFile; fileRef = CD71FF1C12F1C4A900F0A98D /* SBTheTVDB.m */; };
|
||||
CDC06FCE1747494D003C1D0A /* SBiTunesStore.m in Sources */ = {isa = PBXBuildFile; fileRef = CDC06FCD1747494D003C1D0A /* SBiTunesStore.m */; };
|
||||
CDE8E452174CBBD4009410B5 /* iTunesStores.json in Resources */ = {isa = PBXBuildFile; fileRef = CDE8E451174CBBD4009410B5 /* iTunesStores.json */; };
|
||||
/* End PBXBuildFile section */
|
||||
@@ -213,8 +211,6 @@
|
||||
A94721901D49DC0000858DD8 /* SBMetadataPrefsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SBMetadataPrefsViewController.h; path = Classes/SBMetadataPrefsViewController.h; sourceTree = "<group>"; };
|
||||
A94721911D49DC0000858DD8 /* SBMetadataPrefsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBMetadataPrefsViewController.m; path = Classes/SBMetadataPrefsViewController.m; sourceTree = "<group>"; };
|
||||
A94A6A581ED1C5CA00049F7D /* ParseFilename */ = {isa = PBXFileReference; lastKnownFileType = folder; name = ParseFilename; path = Utilities/ParseFilename; sourceTree = "<group>"; };
|
||||
A95395D21ED5839300E578D8 /* SBTheTVDBConnection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SBTheTVDBConnection.h; path = Classes/MetadataImporters/SBTheTVDBConnection.h; sourceTree = "<group>"; };
|
||||
A95395D31ED5839300E578D8 /* SBTheTVDBConnection.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBTheTVDBConnection.m; path = Classes/MetadataImporters/SBTheTVDBConnection.m; sourceTree = "<group>"; };
|
||||
A95B8DA41B09F37700F2F152 /* Subler Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Subler Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A95B8DA71B09F37700F2F152 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
A95B8DA81B09F37800F2F152 /* Subler_Tests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = Subler_Tests.m; sourceTree = "<group>"; };
|
||||
@@ -337,8 +333,6 @@
|
||||
CD56966E12FAAFA90029FADB /* Quartz.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Quartz.framework; path = System/Library/Frameworks/Quartz.framework; sourceTree = SDKROOT; };
|
||||
CD71FEA112F1B5AF00F0A98D /* SBMetadataSearchController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SBMetadataSearchController.h; path = Classes/SBMetadataSearchController.h; sourceTree = "<group>"; };
|
||||
CD71FEA212F1B5AF00F0A98D /* SBMetadataSearchController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBMetadataSearchController.m; path = Classes/SBMetadataSearchController.m; sourceTree = "<group>"; };
|
||||
CD71FF1B12F1C4A900F0A98D /* SBTheTVDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SBTheTVDB.h; path = Classes/MetadataImporters/SBTheTVDB.h; sourceTree = "<group>"; };
|
||||
CD71FF1C12F1C4A900F0A98D /* SBTheTVDB.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBTheTVDB.m; path = Classes/MetadataImporters/SBTheTVDB.m; sourceTree = "<group>"; };
|
||||
CDC06FCC1747494D003C1D0A /* SBiTunesStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SBiTunesStore.h; path = Classes/MetadataImporters/SBiTunesStore.h; sourceTree = "<group>"; };
|
||||
CDC06FCD1747494D003C1D0A /* SBiTunesStore.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBiTunesStore.m; path = Classes/MetadataImporters/SBiTunesStore.m; sourceTree = "<group>"; };
|
||||
CDE8E451174CBBD4009410B5 /* iTunesStores.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = iTunesStores.json; sourceTree = "<group>"; };
|
||||
@@ -666,12 +660,8 @@
|
||||
CDC06FCD1747494D003C1D0A /* SBiTunesStore.m */,
|
||||
CD03087217576A550093A0BE /* SBTheMovieDB3.h */,
|
||||
CD03087317576A550093A0BE /* SBTheMovieDB3.m */,
|
||||
CD71FF1B12F1C4A900F0A98D /* SBTheTVDB.h */,
|
||||
CD71FF1C12F1C4A900F0A98D /* SBTheTVDB.m */,
|
||||
A9B514181EFC12310055A035 /* TheTVDB.swift */,
|
||||
A9FC6FF51EF2E3280034CCED /* TheTVDBService.swift */,
|
||||
A95395D21ED5839300E578D8 /* SBTheTVDBConnection.h */,
|
||||
A95395D31ED5839300E578D8 /* SBTheTVDBConnection.m */,
|
||||
A901C51C1C04F03F00430DC3 /* SBChapterImporter.h */,
|
||||
A901C51D1C04F03F00430DC3 /* SBChapterImporter.m */,
|
||||
A9D4B8681C05CBEB007845C4 /* SBChapterResult.h */,
|
||||
@@ -852,7 +842,6 @@
|
||||
A91690041DABFDAA004B9AB0 /* SBCheckBoxCellView.m in Sources */,
|
||||
A960E96317D4B00900FC6ED9 /* SBImageBrowserView.m in Sources */,
|
||||
A9DA3B9D1B918D5C00F1E40C /* SBExceptionAlertController.m in Sources */,
|
||||
A95395D41ED5839300E578D8 /* SBTheTVDBConnection.m in Sources */,
|
||||
A94721931D49DC0000858DD8 /* SBMetadataPrefsViewController.m in Sources */,
|
||||
A9BC410318D9AB8700F8C92C /* SBItemViewController.m in Sources */,
|
||||
A9AB484917F0AEA2000AA72E /* SBAppDelegate.m in Sources */,
|
||||
@@ -870,7 +859,6 @@
|
||||
A9B46ABF12B79D1C0040517A /* SBDocument.m in Sources */,
|
||||
A9C703121C05E08B00C89151 /* SBMetadataHelper.m in Sources */,
|
||||
CD71FEA312F1B5AF00F0A98D /* SBMetadataSearchController.m in Sources */,
|
||||
CD71FF1D12F1C4A900F0A98D /* SBTheTVDB.m in Sources */,
|
||||
A909440D1DD4C70900E9F89C /* SBTokenFieldCell.m in Sources */,
|
||||
A9F476231ED9DC2E00748CC0 /* SBRemoteImage.m in Sources */,
|
||||
A9C5FA6E19FA22590051F3FF /* SBLogWindowController.m in Sources */,
|
||||
|
||||
Reference in new issue
Block a user