File: SubscriptionManager.swift

package info (click to toggle)
mediainfo 25.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,656 kB
  • sloc: cpp: 18,871; objc: 3,102; xml: 1,426; sh: 1,328; python: 263; makefile: 212
file content (313 lines) | stat: -rw-r--r-- 11,804 bytes parent folder | download | duplicates (3)
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

import Foundation
import StoreKit

import TPInAppReceipt

extension Notification.Name {
    static let subscriptionDetailsReady = Notification.Name("net.mediaarea.mediainfo.ios.notifications.subscriptionDetailsReady")
    static let subscriptionDetailsUnaviable = Notification.Name("net.mediaarea.mediainfo.ios.notifications.subscriptionDetailsUnaviable")
    static let purchaseSucceeded = Notification.Name("net.mediaarea.mediainfo.ios.notifications.purchaseSucceeded")
    static let purchaseFailed = Notification.Name("net.mediaarea.mediainfo.ios.notifications.purchaseFailed")
    static let purchaseDeferred = Notification.Name("net.mediaarea.mediainfo.ios.notifications.purchaseDeferred")
    static let restoreFinished = Notification.Name("net.mediaarea.mediainfo.ios.notifications.restoreFinished")
    static let subscriptionStateChanged = Notification.Name("net.mediaarea.mediainfo.ios.notifications.subscriptionStateChanged")
}

class SubscriptionManager : NSObject, SKProductsRequestDelegate {
    static let shared = SubscriptionManager()

    private let subscriptionId = "net.mediaarea.mediainfo.ios.nrsubs.inapp1"
    private let lifetimeSubscriptionId = "net.mediaarea.mediainfo.ios.purchase.inapp1"

    var subscriptionDetails: SKProduct?
    var lifetimeSubscriptionDetails: SKProduct?

    var subscriptionActive: Bool = false {
        didSet(oldValue) {
            if subscriptionActive != oldValue {
                NotificationCenter.default.post(name: .subscriptionStateChanged, object: nil)
            }
        }
    }
    var isLifetime: Bool {
        get {
            if UserDefaults.standard.bool(forKey: "LifetimeSubscription") {
                return true
            }

            if NSUbiquitousKeyValueStore.default.bool(forKey: "LifetimeSubscription") {
                return true
            }

            return false
        }
        set(newValue) {
            if newValue {
                UserDefaults.standard.set(true, forKey: "LifetimeSubscription")
                NSUbiquitousKeyValueStore.default.set(true, forKey: "LifetimeSubscription")
                subscriptionActive = true
            }
        }
    }

    var subscriptions: [Date] {
        get {
            var toReturn: [Date] = []

            if let local = UserDefaults.standard.array(forKey: "Subscriptions") as? [Date] {
                toReturn = local
            }

            if let remote = NSUbiquitousKeyValueStore.default.array(forKey: "Subscriptions") as? [Date] {
                toReturn = Array(Set(toReturn + remote))
            }
            return toReturn
        }
        set(newValue) {
            var toAdd = newValue

            if let local = UserDefaults.standard.array(forKey: "Subscriptions") as? [Date] {
                toAdd = Array(Set(toAdd + local))
            }

            if let remote = NSUbiquitousKeyValueStore.default.array(forKey: "Subscriptions") as? [Date] {
                toAdd = Array(Set(toAdd + remote))
            }

            if toAdd.count > 0 {
                UserDefaults.standard.set(toAdd, forKey: "Subscriptions")
                NSUbiquitousKeyValueStore.default.set(toAdd, forKey: "Subscriptions")
            }
        }
    }

    var codes: [String] {
        get {
            var toReturn: [String] = []

            if let local = UserDefaults.standard.array(forKey: "Codes") as? [String] {
                toReturn = local
            }

            if let remote = NSUbiquitousKeyValueStore.default.array(forKey: "Codes") as? [String] {
                toReturn = Array(Set(toReturn + remote))
            }
            return toReturn
        }
        set(newValue) {
            var toAdd = newValue

            if let local = UserDefaults.standard.array(forKey: "Codes") as? [String] {
                toAdd = Array(Set(toAdd + local))
            }

            if let remote = NSUbiquitousKeyValueStore.default.array(forKey: "Codes") as? [String] {
                toAdd = Array(Set(toAdd + remote))
            }

            if toAdd.count > 0 {
                UserDefaults.standard.set(toAdd, forKey: "Codes")
                NSUbiquitousKeyValueStore.default.set(toAdd, forKey: "Codes")
            }
        }
    }

    var subscriptionEndDate: Date? {
        get {
            if let saved = UserDefaults.standard.array(forKey: "SubscriptionEndDate") as? [Date], saved.count > 0 {
                return saved[0]
            }
            return nil
        }
        set(newValue) {
            if let newDate = newValue {
                if newDate > subscriptionEndDate ?? Date(timeIntervalSince1970: 0.0) {
                    UserDefaults.standard.set([newDate], forKey: "SubscriptionEndDate")
                    subscriptionActive = subscriptionActive || isLifetime || newDate >= Date()

                }
            }
        }
    }

    var shouldNotifyUserForSubscriptionEnd: Bool {
        get {
            if let end = subscriptionEndDate, end < Date() && !isLifetime {
                if let saved = NSUbiquitousKeyValueStore.default.array(forKey: "SubscriptionEndUserNotificationDate") as? [Date], saved.count > 0 {
                    let lastNotificationDate = saved[0]
                    if lastNotificationDate <= end {
                        return true
                    }
                } else {
                    return true
                }
            }
            return false
        }
    }

    override init() {
        super.init()

        NotificationCenter.default.addObserver(self, selector: #selector(didChangeExternally(_:)), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: NSUbiquitousKeyValueStore.default)

        NSUbiquitousKeyValueStore.default.synchronize()

        parseReceipt()

        if let endDate = subscriptionEndDate {
            subscriptionActive = isLifetime || endDate >= Date()
        }
        if isLifetime {
            subscriptionActive = true
        }
    }

    func notifyUserForSubscriptionEnd(parent: UIViewController & SubscribeResultDelegate) {
        NSUbiquitousKeyValueStore.default.set([Date()], forKey: "SubscriptionEndUserNotificationDate")
        let controller = UIAlertController(title: NSLocalizedString("Renew subscription?", tableName: "Core", comment: ""), message: NSLocalizedString("Your subscription has just ended.", tableName: "Core", comment: ""), preferredStyle: .alert)
        controller.addAction(UIAlertAction(title: NSLocalizedString("Renew", tableName: "Core", comment: ""), style: .default, handler: { _ in
            let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            if let subscribeViewController = storyboard.instantiateViewController(withIdentifier: "SubscribeViewController") as? SubscribeViewController {
                let navigationController = UINavigationController(rootViewController: subscribeViewController)
                subscribeViewController.delegate = parent

                parent.present(navigationController, animated: true, completion: nil)
            }
        }))
        controller.addAction(UIAlertAction(title: NSLocalizedString("Close", tableName: "Core", comment: ""), style: .cancel))

        parent.present(controller, animated: true)
    }

    func purchase(product: SKProduct?) {
        if let subscription = product {
            let payment = SKPayment(product: subscription)
            SKPaymentQueue.default().add(payment)
        }
    }

    func purchaseFailed() {
        NotificationCenter.default.post(name: .purchaseFailed, object: nil)
    }

    func purchaseDeferred() {
        NotificationCenter.default.post(name: .purchaseDeferred, object: nil)
    }

    func purchased() {
        parseReceipt()
        NotificationCenter.default.post(name: .purchaseSucceeded, object: nil)
    }

    func restore() {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    func restored() {
        parseReceipt()
        NotificationCenter.default.post(name: .restoreFinished, object: nil)
    }

    func loadSubscription() {
        let request = SKProductsRequest(productIdentifiers: Set([subscriptionId, lifetimeSubscriptionId]))
        request.delegate = self
        request.start()
    }

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        for product in response.products {
            if product.productIdentifier == subscriptionId {
                subscriptionDetails = product
            }
            else if product.productIdentifier == lifetimeSubscriptionId {
                lifetimeSubscriptionDetails = product
            }
        }
        if subscriptionDetails != nil && lifetimeSubscriptionDetails != nil {
            NotificationCenter.default.post(name: .subscriptionDetailsReady, object: nil)
        }
    }

    func request(_ request: SKRequest, didFailWithError error: Error) {
        if type(of: request) == SKProductsRequest.self {
            NotificationCenter.default.post(name: .subscriptionDetailsUnaviable, object: nil)
        }
    }

    func parseSubscriptions() {
        var end = Date(timeIntervalSince1970: 0.0)
        for subscription in subscriptions.sorted(by: { $0.compare($1) == .orderedAscending }) {
            if subscription > end { // new subscription or re-subscribed after the end of previous subscription
                if let new = Calendar.current.date(byAdding: .year, value: 1, to: subscription) {
                    end = new
                }
            } else { // re-subscribed before the end of previous subscription
                if let new = Calendar.current.date(byAdding: .year, value: 1, to: end) {
                    end = new
                }
            }
        }
        if end != Date(timeIntervalSince1970: 0.0) {
            subscriptionEndDate = end
        }
    }

    func parseReceipt() {
        if let receiptData = loadReceipt() {
            do {
                let decodedReceipt = try InAppReceipt.receipt(from: receiptData)
                try decodedReceipt.verify()

                for subscription in decodedReceipt.purchases(ofProductIdentifier: subscriptionId) {
                    if !subscriptions.contains(subscription.purchaseDate) {
                        subscriptions.append(subscription.purchaseDate)
                    }
                }

                if decodedReceipt.purchases(ofProductIdentifier: lifetimeSubscriptionId).count > 0 {
                    isLifetime = true
                }
            } catch {
                NSLog("ERROR: unable to decode receipt, %@", error as NSError)
            }
        }
        parseSubscriptions()
    }

    func loadReceipt() -> Data? {
        guard let receiptUrl = Bundle.main.appStoreReceiptURL else {
            return nil
        }

        do {
            return try Data(contentsOf: receiptUrl)
        } catch {
            return nil
        }
    }

    @objc func didChangeExternally(_ notification: Notification) {
        // trigger syncronisation
        var toAdd: [Date] = []

        if let local = UserDefaults.standard.array(forKey: "Subscriptions") as? [Date] {
            toAdd = Array(Set(toAdd + local))
        }

        if let remote = NSUbiquitousKeyValueStore.default.array(forKey: "Subscriptions") as? [Date] {
            toAdd = Array(Set(toAdd + remote))
        }

        if toAdd.count > 0 {
            UserDefaults.standard.set(toAdd, forKey: "Subscriptions")
            NSUbiquitousKeyValueStore.default.set(toAdd, forKey: "Subscriptions")
        }
    }
}