-
Notifications
You must be signed in to change notification settings - Fork 392
/
Copy pathSendStoreReceiptOperation.swift
168 lines (144 loc) · 5.03 KB
/
SendStoreReceiptOperation.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
//
// SendStoreReceiptOperation.swift
// MullvadVPN
//
// Created by pronebird on 29/03/2022.
// Copyright © 2022 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadLogging
import MullvadREST
import MullvadTypes
import Operations
import StoreKit
class SendStoreReceiptOperation: ResultOperation<REST.CreateApplePaymentResponse>, SKRequestDelegate {
private let apiProxy: APIQuerying
private let accountNumber: String
private let forceRefresh: Bool
private let receiptProperties: [String: Any]?
private var refreshRequest: SKReceiptRefreshRequest?
private var submitReceiptTask: Cancellable?
private let logger = Logger(label: "SendStoreReceiptOperation")
init(
apiProxy: APIQuerying,
accountNumber: String,
forceRefresh: Bool,
receiptProperties: [String: Any]?,
completionHandler: @escaping CompletionHandler
) {
self.apiProxy = apiProxy
self.accountNumber = accountNumber
self.forceRefresh = forceRefresh
self.receiptProperties = receiptProperties
super.init(
dispatchQueue: .main,
completionQueue: .main,
completionHandler: completionHandler
)
}
override func operationDidCancel() {
refreshRequest?.cancel()
refreshRequest = nil
submitReceiptTask?.cancel()
submitReceiptTask = nil
}
override func main() {
// Pull receipt from AppStore if requested.
guard !forceRefresh else {
startRefreshRequest()
return
}
// Read AppStore receipt from disk.
do {
let data = try readReceiptFromDisk()
sendReceipt(data)
} catch is StoreReceiptNotFound {
// Pull receipt from AppStore if it's not cached locally.
startRefreshRequest()
} catch {
logger.error(
error: error,
message: "Failed to read the AppStore receipt."
)
finish(result: .failure(StorePaymentManagerError.readReceipt(error)))
}
}
// - MARK: SKRequestDelegate
func requestDidFinish(_ request: SKRequest) {
dispatchQueue.async {
do {
let data = try self.readReceiptFromDisk()
self.sendReceipt(data)
} catch {
self.logger.error(
error: error,
message: "Failed to read the AppStore receipt after refresh."
)
self.finish(result: .failure(StorePaymentManagerError.readReceipt(error)))
}
}
}
func request(_ request: SKRequest, didFailWithError error: Error) {
dispatchQueue.async {
self.logger.error(
error: error,
message: "Failed to refresh the AppStore receipt."
)
self.finish(result: .failure(StorePaymentManagerError.readReceipt(error)))
}
}
// MARK: - Private
private func startRefreshRequest() {
let refreshRequest = SKReceiptRefreshRequest(receiptProperties: receiptProperties)
refreshRequest.delegate = self
refreshRequest.start()
self.refreshRequest = refreshRequest
}
private func readReceiptFromDisk() throws -> Data {
guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL else {
throw StoreReceiptNotFound()
}
do {
return try Data(contentsOf: appStoreReceiptURL)
} catch let error as CocoaError
where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile {
throw StoreReceiptNotFound()
} catch {
throw error
}
}
private func sendReceipt(_ receiptData: Data) {
submitReceiptTask = apiProxy.createApplePayment(
accountNumber: accountNumber,
receiptString: receiptData
).execute(retryStrategy: .noRetry) { result in
switch result {
case let .success(response):
self.logger.info(
"""
AppStore receipt was processed. \
Time added: \(response.timeAdded), \
New expiry: \(response.newExpiry.logFormatted)
"""
)
self.finish(result: .success(response))
case let .failure(error):
if error.isOperationCancellationError {
self.logger.debug("Receipt submission cancelled.")
self.finish(result: .failure(error))
} else {
self.logger.error(
error: error,
message: "Failed to send the AppStore receipt."
)
self.finish(result: .failure(StorePaymentManagerError.sendReceipt(error)))
}
}
}
}
}
struct StoreReceiptNotFound: LocalizedError {
var errorDescription: String? {
"AppStore receipt file does not exist on disk."
}
}