This repository was archived by the owner on Sep 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathBookmarkCloudMigrator.swift
More file actions
91 lines (78 loc) · 2.66 KB
/
BookmarkCloudMigrator.swift
File metadata and controls
91 lines (78 loc) · 2.66 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
//
// BookmarkCloudMigrator.swift
// Freetime
//
// Created by Ryan Nystrom on 11/23/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
enum BookmarkCloudMigratorClientResult {
case noMigration
case success([String])
// when oauth restrictions fail some migrations
case partial(success: [String], errors: Int)
case error(Error?)
}
enum BookmarkCloudMigratorClientBookmarks {
case repo(owner: String, name: String)
case issueOrPullRequest(owner: String, name: String, number: Int)
}
protocol BookmarkCloudMigratorClient {
func fetch(
bookmarks: [BookmarkCloudMigratorClientBookmarks],
completion: @escaping (BookmarkCloudMigratorClientResult) -> Void
)
}
final class BookmarkCloudMigrator {
private let bookmarks: [BookmarkCloudMigratorClientBookmarks]
private let client: BookmarkCloudMigratorClient
enum State: Int {
case inProgress
case success
case error
}
private(set) var state: State = .inProgress
private let needsMigrationKey: String
init(username: String, oldBookmarks: [Bookmark], client: BookmarkCloudMigratorClient) {
self.bookmarks = oldBookmarks.compactMap {
switch $0.type {
case .commit, .release, .securityVulnerability, .ci_activity: return nil
case .issue, .pullRequest:
return .issueOrPullRequest(owner: $0.owner, name: $0.name, number: $0.number)
case .repo:
return .repo(owner: $0.owner, name: $0.name)
}
}
self.client = client
self.needsMigrationKey = "com.freetime.bookmark-cloud-migrator.has-migrated.\(username)"
}
var needsMigration: Bool {
get {
return state != .success
// dont offer migration if no old bookmarks
&& !bookmarks.isEmpty
// or this device has already performed a sync
&& !UserDefaults.standard.bool(forKey: needsMigrationKey)
}
set {
UserDefaults.standard.set(newValue, forKey: needsMigrationKey)
}
}
func sync(completion: @escaping (BookmarkCloudMigratorClientResult) -> Void) {
guard needsMigration else {
state = .success
completion(.noMigration)
return
}
client.fetch(bookmarks: bookmarks) { [weak self] result in
switch result {
case .success, .noMigration, .partial:
self?.needsMigration = false
self?.state = .success
case .error:
self?.state = .error
}
completion(result)
}
}
}