mirror of
https://repo.dactyloidae.xyz/Dactyloidae/UXP.git
synced 2026-09-20 07:17:32 +09:00
Dactyloidae iOS initial commit
This commit is contained in:
parent
daa6179d22
commit
7154a0497e
2123 changed files with 197052 additions and 0 deletions
137
mobile/ios/Providers/NSUserDefaultsPrefs.swift
Normal file
137
mobile/ios/Providers/NSUserDefaultsPrefs.swift
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import Foundation
|
||||
import Shared
|
||||
|
||||
open class NSUserDefaultsPrefs: Prefs {
|
||||
|
||||
fileprivate let prefixWithDot: String
|
||||
fileprivate let userDefaults: UserDefaults
|
||||
|
||||
open func getBranchPrefix() -> String {
|
||||
return self.prefixWithDot
|
||||
}
|
||||
|
||||
init(prefix: String, userDefaults: UserDefaults) {
|
||||
self.prefixWithDot = prefix + (prefix.endsWith(".") ? "" : ".")
|
||||
self.userDefaults = userDefaults
|
||||
}
|
||||
|
||||
init(prefix: String) {
|
||||
self.prefixWithDot = prefix + (prefix.endsWith(".") ? "" : ".")
|
||||
self.userDefaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
|
||||
}
|
||||
|
||||
open func branch(_ branch: String) -> Prefs {
|
||||
let prefix = self.prefixWithDot + branch + "."
|
||||
return NSUserDefaultsPrefs(prefix: prefix, userDefaults: self.userDefaults)
|
||||
}
|
||||
|
||||
// Preferences are qualified by the profile's local name.
|
||||
// Connecting a profile to a Firefox Account, or changing to another, won't alter this.
|
||||
fileprivate func qualifyKey(_ key: String) -> String {
|
||||
return self.prefixWithDot + key
|
||||
}
|
||||
|
||||
open func setInt(_ value: Int32, forKey defaultName: String) {
|
||||
// Why aren't you using userDefaults.setInteger?
|
||||
// Because userDefaults.getInteger returns a non-optional; it's impossible
|
||||
// to tell whether there's a value set, and you thus can't distinguish
|
||||
// between "not present" and zero.
|
||||
// Yeah, NSUserDefaults is meant to be used for storing "defaults", not data.
|
||||
setObject(NSNumber(value: value), forKey: defaultName)
|
||||
}
|
||||
|
||||
open func setTimestamp(_ value: Timestamp, forKey defaultName: String) {
|
||||
setLong(value, forKey: defaultName)
|
||||
}
|
||||
|
||||
open func setLong(_ value: UInt64, forKey defaultName: String) {
|
||||
setObject(NSNumber(value: value), forKey: defaultName)
|
||||
}
|
||||
|
||||
open func setLong(_ value: Int64, forKey defaultName: String) {
|
||||
setObject(NSNumber(value: value), forKey: defaultName)
|
||||
}
|
||||
|
||||
open func setString(_ value: String, forKey defaultName: String) {
|
||||
setObject(value as AnyObject?, forKey: defaultName)
|
||||
}
|
||||
|
||||
open func setObject(_ value: Any?, forKey defaultName: String) {
|
||||
userDefaults.set(value, forKey: qualifyKey(defaultName))
|
||||
}
|
||||
|
||||
open func stringForKey(_ defaultName: String) -> String? {
|
||||
// stringForKey converts numbers to strings, which is almost always a bug.
|
||||
return userDefaults.object(forKey: qualifyKey(defaultName)) as? String
|
||||
}
|
||||
|
||||
open func setBool(_ value: Bool, forKey defaultName: String) {
|
||||
setObject(NSNumber(value: value as Bool), forKey: defaultName)
|
||||
}
|
||||
|
||||
open func boolForKey(_ defaultName: String) -> Bool? {
|
||||
// boolForKey just returns false if the key doesn't exist. We need to
|
||||
// distinguish between false and non-existent keys, so use objectForKey
|
||||
// and cast the result instead.
|
||||
let number = userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber
|
||||
return number?.boolValue
|
||||
}
|
||||
|
||||
fileprivate func nsNumberForKey(_ defaultName: String) -> NSNumber? {
|
||||
return userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber
|
||||
}
|
||||
|
||||
open func unsignedLongForKey(_ defaultName: String) -> UInt64? {
|
||||
return nsNumberForKey(defaultName)?.uint64Value
|
||||
}
|
||||
|
||||
open func timestampForKey(_ defaultName: String) -> Timestamp? {
|
||||
return unsignedLongForKey(defaultName)
|
||||
}
|
||||
|
||||
open func longForKey(_ defaultName: String) -> Int64? {
|
||||
return nsNumberForKey(defaultName)?.int64Value
|
||||
}
|
||||
|
||||
open func objectForKey<T: Any>(_ defaultName: String) -> T? {
|
||||
return userDefaults.object(forKey: qualifyKey(defaultName)) as? T
|
||||
}
|
||||
|
||||
open func intForKey(_ defaultName: String) -> Int32? {
|
||||
return nsNumberForKey(defaultName)?.int32Value
|
||||
}
|
||||
|
||||
open func stringArrayForKey(_ defaultName: String) -> [String]? {
|
||||
let objects = userDefaults.stringArray(forKey: qualifyKey(defaultName))
|
||||
if let strings = objects {
|
||||
return strings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
open func arrayForKey(_ defaultName: String) -> [Any]? {
|
||||
return userDefaults.array(forKey: qualifyKey(defaultName)) as [Any]?
|
||||
}
|
||||
|
||||
open func dictionaryForKey(_ defaultName: String) -> [String: Any]? {
|
||||
return userDefaults.dictionary(forKey: qualifyKey(defaultName)) as [String: Any]?
|
||||
}
|
||||
|
||||
open func removeObjectForKey(_ defaultName: String) {
|
||||
userDefaults.removeObject(forKey: qualifyKey(defaultName))
|
||||
}
|
||||
|
||||
open func clearAll() {
|
||||
// TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites.
|
||||
// iOS Bug? Iterate and remove each manually for now.
|
||||
for key in userDefaults.dictionaryRepresentation().keys {
|
||||
if key.startsWith(prefixWithDot) {
|
||||
userDefaults.removeObject(forKey: key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
144
mobile/ios/Providers/PocketFeed.swift
Normal file
144
mobile/ios/Providers/PocketFeed.swift
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import Foundation
|
||||
import Alamofire
|
||||
import Shared
|
||||
import Deferred
|
||||
import Storage
|
||||
|
||||
private let PocketEnvAPIKey = "PocketEnvironmentAPIKey"
|
||||
private let PocketGlobalFeed = "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs"
|
||||
private let MaxCacheAge: Timestamp = OneMinuteInMilliseconds * 60 // 1 hour in milliseconds
|
||||
private let SupportedLocales = ["en_US", "en_GB", "en_ZA", "de_DE", "de_AT", "de_CH"]
|
||||
|
||||
/*s
|
||||
The Pocket class is used to fetch stories from the Pocked API.
|
||||
Right now this only supports the global feed
|
||||
|
||||
For a sample feed item check ClientTests/pocketglobalfeed.json
|
||||
*/
|
||||
struct PocketStory {
|
||||
let url: URL
|
||||
let title: String
|
||||
let storyDescription: String
|
||||
let imageURL: URL
|
||||
let domain: String
|
||||
let dedupeURL: URL
|
||||
|
||||
static func parseJSON(list: Array<[String: Any]>) -> [PocketStory] {
|
||||
return list.flatMap({ (storyDict) -> PocketStory? in
|
||||
guard let urlS = storyDict["url"] as? String, let domain = storyDict["domain"] as? String,
|
||||
let dedupe_URL = storyDict["dedupe_url"] as? String,
|
||||
let imageURLS = storyDict["image_src"] as? String,
|
||||
let title = storyDict["title"] as? String,
|
||||
let description = storyDict["excerpt"] as? String else {
|
||||
return nil
|
||||
}
|
||||
guard let url = URL(string: urlS), let imageURL = URL(string: imageURLS), let dedupeURL = URL(string: dedupe_URL) else {
|
||||
return nil
|
||||
}
|
||||
return PocketStory(url: url, title: title, storyDescription: description, imageURL: imageURL, domain: domain, dedupeURL: dedupeURL)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private class PocketError: MaybeErrorType {
|
||||
var description = "Failed to load from API"
|
||||
}
|
||||
|
||||
class Pocket {
|
||||
private let pocketGlobalFeed: String
|
||||
static let MoreStoriesURL = URL(string: "https://getpocket.com/explore/trending?src=ff_ios&cdn=0")!
|
||||
|
||||
// Allow endPoint to be overriden for testing
|
||||
init(endPoint: String = PocketGlobalFeed) {
|
||||
self.pocketGlobalFeed = endPoint
|
||||
}
|
||||
|
||||
lazy fileprivate var alamofire: SessionManager = {
|
||||
let ua = UserAgent.defaultClientUserAgent
|
||||
let configuration = URLSessionConfiguration.default
|
||||
var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
|
||||
defaultHeaders["User-Agent"] = ua
|
||||
configuration.httpAdditionalHeaders = defaultHeaders
|
||||
return SessionManager(configuration: configuration)
|
||||
}()
|
||||
|
||||
private func findCachedResponse(for request: URLRequest) -> [String: Any]? {
|
||||
let cachedResponse = URLCache.shared.cachedResponse(for: request)
|
||||
guard let cachedAtTime = cachedResponse?.userInfo?["cache-time"] as? Timestamp, (Date.now() - cachedAtTime) < MaxCacheAge else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let data = cachedResponse?.data, let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return json as? [String: Any]
|
||||
}
|
||||
|
||||
private func cache(response: HTTPURLResponse?, for request: URLRequest, with data: Data?) {
|
||||
guard let resp = response, let data = data else {
|
||||
return
|
||||
}
|
||||
let metadata = ["cache-time": Date.now()]
|
||||
let cachedResp = CachedURLResponse(response: resp, data: data, userInfo: metadata, storagePolicy: .allowed)
|
||||
URLCache.shared.removeCachedResponse(for: request)
|
||||
URLCache.shared.storeCachedResponse(cachedResp, for: request)
|
||||
}
|
||||
|
||||
// Fetch items from the global pocket feed
|
||||
func globalFeed(items: Int = 2) -> Deferred<Array<PocketStory>> {
|
||||
let deferred = Deferred<Array<PocketStory>>()
|
||||
|
||||
guard let request = createGlobalFeedRequest(items: items) else {
|
||||
deferred.fill([])
|
||||
return deferred
|
||||
}
|
||||
|
||||
if let cachedResponse = findCachedResponse(for: request), let items = cachedResponse["list"] as? Array<[String: Any]> {
|
||||
deferred.fill(PocketStory.parseJSON(list: items))
|
||||
return deferred
|
||||
}
|
||||
|
||||
alamofire.request(request).validate(contentType: ["application/json"]).responseJSON { response in
|
||||
guard response.error == nil, let result = response.result.value as? [String: Any] else {
|
||||
return deferred.fill([])
|
||||
}
|
||||
self.cache(response: response.response, for: request, with: response.data)
|
||||
guard let items = result["list"] as? Array<[String: Any]> else {
|
||||
return deferred.fill([])
|
||||
}
|
||||
return deferred.fill(PocketStory.parseJSON(list: items))
|
||||
}
|
||||
|
||||
return deferred
|
||||
}
|
||||
|
||||
// Returns nil if the locale is not supported
|
||||
static func IslocaleSupported(_ locale: String) -> Bool {
|
||||
return SupportedLocales.contains(locale)
|
||||
}
|
||||
|
||||
// Create the URL request to query the Pocket API. The max items that the query can return is 20
|
||||
private func createGlobalFeedRequest(items: Int = 2) -> URLRequest? {
|
||||
guard items > 0 && items <= 20 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let locale = Locale.current.identifier
|
||||
let pocketLocale = locale.replacingOccurrences(of: "_", with: "-")
|
||||
var params = [URLQueryItem(name: "count", value: String(items)), URLQueryItem(name: "locale_lang", value: pocketLocale)]
|
||||
if let consumerKey = Bundle.main.object(forInfoDictionaryKey: PocketEnvAPIKey) as? String {
|
||||
params.append(URLQueryItem(name: "consumer_key", value: consumerKey))
|
||||
}
|
||||
|
||||
guard let feedURL = URL(string: pocketGlobalFeed)?.withQueryParams(params) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return URLRequest(url: feedURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 5)
|
||||
}
|
||||
}
|
||||
1251
mobile/ios/Providers/Profile.swift
Normal file
1251
mobile/ios/Providers/Profile.swift
Normal file
File diff suppressed because it is too large
Load diff
131
mobile/ios/Providers/SyncStatusResolver.swift
Normal file
131
mobile/ios/Providers/SyncStatusResolver.swift
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import Sync
|
||||
import Shared
|
||||
import Storage
|
||||
|
||||
public enum SyncDisplayState {
|
||||
case inProgress
|
||||
case good
|
||||
case bad(message: String?)
|
||||
case warning(message: String)
|
||||
|
||||
func asObject() -> [String: String]? {
|
||||
switch self {
|
||||
case .bad(let msg):
|
||||
guard let message = msg else {
|
||||
return ["state": "Error"]
|
||||
}
|
||||
return ["state": "Error",
|
||||
"message": message]
|
||||
case .warning(let message):
|
||||
return ["state": "Warning",
|
||||
"message": message]
|
||||
default:
|
||||
break
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func ==(a: SyncDisplayState, b: SyncDisplayState) -> Bool {
|
||||
switch (a, b) {
|
||||
case (.inProgress, .inProgress):
|
||||
return true
|
||||
case (.good, .good):
|
||||
return true
|
||||
case (.bad(let a), .bad(let b)) where a == b:
|
||||
return true
|
||||
case (.warning(let a), .warning(let b)) where a == b:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Translates the fine-grained SyncStatuses of each sync engine into a more coarse-grained
|
||||
* display-oriented state for displaying warnings/errors to the user.
|
||||
*/
|
||||
public struct SyncStatusResolver {
|
||||
|
||||
let engineResults: Maybe<EngineResults>
|
||||
|
||||
public func resolveResults() -> SyncDisplayState {
|
||||
guard let results = engineResults.successValue else {
|
||||
switch engineResults.failureValue {
|
||||
case _ as BookmarksMergeError, _ as BufferInvalidError:
|
||||
return SyncDisplayState.warning(message: String(format: Strings.FirefoxSyncPartialTitle, Strings.localizedStringForSyncComponent("bookmarks") ?? ""))
|
||||
default:
|
||||
return SyncDisplayState.bad(message: nil)
|
||||
}
|
||||
}
|
||||
|
||||
// Run through the engine results and produce a relevant display status for each one
|
||||
let displayStates: [SyncDisplayState] = results.map { (engineIdentifier, syncStatus) in
|
||||
print("Sync status for \(engineIdentifier): \(syncStatus)")
|
||||
|
||||
// Explicitly call out each of the enum cases to let us lean on the compiler when
|
||||
// we add new error states
|
||||
switch syncStatus {
|
||||
case .notStarted(let reason):
|
||||
switch reason {
|
||||
case .offline:
|
||||
return .bad(message: Strings.FirefoxSyncOfflineTitle)
|
||||
case .noAccount:
|
||||
return .warning(message: Strings.FirefoxSyncOfflineTitle)
|
||||
case .backoff(_):
|
||||
return .good
|
||||
case .engineRemotelyNotEnabled(_):
|
||||
return .good
|
||||
case .engineFormatOutdated(_):
|
||||
return .good
|
||||
case .engineFormatTooNew(_):
|
||||
return .good
|
||||
case .storageFormatOutdated(_):
|
||||
return .good
|
||||
case .storageFormatTooNew(_):
|
||||
return .good
|
||||
case .stateMachineNotReady:
|
||||
return .good
|
||||
case .redLight:
|
||||
return .good
|
||||
case .unknown:
|
||||
return .good
|
||||
}
|
||||
case .completed:
|
||||
return .good
|
||||
case .partial:
|
||||
return .good
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Instead of finding the worst offender in a list of statuses, we should better surface
|
||||
// what might have happened with a particular engine when syncing.
|
||||
let aggregate: SyncDisplayState = displayStates.reduce(.good) { carried, displayState in
|
||||
switch displayState {
|
||||
|
||||
case .bad(_):
|
||||
return displayState
|
||||
|
||||
case .warning(_):
|
||||
// If the state we're carrying is worse than the stale one, keep passing
|
||||
// along the worst one
|
||||
switch carried {
|
||||
case .bad(_):
|
||||
return carried
|
||||
default:
|
||||
return displayState
|
||||
}
|
||||
default:
|
||||
// This one is good so just pass on what was being carried
|
||||
return carried
|
||||
}
|
||||
}
|
||||
|
||||
print("Resolved sync display state: \(aggregate)")
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue