Skip to content

Commit 00dd682

Browse files
authored
Merge pull request #65 from TaskarCenterAtUW/feature-setup-posm-dev
Replaced Dev environment
2 parents 7341762 + 05aebd5 commit 00dd682

File tree

11 files changed

+149
-77
lines changed

11 files changed

+149
-77
lines changed

GoInfoGame/GoInfoGame/AppQuestManager.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,10 @@ class AppQuestManager {
3434
// Get the data from bbox
3535
let centralLocation = CLLocation(latitude: 37.7749, longitude: -122.4194) // San Francisco coords
3636
let distance = 100
37+
//37.41465820658871,-122.0912196996173,37.42366839341129,-122.0799229003827
3738
let boundingCoordinates = centralLocation.boundingCoordinates(distance: CLLocationDistance(distance))
38-
osmConnection.fetchMapData(left:boundingCoordinates.left.coordinate.longitude , bottom:boundingCoordinates.bottom.coordinate.latitude , right:boundingCoordinates.right.coordinate.longitude , top:boundingCoordinates.top.coordinate.latitude ) { result in
39+
40+
osmConnection.fetchMapData(left:bbox.minLon , bottom:bbox.minLat , right:bbox.maxLon , top:bbox.maxLat ) { result in
3941
switch result {
4042
case .success(let mapData):
4143
let response = Array(mapData.values)

GoInfoGame/GoInfoGame/DataBase/DBModels/StoredNode.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ class StoredNode : Object {
3232
}
3333

3434
public func asOSMNode() -> OSMNode {
35-
return OSMNode(type: "node", id: id, lat: point.latitude, lon: point.longitude, timestamp: Date(), version: version, changeset: -1, user: "", uid: -1)
35+
var storage = [String: String]()
36+
for tag in tags {
37+
storage[tag.key] = tag.value
38+
}
39+
return OSMNode(type: "node", id: id, lat: point.latitude, lon: point.longitude, timestamp: Date(), version: version, changeset: -1, user: "", uid: -1, tags: storage)
3640
}
3741
}

GoInfoGame/GoInfoGame/DataBase/DBModels/StoredWay.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import Foundation
1010
import RealmSwift
1111
import osmparser
1212
import MapKit
13+
import osmapi
1314

1415
// Represents one stored way
1516
class StoredWay: Object {
@@ -32,4 +33,13 @@ class StoredWay: Object {
3233
let way = Way(id: Int64(id), version: version, tags: theTags, timestampEdited: 0, type: .way, nodeIds: nodeList)
3334
return way
3435
}
36+
37+
public func asOSMWay() -> OSMWay {
38+
var storage = [String: String]()
39+
for tag in tags {
40+
storage[tag.key] = tag.value
41+
}
42+
let nodes = Array(nodes.map { Int($0) })
43+
return OSMWay(type: "way", id: id, timestamp: Date(), version: version, changeset: -1, user: "", uid: -1, nodes: nodes, tags: storage)
44+
}
3545
}

GoInfoGame/GoInfoGame/data/DatasyncManager.swift

Lines changed: 69 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,19 @@ class DatasyncManager {
1919

2020
private let dbInstance = DatabaseConnector.shared
2121

22-
private let osmConnection = OSMConnection(config: OSMConfig.test, currentChangesetId: nil, userCreds: OSMLogin.test)
22+
private let osmConnection = OSMConnection(config: OSMConfig.testOSM, currentChangesetId: nil, userCreds: OSMLogin.testOSM)
2323

24+
func syncDataToOSM( completionHandler: @escaping ()-> Void?) {
25+
Task {
26+
await syncData()
27+
completionHandler()
28+
}
29+
}
30+
31+
/// *** Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.'
32+
/// To fix the above error added @mainActor
33+
@MainActor
2434
func syncData() async {
25-
2635
if(isSynching){
2736
print("Already syncing")
2837
return
@@ -33,6 +42,7 @@ class DatasyncManager {
3342
let changesets = dbInstance.getChangesets()
3443
print("Starting to sync data")
3544
var nodesToSync: [String:StoredNode] = [:]
45+
var waysToSync: [String:StoredWay] = [:]
3646
for changeset in changesets {
3747
// Get the element type
3848
if changeset.elementType == .node {
@@ -41,6 +51,12 @@ class DatasyncManager {
4151
if let node = dbInstance.getNode(id: changeset.elementId) {
4252
nodesToSync[changeset.id] = node
4353
}
54+
}else if changeset.elementType == .way {
55+
print("Syncing Way")
56+
// Get the way
57+
if let way = dbInstance.getWay(id: changeset.elementId) {
58+
waysToSync[changeset.id] = way
59+
}
4460
}
4561
}
4662

@@ -52,15 +68,33 @@ class DatasyncManager {
5268
case .success(let isFinished):
5369
print("Synced \(payload)")
5470
DispatchQueue.main.async {
55-
// your code here
71+
// your code here
72+
self.dbInstance.assignChangesetId(obj: key, changesetId: payload.changeset)
73+
}
74+
75+
case .failure(let error):
76+
print("Failed to sync \(payload)")
77+
}
78+
}
79+
// TODO: Add logic to sync Way
80+
for (key,way) in waysToSync {
81+
var payload = way.asOSMWay()
82+
// update the way
83+
let result = await syncWay(way: &payload)
84+
switch result{
85+
case .success(let isFinished):
86+
print("Synced \(payload)")
87+
DispatchQueue.main.async {
88+
// your code here
5689
self.dbInstance.assignChangesetId(obj: key, changesetId: payload.changeset)
5790
}
5891

5992
case .failure(let error):
6093
print("Failed to sync \(payload)")
6194
}
95+
6296
}
63-
isSynching = false
97+
isSynching = false
6498

6599
}
66100

@@ -103,12 +137,22 @@ class DatasyncManager {
103137
// utility function to act as substitute for osmConnection functions
104138
func updateNode(node: inout OSMNode) async -> Result<Int,Error> {
105139
await withCheckedContinuation { continuation in
106-
osmConnection.updateNode(node: &node, tags: [:]) { result in
140+
osmConnection.updateNode(node: &node, tags: node.tags ?? [:]) { result in
107141
continuation.resume(returning: result)
108142
}
109143
}
110144
}
111145

146+
// utility function to act as substitute for osmConnection functions
147+
func updateWay(way: inout OSMWay) async -> Result<Int,Error> {
148+
await withCheckedContinuation { continuation in
149+
osmConnection.updateWay(way: &way, tags: way.tags) { result in
150+
continuation.resume(returning:result)
151+
}
152+
}
153+
}
154+
155+
112156

113157
/**
114158
Syncs the node along with the updated
@@ -132,4 +176,24 @@ class DatasyncManager {
132176
return .failure(error)
133177
}
134178
}
179+
180+
func syncWay(way: inout OSMWay) async -> Result<Bool,Error> {
181+
do {
182+
// open changeset
183+
let changesetId = try await openChangeset().get()
184+
// update node
185+
way.changeset = changesetId
186+
// close changeset
187+
let newVersion = try await updateWay(way: &way).get()
188+
way.version = newVersion
189+
// Give back the new version and other stuff.
190+
let closeResult = try await closeChangeset(id: String(changesetId)).get()
191+
192+
return .success(true)
193+
194+
} catch (let error){
195+
print(error)
196+
return .failure(error)
197+
}
198+
}
135199
}

GoInfoGame/GoInfoGame/quests/QuestProtocols.swift

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,17 +36,20 @@ class QuestBase {
3636
let storedElementType: StoredElementEnum = type == .way ? .way : .node
3737
let storedId = String(id)
3838
// Create a changeset
39-
let newChangeset = DatabaseConnector.shared.createChangeset(id: storedId, type: storedElementType, tags: tags)
39+
_ = DatabaseConnector.shared.createChangeset(id: storedId, type: storedElementType, tags: tags)
4040
switch (storedElementType){
4141
case .way:
42-
DatabaseConnector.shared.addWayTags(id: storedId, tags: tags)
42+
_ = DatabaseConnector.shared.addWayTags(id: storedId, tags: tags)
4343
case .node:
44-
DatabaseConnector.shared.addNodeTags(id: storedId, tags: tags)
44+
_ = DatabaseConnector.shared.addNodeTags(id: storedId, tags: tags)
4545
case .unknown:
4646
print("Unknown Stored element type received")
4747
}
4848
// Sync using datasyncmanager
4949

50+
DatasyncManager.shared.syncDataToOSM {
51+
print("SYNC DONE")
52+
}
5053
}
5154

5255
}

GoInfoGame/osmapi/OSMConfig.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,8 @@ public struct OSMConfig {
1919
public static var test: OSMConfig {
2020
OSMConfig(baseUrl: "https://waylyticsposm.westus2.cloudapp.azure.com/api/0.6/")
2121
}
22+
23+
public static var testOSM : OSMConfig {
24+
OSMConfig(baseUrl: "https://master.apis.dev.openstreetmap.org/api/0.6/")
25+
}
2226
}

GoInfoGame/osmapi/OSMConnection.swift

Lines changed: 33 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,11 @@
88
import Foundation
99
public class OSMConnection {
1010
// Creates a connection
11-
let baseUrl: String// = OSMConfig.baseUrl
12-
11+
let baseUrl: String
1312
var currentChangesetId: Int? = 0
14-
15-
// let userCreds: OSMLogin = OSMLogin(username: "[email protected]", password: "a$hwa7hamA")
1613
let userCreds: OSMLogin
17-
//ycqzd3_F6rqDEhs / [email protected]
18-
1914
// Lets see if we can start with some authentication or node
20-
21-
public init(config: OSMConfig = OSMConfig.test, currentChangesetId: Int? = nil, userCreds: OSMLogin = OSMLogin.test) {
15+
public init(config: OSMConfig = OSMConfig.testOSM, currentChangesetId: Int? = nil, userCreds: OSMLogin = OSMLogin.testOSM) {
2216
self.baseUrl = config.baseUrl
2317
self.currentChangesetId = currentChangesetId
2418
self.userCreds = userCreds
@@ -28,17 +22,19 @@ public class OSMConnection {
2822
let urlString = self.baseUrl.appending("node/").appending(id).appending(".json")
2923
guard let url = URL(string: urlString) else {
3024
print("Invalid URL given")
31-
return
32-
}
25+
return
26+
}
27+
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
3328
BaseNetworkManager.shared.fetchData(url: url, completion: completion) // Need to improve this one
3429
}
3530

3631
func getWay(id: String,_ completion: @escaping (Result<OSMWayResponse, Error>)-> Void) {
3732
let urlString = self.baseUrl.appending("way/").appending(id).appending(".json")
3833
guard let url = URL(string: urlString) else {
3934
print("Invalid URL given")
40-
return
41-
}
35+
return
36+
}
37+
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
4238
BaseNetworkManager.shared.fetchData(url: url, completion: completion) // Need to improve this one
4339
}
4440

@@ -47,8 +43,8 @@ public class OSMConnection {
4743
let urlString = self.baseUrl.appending("changeset/create")
4844
guard let url = URL(string: urlString) else {
4945
print("Invalid URL given")
50-
return
51-
}
46+
return
47+
}
5248
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
5349
BaseNetworkManager.shared.postData(url: url,method: "PUT" ,body: OSMChangesetPayload()) { (result: Result<Int,Error>) in
5450
switch result {
@@ -63,12 +59,12 @@ public class OSMConnection {
6359
}
6460
}
6561

66-
public func closeChangeSet(id: String,completion: @escaping((Result<Bool,Error>)->Void)) {
62+
public func closeChangeSet(id: String,completion: @escaping((Result<Bool,Error>)->Void)) {
6763
let urlString = self.baseUrl.appending("changeset/").appending(id).appending("/close")
6864
guard let url = URL(string: urlString) else {
6965
print("Invalid URL given")
70-
return
71-
}
66+
return
67+
}
7268
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
7369
BaseNetworkManager.shared.postData(url: url,method: "PUT" ,body: ["tag":"xyz"],expectEmpty: true) { (result: Result<Bool,Error>) in
7470
switch result {
@@ -83,24 +79,20 @@ public class OSMConnection {
8379
}
8480
}
8581

82+
// TODO: We are not using this any where, need to discuss and remove it.
8683
// Original method with everything from postman
8784
func getChangesets(_ completion: @escaping(()->())) {
88-
89-
var request = URLRequest(url: URL(string: "https://waylyticsposm.westus2.cloudapp.azure.com/api/0.6/changesets.json")!,timeoutInterval: Double.infinity)
90-
request.addValue("Basic bmFyZXNoZEB2aW5kYWdvLmluOmEkaHdhN2hhbUE=", forHTTPHeaderField: "Authorization")
91-
85+
let urlString = self.baseUrl.appending("changesets.json")
86+
var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
87+
request.addValue("Basic \(self.userCreds.getHeaderData())", forHTTPHeaderField: "Authorization")
9288
request.httpMethod = "GET"
93-
9489
let task = URLSession.shared.dataTask(with: request) { data, response, error in
95-
guard let data = data else {
96-
print(String(describing: error))
97-
completion()
98-
return
99-
}
100-
print(String(data: data, encoding: .utf8)!)
90+
guard let data = data else {
91+
completion()
92+
return
93+
}
10194
completion()
10295
}
103-
10496
task.resume()
10597
}
10698

@@ -110,8 +102,8 @@ public class OSMConnection {
110102
let urlString = self.baseUrl.appending("changesets.json?open=true")
111103
guard let url = URL(string: urlString) else {
112104
print("Invalid URL given")
113-
return
114-
}
105+
return
106+
}
115107
// Get to work
116108
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
117109
BaseNetworkManager.shared.fetchData(url: url, completion: completion)
@@ -123,8 +115,8 @@ public class OSMConnection {
123115
let urlString = self.baseUrl.appending("node/").appending(String(node.id))
124116
guard let url = URL(string: urlString) else {
125117
print("Invalid URL given")
126-
return
127-
}
118+
return
119+
}
128120
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
129121
// Add nodes to the same
130122
if(node.tags == nil){
@@ -139,13 +131,13 @@ public class OSMConnection {
139131

140132
}
141133

142-
func updateWay(way: inout OSMWay, tags:[String:String], completion: @escaping((Result<Int,Error>)->Void)){
134+
public func updateWay(way: inout OSMWay, tags:[String:String], completion: @escaping((Result<Int,Error>)->Void)){
143135
// Have to do this.
144136
let urlString = self.baseUrl.appending("way/").appending(String(way.id))
145137
guard let url = URL(string: urlString) else {
146138
print("Invalid URL given")
147-
return
148-
}
139+
return
140+
}
149141
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
150142
// Add nodes to the same
151143

@@ -158,27 +150,25 @@ public class OSMConnection {
158150
}
159151
func getUserDetailsWithId(id: String,_ completion: @escaping (Result<OSMUserDataResponse, Error>)-> Void) {
160152
let urlString = self.baseUrl.appending("user/").appending(id).appending(".json")
161-
print(urlString)
162153
guard let url = URL(string: urlString) else {
163154
print("Invalid URL given")
164-
return
165-
}
155+
return
156+
}
166157
BaseNetworkManager.shared.fetchData(url: url, completion: completion)
167158
}
168159
func getUserDetails(_ completion: @escaping (Result<OSMUserDataResponse, Error>)-> Void) {
169160
let urlString = self.baseUrl.appending("user/details.json")
170-
print(urlString)
171161
guard let url = URL(string: urlString) else {
172162
print("Invalid URL given")
173-
return
174-
}
163+
return
164+
}
175165
BaseNetworkManager.shared.addOrSetHeaders(header: "Authorization", value: "Basic \(self.userCreds.getHeaderData())")
176166
BaseNetworkManager.shared.fetchData(url: url, completion: completion)
177167
}
178168

179169
/// Internal function for getting the map data
180170
public func getOSMMapData(left: Double, bottom: Double, right: Double, top: Double,_ completion: @escaping (Result<OSMMapDataResponse, Error>)-> Void) {
181-
let urlString = "https://api.openstreetmap.org/api/0.6/map.json?bbox=\(left),\(bottom),\(right),\(top)"
171+
let urlString = self.baseUrl.appending("map.json?bbox=\(left),\(bottom),\(right),\(top)")
182172
print(urlString)
183173
guard let url = URL(string: urlString) else {
184174
print("Invalid URL given")

GoInfoGame/osmapi/OSMLogin.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,8 @@ public struct OSMLogin {
2525
public static var test : OSMLogin {
2626
OSMLogin(username: "[email protected]", password: "a$hwa7hamA") // Need to change
2727
}
28+
29+
public static var testOSM : OSMLogin {
30+
OSMLogin(username: "[email protected]", password: "d.Dgq6J6aBy.dCJ")
31+
}
2832
}

0 commit comments

Comments
 (0)