Download all the themoviedb results, add a rather crude retry-after implementation.

This commit is contained in:
Damiano Galassi committed 2018-08-16 17:40:04 +02:00
1 parent ac51609e18
commit d3907a7882
4 files changed
+59 -17

No files matched your search

+2 -2
View File
@@ -289,8 +289,8 @@ public struct TheMovieDB: MetadataService {
let USRating = ratings.filter { $0.iso_3166_1 == "US" }.compactMap { $0.rating }
if let rating = USRating.first {
metadata[.rating] = MP42Ratings.defaultManager.ratingStringForiTunesCountry("USA",
media: "TV",
ratingString: rating)
media: "TV",
ratingString: rating)
}
}
@@ -221,21 +221,33 @@ final public class TheMovieDBService {
private struct Wrapper<T> : Codable where T : Codable {
let results: T
let page: Int?
let total_results: Int?
let total_pages: Int?
}
// MARK: - Data request
private func sendRequest(url: URL, language: String) -> Data? {
private func sendRequest(url: URL, language: String) -> (Data?, URLResponse?) {
let header = ["Content-Type" : "application/json",
"Accept" : "application/json;charset=utf-8",
"Accept-Language" : language]
return URLSession.data(from: url, header: header)
return URLSession.dataAndResponse(from: url, header: header)
}
private func sendJSONRequest<T>(url: URL, language: String, type: T.Type) -> T? where T : Decodable {
guard let data = sendRequest(url: url, language: language),
let result = try? JSONDecoder().decode(type, from: data)
let (data, response) = sendRequest(url: url, language: language)
if let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 429,
let retryAfter = httpResponse.allHeaderFields["Retry-After"] as? String {
let retryTime = (Int(retryAfter) ?? 1) * 1000000
usleep(useconds_t(retryTime))
return sendJSONRequest(url: url, language: language, type: type)
}
guard let data1 = data, let result = try? JSONDecoder().decode(type, from: data1)
else { return nil }
return result
@@ -243,14 +255,25 @@ final public class TheMovieDBService {
// MARK: - Service calls
public func search(movie: String, language: String) -> [TMDBMovieSearchResult] {
private func search(movie: String, language: String, page: Int) -> Wrapper<[TMDBMovieSearchResult]>? {
let encodedName = movie.urlEncoded()
guard let url = URL(string: basePath + "search/movie?api_key=" + key + "&query=" + encodedName + "&language=" + language),
guard let url = URL(string: basePath + "search/movie?api_key=" + key + "&query=" + encodedName + "&language=" + language + "&page=" + String(page)),
let result = sendJSONRequest(url: url, language: language, type: Wrapper<[TMDBMovieSearchResult]>.self)
else { return [] }
else { return nil }
return result.results
return result
}
public func search(movie: String, language: String) -> [TMDBMovieSearchResult] {
guard let result = search(movie: movie, language: language, page: 1) else { return [] }
if let totalPages = result.total_pages, totalPages > 1 {
let additionalResult = Array(2...totalPages).compactMap { search(movie: movie, language: language, page: $0)?.results }
return result.results + additionalResult.joined();
} else {
return result.results
}
}
public func fetch(movieID: Int, language: String) -> TMDBMovie? {
+4 -2
View File
@@ -498,7 +498,8 @@ public struct iTunesStore: MetadataService {
guard let typeNodes = try? node.nodes(forXPath: "dt[contains(@class,'cast-list__term')]"),
let valueNodes = try? node.nodes(forXPath: "dd[contains(@class,'cast-list__detail')]") else { continue }
if let nodeType = typeNodes.first?.stringValue?.trimmingWhitespacesAndNewlinews(), nodeType.contains(type) {
if let nodeType = typeNodes.first?.stringValue?.trimmingWhitespacesAndNewlinews(),
nodeType.caseInsensitiveCompare(type) == ComparisonResult.orderedSame {
return valueNodes.compactMap { $0.stringValue }
}
}
@@ -513,7 +514,8 @@ public struct iTunesStore: MetadataService {
guard let typeNodes = try? node.nodes(forXPath: "dt[contains(@class,'information-list__item__term')]"),
let valueNodes = try? node.nodes(forXPath: "dd[contains(@class,'information-list__item__definition')]") else { continue }
if let nodeType = typeNodes.first?.stringValue, nodeType.contains(type),
if let nodeType = typeNodes.first?.stringValue?.trimmingWhitespacesAndNewlinews(),
nodeType.caseInsensitiveCompare(type) == ComparisonResult.orderedSame,
var value = valueNodes.first?.stringValue?.trimmingWhitespacesAndNewlinews() {
if let range = value.range(of: ". All Rights Reserved", options: .caseInsensitive,
range: value.startIndex ..< value.endIndex, locale: nil) {
+22 -5
View File
@@ -78,7 +78,7 @@ extension URLSession {
let sem = DispatchSemaphore(value: 0)
var downloadData : Data? = nil
URLSession.dataTask(with: url, httpMethod: httpMethod, httpBody: httpBody, header: header, cachePolicy: cachePolicy) { (data) in
URLSession.dataTask(with: url, httpMethod: httpMethod, httpBody: httpBody, header: header, cachePolicy: cachePolicy) { (data, response) in
downloadData = data
sem.signal()
}.resume()
@@ -88,7 +88,24 @@ extension URLSession {
return downloadData
}
static func dataTask(with url: URL, httpMethod: String = "GET", httpBody: Data? = nil, header: [String:String] = [:], cachePolicy: URLRequest.CachePolicy = URLRequest.CachePolicy.useProtocolCachePolicy, completionHandler: @escaping (Data?) -> Void) -> URLSessionTask {
static func dataAndResponse(from url: URL, httpMethod: String = "GET", httpBody: Data? = nil, header: [String:String] = [:], cachePolicy: URLRequest.CachePolicy = URLRequest.CachePolicy.useProtocolCachePolicy) -> (Data?, URLResponse?) {
let sem = DispatchSemaphore(value: 0)
var downloadData : Data? = nil
var downloadResponse: URLResponse? = nil
URLSession.dataTask(with: url, httpMethod: httpMethod, httpBody: httpBody, header: header, cachePolicy: cachePolicy) { (data, response) in
downloadData = data
downloadResponse = response
sem.signal()
}.resume()
_ = sem.wait()
return (downloadData, downloadResponse)
}
static func dataTask(with url: URL, httpMethod: String = "GET", httpBody: Data? = nil, header: [String:String] = [:], cachePolicy: URLRequest.CachePolicy = URLRequest.CachePolicy.useProtocolCachePolicy, completionHandler: @escaping (Data?, URLResponse?) -> Void) -> URLSessionTask {
var request = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: 30.0)
request.httpMethod = httpMethod
@@ -104,14 +121,14 @@ extension URLSession {
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
if statusCode == 200 {
completionHandler(data)
completionHandler(data, response)
}
else {
completionHandler(nil)
completionHandler(nil, response)
}
}
else {
completionHandler(nil)
completionHandler(nil, response)
}
}