Skip to content

Commit

Permalink
Add reporting API.
Browse files Browse the repository at this point in the history
  • Loading branch information
edwardbeecroft committed May 15, 2023
1 parent 5d4883c commit e310427
Show file tree
Hide file tree
Showing 19 changed files with 390 additions and 167 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"location" : "git@github.com:QuickVerse/quickverse-ios-sdk.git",
"state" : {
"branch" : "main",
"revision" : "c9c46a394f7debf8031302b280c5e32c5f407b4d"
"revision" : "5d4883c655a0821b94209f3f265c11fba6a33325"
}
}
],
Expand Down
2 changes: 1 addition & 1 deletion QuickVerse.podspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Pod::Spec.new do |spec|
spec.name = "QuickVerse"
spec.version = "1.4.0"
spec.version = "1.4.1"
spec.summary = "Effortlessly integrate your quickverse.io localisations into your iOS app, for instant, over-the-air updates & more."
spec.description = <<-DESC
QuickVerse lets you translate your web and mobile apps with ease. Powered by instant, over-the-air updates, you can change your app copy anytime, anywhere.
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ The library should have been added to the Swift Package Dependencies section, an

```
pod 'QuickVerse' // Always use the latest version
pod 'QuickVerse', '~> 1.4.0' // Or pin to a specific version
pod 'QuickVerse', '~> 1.4.1' // Or pin to a specific version
```
2. In a terminal window, navigate to the directory of your `Podfile`, and run `pod install --repo-update`

### Carthage

We recommend SPM for CocoaPods, but please contact us for integration guidance if you wish to use Carthage.
We recommend integrating with SPM or CocoaPods, but please contact us for integration guidance if you wish to use Carthage.

## Usage

Expand Down
20 changes: 20 additions & 0 deletions Sources/QuickVerse/Internal/Managers/LocalizationManager.swift
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)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
struct QuickVerseLogger {
static func logStatement(_ string: String) {
struct LoggingManager {
static func log(_ string: String) {
print("QuickVerse: \(string)")
}
static func printCodeForAvailableLocalizations(_ localizations: [QuickVerseLocalization]) {
static func logCodeForAvailableLocalizations(_ localizations: [QuickVerseLocalization]) {
var casesString = ""
for (index, localization) in localizations.enumerated() {
let propertyName = localization.key.replacingOccurrences(of: ".", with: "_")
Expand All @@ -20,10 +20,10 @@ struct QuickVerseLogger {
\(casesString)
}
Example: QuickVerse.shared.stringFor(key: QVKey.\(localizations.last?.key.replacingOccurrences(of: " .,-", with: "", options: [.regularExpression]) ?? ""))
Example: QuickVerse.stringFor(key: QVKey.\(localizations.last?.key.replacingOccurrences(of: " .,-", with: "", options: [.regularExpression]) ?? ""))
ℹ️ℹ️ℹ️ DEBUG: END AVAILABLE LOCALIZATION KEYS ℹ️ℹ️ℹ️
"""
QuickVerseLogger.logStatement(logString)
LoggingManager.log(logString)
}
}
83 changes: 83 additions & 0 deletions Sources/QuickVerse/Internal/Managers/ReportingManager.swift
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
}
}
}
10 changes: 10 additions & 0 deletions Sources/QuickVerse/Internal/Model/Request/RequestBuilder.swift
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
}
}
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 Sources/QuickVerse/Internal/Model/Request/RequestType.swift
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"
}
}
}
91 changes: 91 additions & 0 deletions Sources/QuickVerse/Internal/Networking/APIClient.swift
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
}
}
11 changes: 11 additions & 0 deletions Sources/QuickVerse/Internal/Networking/APIError.swift
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
}
4 changes: 4 additions & 0 deletions Sources/QuickVerse/Internal/Networking/HTTPMethod.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
}
6 changes: 6 additions & 0 deletions Sources/QuickVerse/Internal/Networking/Request.swift
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?
}
Loading

0 comments on commit e310427

Please sign in to comment.