Skip to content
Navigation Menu
{{ message }}
forked from altstoreio/AltStore
-
-
Notifications
You must be signed in to change notification settings - Fork 390
Expand file tree
/
Copy pathSource.swift
More file actions
409 lines (329 loc) · 13.7 KB
/
Copy pathSource.swift
File metadata and controls
409 lines (329 loc) · 13.7 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//
// Source.swift
// AltStore
//
// Created by Riley Testut on 7/30/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
import CoreData
import UIKit
public extension Source
{
#if ALPHA
static let altStoreGroupIdentifier = Bundle.Info.appbundleIdentifier
#else
static let altStoreGroupIdentifier = Bundle.Info.appbundleIdentifier
#endif
#if STAGING
#if ALPHA
static let altStoreSourceURL = URL(string: "https://apps.sidestore.io/")!
#else
static let altStoreSourceURL = URL(string: "https://apps.sidestore.io/")!
#endif
#else
#if ALPHA
static let altStoreSourceURL = URL(string: "https://sidestore.io/apps-v2.json/")!
#else
static let altStoreSourceURL = URL(string: "https://sidestore.io/apps-v2.json/")!
#endif
#endif
// normalized url is the source identifier (or) p-key!
static let altStoreIdentifier = try! Source.sourceID(from: altStoreSourceURL)
}
public extension Source
{
// Fallbacks for optional JSON values.
var effectiveIconURL: URL? {
return self.iconURL ?? self.apps.first?.iconURL
}
var effectiveHeaderImageURL: URL? {
return self.headerImageURL ?? self.effectiveIconURL
}
var effectiveTintColor: UIColor? {
return self.tintColor ?? self.apps.first?.tintColor
}
var effectiveFeaturedApps: [StoreApp] {
return self.featuredApps ?? self.apps
}
}
@objc(Source)
public class Source: BaseEntity, Decodable
{
/* Properties */
@NSManaged public var version: Int
@NSManaged public var name: String
@NSManaged public private(set) var identifier: String // NOTE: sourceID is just normalized sourceURL
@NSManaged public private(set) var groupID: String?
@NSManaged public var sourceURL: URL
/* Source Detail */
@NSManaged public var subtitle: String?
@NSManaged public var localizedDescription: String?
@NSManaged public var websiteURL: URL?
@NSManaged public var patreonURL: URL?
// Optional properties with fallbacks.
// `private` to prevent accidentally using instead of `effective[PropertyName]`
@NSManaged private var iconURL: URL?
@NSManaged private var headerImageURL: URL?
@NSManaged private var tintColor: UIColor?
@NSManaged public var error: NSError?
@NSManaged public var featuredSortID: String?
/* Non-Core Data Properties */
public var userInfo: [ALTSourceUserInfoKey: String]?
/* Relationships */
@objc(apps) @NSManaged public private(set) var _apps: NSOrderedSet
@objc(newsItems) @NSManaged public private(set) var _newsItems: NSOrderedSet
@objc(featuredApps) @NSManaged public private(set) var _featuredApps: NSOrderedSet
@objc(hasFeaturedApps) @NSManaged private var _hasFeaturedApps: Bool
@nonobjc public var apps: [StoreApp] {
get {
return self._apps.array as! [StoreApp]
}
set {
self._apps = NSOrderedSet(array: newValue)
}
}
@nonobjc public var newsItems: [NewsItem] {
get {
return self._newsItems.array as! [NewsItem]
}
set {
self._newsItems = NSOrderedSet(array: newValue)
}
}
public var isSourceAtLeastV2: Bool {
return self.version >= 2
}
// `internal` to prevent accidentally using instead of `effectiveFeaturedApps`
@nonobjc internal var featuredApps: [StoreApp]? {
return self._hasFeaturedApps ? self._featuredApps.array as? [StoreApp] : nil
}
private enum CodingKeys: String, CodingKey
{
case version
case name
case sourceURL
case subtitle
case localizedDescription = "description"
case iconURL
case headerImageURL = "headerURL"
case websiteURL = "website"
case tintColor
case patreonURL
case apps
case news
case featuredApps
case userInfo
// case identifier
case groupID = "identifier"
}
private override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?)
{
super.init(entity: entity, insertInto: context)
}
public required init(from decoder: Decoder) throws
{
guard let context = decoder.managedObjectContext else { preconditionFailure("Decoder must have non-nil NSManagedObjectContext.") }
guard let sourceURL = decoder.sourceURL else { preconditionFailure("Decoder must have non-nil sourceURL.") }
super.init(entity: Source.entity(), insertInto: context)
do
{
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
// Optional Values
// use sourceversion = 1 by default if not specified in source json
self.version = try container.decodeIfPresent(Int.self, forKey: .version) ?? 1
self.subtitle = try container.decodeIfPresent(String.self, forKey: .subtitle)
self.websiteURL = try container.decodeIfPresent(URL.self, forKey: .websiteURL)
self.localizedDescription = try container.decodeIfPresent(String.self, forKey: .localizedDescription)
self.iconURL = try container.decodeIfPresent(URL.self, forKey: .iconURL)
self.headerImageURL = try container.decodeIfPresent(URL.self, forKey: .headerImageURL)
self.patreonURL = try container.decodeIfPresent(URL.self, forKey: .patreonURL)
if let tintColorHex = try container.decodeIfPresent(String.self, forKey: .tintColor)
{
guard let tintColor = UIColor(hexString: tintColorHex) else {
throw DecodingError.dataCorruptedError(forKey: .tintColor, in: container, debugDescription: "Hex code is invalid.")
}
self.tintColor = tintColor
}
let userInfo = try container.decodeIfPresent([String: String].self, forKey: .userInfo)
self.userInfo = userInfo?.reduce(into: [:]) { $0[ALTSourceUserInfoKey($1.key)] = $1.value }
let apps = try container.decodeIfPresent([StoreApp].self, forKey: .apps) ?? []
let appsByID = Dictionary(apps.map { ($0.bundleIdentifier, $0) }, uniquingKeysWith: { (a, b) in return a })
for (index, app) in apps.enumerated()
{
app.sortIndex = Int32(index)
}
self._apps = NSMutableOrderedSet(array: apps)
let newsItems = try container.decodeIfPresent([NewsItem].self, forKey: .news) ?? []
for (index, item) in newsItems.enumerated()
{
item.sortIndex = Int32(index)
}
for newsItem in newsItems
{
guard let appID = newsItem.appID else { continue }
if let storeApp = appsByID[appID]
{
newsItem.storeApp = storeApp
}
else
{
newsItem.storeApp = nil
}
}
self._newsItems = NSMutableOrderedSet(array: newsItems)
let featuredAppBundleIDs = try container.decodeIfPresent([String].self, forKey: .featuredApps)
let featuredApps = featuredAppBundleIDs?.compactMap { appsByID[$0] }
self.setFeaturedApps(featuredApps)
// Updates identifier + apps & newsItems
try self.setSourceURL(sourceURL)
// NOTE: Source ID is just normalized sourceURL. coz normalized url is the primary key which needs to be unique
// Hence if a source's URL changed, then it means it is a different source now.
// This also means that the identifier field in the source is irrelevant (if any)
// if we want grouping of sources from same author or something like that then we should have used groupID (a new field)
// shouldn't use the existing "identifier" field, hence the following is commented out
// // if an explicit identifier is present, then use it
// if let identifier = try container.decodeIfPresent(String.self, forKey: .identifier)
// {
// self.identifier = identifier
// }
// if an explicit (group)identifier is present, then use it as groupID else use sourceID as groupID too
self.groupID = try container.decodeIfPresent(String.self, forKey: .groupID) ?? self.identifier
}
catch
{
if let context = self.managedObjectContext
{
context.delete(self)
}
throw error
}
}
public override func awakeFromInsert()
{
super.awakeFromInsert()
self.featuredSortID = UUID().uuidString
}
}
public extension Source
{
// Source is considered added IFF it has been saved to disk,
// which we can check by fetching on a new managed object context.
var isAdded: Bool {
get async throws {
let identifier = await AsyncManaged(wrappedValue: self).identifier
let backgroundContext = DatabaseManager.shared.persistentContainer.newBackgroundContext()
let isAdded = try await backgroundContext.performAsync {
let fetchRequest = Source.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "%K == %@", #keyPath(Source.identifier), identifier)
let count = try backgroundContext.count(for: fetchRequest)
return (count > 0)
}
return isAdded
}
}
var isPersisted: Bool {
let identifier = self.identifier
var count = 0
let context = DatabaseManager.shared.viewContext
context.performAndWait {
let fetchRequest = Source.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "%K == %@", #keyPath(Source.identifier), identifier)
count = (try? context.count(for: fetchRequest)) ?? 0
}
return count > 0
}
var isRecommended: Bool {
guard let recommendedSources = UserDefaults.shared.recommendedSources else { return false }
// TODO: Support alternate URLs
let isRecommended = recommendedSources.contains { source in
return source.identifier == self.identifier || source.sourceURL?.absoluteString.lowercased() == self.sourceURL.absoluteString.lowercased()
}
return isRecommended
}
var lastUpdatedDate: Date? {
let allDates = self.apps.compactMap { $0.latestAvailableVersion?.date } + self.newsItems.map { $0.date }
let lastUpdatedDate = allDates.sorted().last
return lastUpdatedDate
}
}
public extension Source
{
class func sourceID(from sourceURL: URL) throws -> String
{
let sourceID = try sourceURL.normalized()
return sourceID
}
}
internal extension Source
{
func setFeaturedApps(_ featuredApps: [StoreApp]?)
{
// Explicitly update relationships for all apps to ensure featuredApps merges correctly.
for case let storeApp as StoreApp in self._apps
{
if let featuredApps, featuredApps.contains(where: { $0.bundleIdentifier == storeApp.bundleIdentifier })
{
storeApp.featuringSource = self
}
else
{
storeApp.featuringSource = nil
}
}
self._featuredApps = NSOrderedSet(array: featuredApps ?? [])
self._hasFeaturedApps = (featuredApps != nil)
}
}
public extension Source
{
func setSourceURL(_ sourceURL: URL) throws
{
self.sourceURL = sourceURL
// update the normalized sourceURL as the identifier
let identifier = try Source.sourceID(from: sourceURL)
try self.setSourceID(identifier)
}
func setSourceID(_ identifier: String) throws
{
self.identifier = identifier
for app in self.apps
{
app.sourceIdentifier = identifier
}
for newsItem in self.newsItems
{
newsItem.sourceIdentifier = identifier
}
}
}
public extension Source
{
@nonobjc class func fetchRequest() -> NSFetchRequest<Source>
{
return NSFetchRequest<Source>(entityName: "Source")
}
class func makeAltStoreSource(in context: NSManagedObjectContext) -> Source
{
let source = Source(context: context)
source.name = "SideStore Offical"
source.groupID = Source.altStoreGroupIdentifier
source.identifier = Source.altStoreIdentifier
try! source.setSourceURL(Source.altStoreSourceURL)
return source
}
class func fetchAltStoreSource(in context: NSManagedObjectContext) -> Source?
{
let source = Source.first(satisfying: NSPredicate(format: "%K == %@", #keyPath(Source.identifier), Source.altStoreIdentifier), in: context)
return source
}
class func make(name: String, groupID: String, sourceURL: URL, context: NSManagedObjectContext) -> Source
{
let source = Source(context: context)
source.name = name
source.sourceURL = sourceURL
source.sourceURL = sourceURL
source.identifier = try! Source.sourceID(from: sourceURL)
return source
}
}
You can’t perform that action at this time.
