-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5d4883c
commit e310427
Showing
19 changed files
with
390 additions
and
167 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
20 changes: 20 additions & 0 deletions
20
Sources/QuickVerse/Internal/Managers/LocalizationManager.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import Foundation | ||
|
||
class LocalizationManager { | ||
private let apiClient: API | ||
init(apiClient: API) { | ||
self.apiClient = apiClient | ||
} | ||
} | ||
|
||
extension LocalizationManager { | ||
func getLocalizationsFor(languageCode: String, completion: @escaping (Result<QuickVerseResponse, APIError>) -> Void) { | ||
guard let url = URL(string: RequestBuilder.buildLocalizationRequest(languageCode: languageCode)) else { | ||
return completion(.failure(.invalidURL)) | ||
} | ||
let request = Request(url: url, httpMethod: .get, body: nil) | ||
apiClient.makeRequest(request: request) { (result: Result<QuickVerseResponse, APIError>) in | ||
completion(result) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
83 changes: 83 additions & 0 deletions
83
Sources/QuickVerse/Internal/Managers/ReportingManager.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import Foundation | ||
|
||
class ReportingManager { | ||
private let apiClient: API | ||
init(apiClient: API) { | ||
self.apiClient = apiClient | ||
} | ||
|
||
struct UtilisedKey { | ||
let key: String | ||
var count: Int | ||
} | ||
struct MissingKey { | ||
let key: String | ||
let defaultValue: String | ||
} | ||
|
||
private let keyLimit = 4 | ||
private var missingKeys: [MissingKey] = [] | ||
private var utilisedKeys: [UtilisedKey] = [] | ||
private var needsTransmission: Bool { | ||
if !missingKeys.isEmpty { | ||
return true | ||
} else { | ||
let utilisedCount = utilisedKeys.compactMap { $0.count }.reduce(0, +) | ||
return (missingKeys.count + utilisedCount) >= keyLimit | ||
} | ||
} | ||
private var requestInFlight: Bool = false | ||
} | ||
|
||
extension ReportingManager { | ||
func logUtilisedKey(_ key: String) { | ||
let existingCount = utilisedKeys.first(where: { $0.key == key })?.count ?? 0 | ||
let newCount = existingCount + 1 | ||
utilisedKeys.removeAll(where: { $0.key == key }) | ||
utilisedKeys.append(UtilisedKey(key: key, count: newCount)) | ||
uploadKeyDataIfNecessary() | ||
} | ||
func logMissingKey(_ key: String, defaultValue: String?) { | ||
missingKeys.removeAll(where: { $0.key == key }) | ||
missingKeys.append(MissingKey(key: key, defaultValue: defaultValue ?? "")) | ||
uploadKeyDataIfNecessary() | ||
} | ||
} | ||
|
||
extension ReportingManager { | ||
func uploadKeyDataIfNecessary() { | ||
guard | ||
needsTransmission, | ||
!requestInFlight else { return } | ||
|
||
var missing: [[String: Any]] = [[:]] | ||
missingKeys.forEach { missingKey in | ||
missing.append(["key": missingKey.key, "default_value": missingKey.defaultValue]) | ||
} | ||
var utilised: [[String: Any]] = [[:]] | ||
utilisedKeys.forEach { utilisedKey in | ||
utilised.append(["key": utilisedKey.key, "count": utilisedKey.count]) | ||
} | ||
let json: [String: Any] = ["missing_keys": missing, "utilised_keys": utilised] | ||
|
||
guard | ||
let jsonData = try? JSONSerialization.data(withJSONObject: json), | ||
let url = URL(string: RequestBuilder.buildAnalyticsRequest()) else { return } | ||
|
||
requestInFlight = true | ||
|
||
let request = Request(url: url, httpMethod: .post, body: jsonData) | ||
apiClient.makeRequest(request: request) { [weak self] (result: Result<Void, APIError>) in | ||
guard let self else { return } | ||
switch result { | ||
case .success: | ||
missingKeys.removeAll() | ||
utilisedKeys.removeAll() | ||
case .failure: | ||
// Request failed, do not clear keys, retry on next | ||
break | ||
} | ||
requestInFlight = false | ||
} | ||
} | ||
} |
File renamed without changes.
File renamed without changes.
File renamed without changes.
10 changes: 10 additions & 0 deletions
10
Sources/QuickVerse/Internal/Model/Request/RequestBuilder.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import Foundation | ||
|
||
struct RequestBuilder { | ||
static func buildLocalizationRequest(languageCode: String) -> String { | ||
return RequestEndpoint.base + RequestType.localizations.path + languageCode | ||
} | ||
static func buildAnalyticsRequest() -> String { | ||
return RequestEndpoint.base + RequestType.reporting.path | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
Sources/QuickVerse/Internal/Model/Request/RequestEndpoint.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
struct RequestEndpoint { | ||
static let base = "https://quickverse.io/sdk/api/" | ||
} |
11 changes: 11 additions & 0 deletions
11
Sources/QuickVerse/Internal/Model/Request/RequestType.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
enum RequestType { | ||
case localizations | ||
case reporting | ||
|
||
var path: String { | ||
switch self { | ||
case .localizations: return "localisation/" | ||
case .reporting: return "report" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import Foundation | ||
import UIKit | ||
|
||
protocol API { | ||
func makeRequest<T: Decodable>(request: Request, completion: @escaping (Result<T, APIError>) -> Void) | ||
func makeRequest(request: Request, completion: @escaping (Result<Void, APIError>) -> Void) | ||
} | ||
|
||
class APIClient: API { | ||
var apiKey: String! | ||
private let sdkVersion = "1.4.1" | ||
|
||
private let session: URLSession | ||
init(session: URLSession) { | ||
self.session = session | ||
} | ||
} | ||
|
||
extension APIClient { | ||
func makeRequest<T: Decodable>(request: Request, completion: @escaping (Result<T, APIError>) -> Void) { | ||
|
||
guard let apiKey, !apiKey.isEmpty else { return completion (.failure(.noAPIKey)) } | ||
guard let bundleIdentifier = Bundle.main.bundleIdentifier else { return completion (.failure(.noBundleID)) } | ||
|
||
let tokenString = "\(bundleIdentifier):\(apiKey)" | ||
guard let tokenData = tokenString.data(using: .utf8) else { return completion (.failure(.invalidToken)) } | ||
let tokenEncoded = tokenData.base64EncodedString() | ||
|
||
let urlRequest = buildURLRequestWith(request: request, token: tokenEncoded) | ||
|
||
session.dataTask(with: urlRequest) { data, response, error in | ||
guard let response = response as? HTTPURLResponse else { return completion(.failure(.noResponse)) } | ||
guard let data else { return completion(.failure(.noData)) } | ||
|
||
guard (200...300).contains(response.statusCode) else { | ||
switch response.statusCode { | ||
case 401: return completion(.failure(.unauthorized)) | ||
default: return completion(.failure(.generic(response.statusCode))) | ||
} | ||
} | ||
do { | ||
let decoder = JSONDecoder() | ||
try completion(.success(decoder.decode(T.self, from: data))) | ||
} catch { | ||
completion(.failure(.decoding)) | ||
} | ||
|
||
}.resume() | ||
} | ||
func makeRequest(request: Request, completion: @escaping (Result<Void, APIError>) -> Void) { | ||
|
||
guard let apiKey, !apiKey.isEmpty else { return completion (.failure(.noAPIKey)) } | ||
guard let bundleIdentifier = Bundle.main.bundleIdentifier else { return completion (.failure(.noBundleID)) } | ||
|
||
let tokenString = "\(bundleIdentifier):\(apiKey)" | ||
guard let tokenData = tokenString.data(using: .utf8) else { return completion (.failure(.invalidToken)) } | ||
let tokenEncoded = tokenData.base64EncodedString() | ||
|
||
let urlRequest = buildURLRequestWith(request: request, token: tokenEncoded) | ||
|
||
session.dataTask(with: urlRequest) { data, response, error in | ||
guard let response = response as? HTTPURLResponse else { return completion(.failure(.noResponse)) } | ||
|
||
guard (200...300).contains(response.statusCode) else { | ||
switch response.statusCode { | ||
case 401: return completion(.failure(.unauthorized)) | ||
default: return completion(.failure(.generic(response.statusCode))) | ||
} | ||
} | ||
completion(.success(())) | ||
}.resume() | ||
} | ||
} | ||
|
||
extension APIClient { | ||
private func buildURLRequestWith(request: Request, token: String) -> URLRequest { | ||
var urlRequest = URLRequest(url: request.url) | ||
urlRequest.httpMethod = request.httpMethod.rawValue | ||
urlRequest.httpBody = request.body | ||
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") | ||
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") | ||
urlRequest.setValue("Apple", forHTTPHeaderField: "Platform") | ||
urlRequest.setValue(sdkVersion, forHTTPHeaderField: "X_QUICKVERSE_VERSION") | ||
|
||
// NOTE: This is *not* an advertising identifier. It has no implication for privacy declarations. | ||
let vendorIdentifier = UIDevice.current.identifierForVendor?.uuidString ?? "" | ||
urlRequest.setValue(vendorIdentifier, forHTTPHeaderField: "X-QUICKVERSE-DEVICEID") | ||
|
||
return urlRequest | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
enum APIError: Error { | ||
case noAPIKey | ||
case noBundleID | ||
case invalidToken | ||
case invalidURL | ||
case noResponse | ||
case noData | ||
case unauthorized // 401 | ||
case generic(Int) // Returns error code for inspection | ||
case decoding | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
enum HTTPMethod: String { | ||
case get = "GET" | ||
case post = "POST" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import Foundation | ||
struct Request { | ||
let url: URL | ||
let httpMethod: HTTPMethod | ||
let body: Data? | ||
} |
Oops, something went wrong.