Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / XKit / GrandSlam / Requests / GrandSlamOperationRequest.swift

GrandSlamOperationRequest.swift102 lines · 2.7 KiBRaw
1//
2// GrandSlamOperationRequest.swift
3// XKit
4//
5// Created by Kabir Oberai on 19/11/19.
6// Copyright © 2019 Kabir Oberai. All rights reserved.
7//
8
9import Foundation
10
11struct GrandSlamOperationError: Error, LocalizedError {
12 let code: Int
13 let message: String
14
15 var errorDescription: String? {
16 "\(message) (\(code))"
17 }
18}
19
20struct GrandSlamOperationResponseStatusWrapper: Decodable {
21 struct Status: Decodable {
22 let errorCode: Int
23 let errorMessage: String
24
25 private enum CodingKeys: String, CodingKey {
26 case errorCode = "ec"
27 case errorMessage = "em"
28 }
29 }
30 let status: Status
31
32 private enum CodingKeys: String, CodingKey {
33 case status = "Status"
34 }
35}
36
37struct GrandSlamOperationResponseWrapper<T: Decodable>: Decodable {
38 let value: T
39 private enum CodingKeys: String, CodingKey {
40 case value = "Response"
41 }
42}
43
44struct GrandSlamOperationDecoder<T: Decodable>: GrandSlamDataDecoder {
45 static func decode(data: Data) throws -> T {
46 let decoder = PropertyListDecoder()
47 let status = try decoder.decode(
48 GrandSlamOperationResponseWrapper<GrandSlamOperationResponseStatusWrapper>.self,
49 from: data
50 ).value.status
51 guard status.errorCode == 0 else {
52 throw GrandSlamOperationError(code: status.errorCode, message: status.errorMessage)
53 }
54 return try decoder.decode(GrandSlamOperationResponseWrapper<T>.self, from: data).value
55 }
56}
57
58protocol GrandSlamOperationRequest: GrandSlamRequest
59 where Decoder == GrandSlamOperationDecoder<Value> {
60 associatedtype Value: Decodable
61
62 static var operation: String { get }
63
64 var username: String { get }
65 var parameters: [String: Any] { get }
66}
67
68extension GrandSlamOperationRequest {
69
70 static var endpoint: GrandSlamEndpoint { .lookup(\.gsService) }
71
72 func configure(request: inout HTTPRequest, anisetteData: AnisetteData) {
73 request.headerFields[.accept] = "*/*"
74 request.headerFields[.userAgent] = anisetteData.deviceInfo.akdUserAgent
75 }
76
77 func method(anisetteData: AnisetteData) -> GrandSlamMethod {
78 var clientData: [String: Any] = [
79 "bootstrap": true,
80 "icscrec": true,
81 "pbe": false,
82 "prkgen": true,
83 "svct": "iCloud",
84 "loc": Locale.current.identifier
85 ]
86 clientData.merge(anisetteData.dictionary) { _, b in b }
87
88 var request: [String: Any] = [
89 "o": Self.operation,
90 "u": username,
91 "cpd": clientData
92 ]
93 request.merge(parameters) { _, b in b }
94
95 let body = [
96 "Header": ["Version": "1.0.1"],
97 "Request": request
98 ]
99 return .post(body)
100 }
101
102}