Skip to content

Commit

Permalink
#17 Functioning Lift Time Updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Peyton-McKee committed May 24, 2023
1 parent aa20000 commit 23f4eaa
Show file tree
Hide file tree
Showing 14 changed files with 104 additions and 72 deletions.
4 changes: 3 additions & 1 deletion Database/Sources/App/Controllers/MapsController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ struct MapsController: RouteCollection {

return map.save(on: req.db).map { map }
}

func getAllHandler(_ req: Request) -> EventLoopFuture<[Map]> {
Map.query(on: req.db).all()
}
Expand Down Expand Up @@ -59,6 +60,7 @@ struct MapsController: RouteCollection {

return PublicMap(id: map.id!, name: map.name, initialLocationLatitude: map.initialLocationLatitude, initialLocationLongitude: map.initialLocationLongitude, mountainReportUrl: map.mountainReportUrl, trailStatusElementId: map.trailStatusElementId, liftStatusElementId: map.liftStatusElementId, mapTrail: publicMapTrails, mapConnector: publicMapConnectors)
}

func getMapTrailsHandler(_ req: Request)
-> EventLoopFuture<[MapTrail]> {
// 2
Expand All @@ -70,7 +72,6 @@ struct MapsController: RouteCollection {
}
}


func getMapConnectorsHandler(_ req: Request) -> EventLoopFuture<[MapConnector]> {
Map.find(req.parameters.get("mapId"), on: req.db)
.unwrap(or: Abort(.notFound))
Expand Down Expand Up @@ -112,6 +113,7 @@ struct MapsController: RouteCollection {

return .noContent
}

func deleteAllHandler(_ req: Request) async throws -> HTTPStatus {
let maps = try await Map.query(on: req.db).all()

Expand Down
35 changes: 23 additions & 12 deletions Database/Sources/App/Controllers/PointsController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ struct PointsController: RouteCollection {
pointsRoute.delete(":pointId", use: deleteHandler)
pointsRoute.delete( use: deleteAllHandler)
pointsRoute.put(":pointId", use: updateHandler)

}

func createHandler(_ req: Request)
Expand All @@ -28,32 +28,43 @@ struct PointsController: RouteCollection {
let point = Point(latitude: data.latitude, longitude: data.longitude, mapTrailID: data.mapTrailId, mapConnectorID: data.mapConnectorId, time: data.time, order: data.order)
return point.save(on: req.db).map { point }
}

func getAllHandler(_ req: Request) -> EventLoopFuture<[Point]> {
Point.query(on: req.db).all()
}

func getHandler(_ req: Request)
-> EventLoopFuture<Point> {

Point.find(req.parameters.get("pointId"), on: req.db)
.unwrap(or: Abort(.notFound))
}

func deleteHandler(_ req: Request) -> EventLoopFuture<HTTPStatus> {
Point.find(req.parameters.get("pointId"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { point in
point.delete(on: req.db).transform(to: .noContent)
}
}
func updateHandler(_ req: Request) throws -> EventLoopFuture<Point> {
let updatedPoint = try req.content.decode(updatePointTimeData.self)
return Point.find(req.parameters.get("pointId"), on: req.db)
.unwrap(or: Abort(.notFound)).flatMap { point in
point.time = updatedPoint.time
return point.save(on: req.db).map{
point
}
}

func updateHandler(_ req: Request) async throws -> Point {
guard let point = try? await Point.find(req.parameters.get("pointId"), on: req.db) else {
throw Abort(.notFound)
}
let updatedPointData = try req.content.decode(updatePointTimeData.self)

point.time = updatedPointData.time
do {
try await point.update(on: req.db)
} catch {
print("ERROR: ", error)
}

return point

}

func deleteAllHandler(_ req: Request) ->EventLoopFuture<HTTPStatus> {
Point.query(on: req.db)
.delete(force: true).transform(to: .noContent)
Expand All @@ -64,11 +75,11 @@ struct CreatePointData: Content{
let latitude: Float
let longitude: Float
let mapTrailId: UUID?
let time: [Float]
let time: [Double]
let mapConnectorId: UUID?
let order: Int
}

struct updatePointTimeData: Content {
let time: [Float]
let time: [Double]
}
17 changes: 12 additions & 5 deletions Database/Sources/App/Controllers/UsersController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ struct UsersController: RouteCollection
}

}

// 5
func createHandler(_ req: Request)
throws -> EventLoopFuture<User> {
Expand All @@ -57,18 +58,21 @@ struct UsersController: RouteCollection
}

return user.save(on: req.db).map{ user }

}
}

func getAllHandler(_ req: Request) -> EventLoopFuture<[User]> {
User.query(on: req.db).all()
}

func getHandler(_ req: Request)
-> EventLoopFuture<User> {
// 4
User.find(req.parameters.get("userID"), on: req.db)
.unwrap(or: Abort(.notFound))
}

func getTrailReportsHandler(_ req: Request)
-> EventLoopFuture<[TrailReport]> {
// 2
Expand All @@ -79,6 +83,7 @@ struct UsersController: RouteCollection
user.$trailReports.get(on: req.db)
}
}

func getUserLocationsHandler(_ req: Request)
-> EventLoopFuture<[UserLocation]> {
// 2
Expand All @@ -89,6 +94,7 @@ struct UsersController: RouteCollection
user.$userLocations.get(on: req.db)
}
}

func updateHandler(_ req: Request) throws -> EventLoopFuture<User> {
let updatedUser = try req.content.decode(User.self)
return User.find(req.parameters.get("userID"), on: req.db)
Expand All @@ -100,6 +106,7 @@ struct UsersController: RouteCollection
}
}
}

func getUserRoutesHandler(_ req: Request)
-> EventLoopFuture<[UserRoute]> {
// 2
Expand All @@ -123,10 +130,10 @@ struct UsersController: RouteCollection
.delete(force: true).transform(to: .noContent)
}

// func login(req: Request) throws -> User {
// print(req)
// return try req.auth.require(User.self)
// }
// func login(req: Request) throws -> User {
// print(req)
// return try req.auth.require(User.self)
// }
func checkIfUserExists(_ username: String, req: Request) -> EventLoopFuture<Bool> {
User.query(on: req.db).filter(\.$username == username).first().map({ $0 != nil })
}
Expand Down
2 changes: 1 addition & 1 deletion Database/Sources/App/Migrations/CreatePoints.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ struct CreatePoints: Migration {

.field("order", .int, .required)

.field("time", .array(of: .float), .required)
.field("time", .array(of: .double), .required)

.field("mapTrailID", .uuid, .references("mapTrails", "id"))

Expand Down
4 changes: 2 additions & 2 deletions Database/Sources/App/Models/Point.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ final class Point: Model, Content {
var order: Int

@Field(key: "time")
var time: [Float]
var time: [Double]

@OptionalParent(key: "mapTrailID")
var mapTrail: MapTrail?
Expand All @@ -34,7 +34,7 @@ final class Point: Model, Content {

init() {}

init(id: UUID? = nil, latitude: Float, longitude: Float, mapTrailID: MapTrail.IDValue?, mapConnectorID: MapConnector.IDValue?, time: [Float], order: Int) {
init(id: UUID? = nil, latitude: Float, longitude: Float, mapTrailID: MapTrail.IDValue?, mapConnectorID: MapConnector.IDValue?, time: [Double], order: Int) {
self.latitude = latitude
self.longitude = longitude
self.$mapTrail.id = mapTrailID
Expand Down
8 changes: 4 additions & 4 deletions MapsInterpreter/kmlInterpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def save_mountain_to_database(mapInfo: MapInfo):
jsonMap = {'name': name, 'initialLocationLatitude': iniitalLocationLatitude, 'initialLocationLongitude': initialLocationLongitude, 'mountainReportUrl': mountainReportUrl,
'trailStatusElementId': trailStatusElementId, 'liftStatusElementId': liftStatusElementId}
#35.172.135.117
baseURL = "http://35.172.13/api"
baseURL = "http://localhost:8080/api"
mapUrl = baseURL + '/maps'
mapConnectorURL = baseURL + '/map-connectors'
mapTrailURL = baseURL + '/map-trails'
Expand All @@ -51,7 +51,7 @@ def save_mountain_to_database(mapInfo: MapInfo):
for idx, coordinate in enumerate(e.geometry.coords):
lat = coordinate[1]
long = coordinate[0]
mapConnectorPoint = {'latitude': lat, 'longitude': long, 'time': [], 'mapConnectorId': mapConnector.json().get('id'), 'order': idx}
mapConnectorPoint = {'latitude': lat, 'longitude': long, 'time': [0.0], 'mapConnectorId': mapConnector.json().get('id'), 'order': idx}
mc = requests.post(mapPointURL, json= mapConnectorPoint)
else :
print(e.name)
Expand All @@ -65,11 +65,11 @@ def save_mountain_to_database(mapInfo: MapInfo):
for idx, coordinate in enumerate(e.geometry.coords):
lat = coordinate[1]
long = coordinate[0]
mapTrailPoint = {'latitude': lat, 'longitude': long, 'time': [], 'mapTrailId': mapTrail.json().get('id'), 'order': idx}
mapTrailPoint = {'latitude': lat, 'longitude': long, 'time': [0.0], 'mapTrailId': mapTrail.json().get('id'), 'order': idx}
mt = requests.post(mapPointURL, json= mapTrailPoint)
print("Completed " + str(index) + " out of " + str(len(list(folder.features()))) + " " + folder.name + " trails")

mountains = [sugarloaf]
mountains = [sugarloaf, sr]

for mountain in mountains:
save_mountain_to_database(mountain)
11 changes: 6 additions & 5 deletions TrailblazerIOS/API/PointAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Foundation
extension APIHandler {
func updatePointTime(point: PointTimeUpdateData, completion: @escaping (Result<Point, Error>) -> Void)
{
let url = URL(string: "\(self.baseURL)/api/users/\(point.id)")!
let url = URL(string: "\(self.baseURL)/api/points/\(point.id)")!

let encoder = JSONEncoder()

Expand All @@ -22,11 +22,12 @@ extension APIHandler {
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
let decoder = JSONDecoder()
if let point = try? decoder.decode(Point.self, from: data) {
do {
let point = try decoder.decode(Point.self, from: data)
completion(.success(point))
} else {
completion(.failure(DecodingErrors.pointDecodingError))
print("Could not update user")
} catch {
print("Could not update point")
completion(.failure(error))
}
}
}.resume()
Expand Down
4 changes: 2 additions & 2 deletions TrailblazerIOS/Models/Point.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ struct Point: Codable {
var latitude: Float
var longitude: Float
var distance: Float?
var time: [Float] = []
var time: [Double] = []
var order: Int
}

struct PointTimeUpdateData: Codable{
var id: String
var time: [Float]
var time: [Double]

}
28 changes: 18 additions & 10 deletions TrailblazerIOS/Singletons/MapInterpreter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ final class MapInterpreter: NSObject {
var distanceGraph = EdgeWeightedDigraph<ImageAnnotation>()
var baseLiftVertexes = [Vertex<ImageAnnotation>]()
let baseURL = APIHandler.shared.baseURL

var trailReports = [TrailReport]()
func createMap(map: Map)
{
self.mapView.removeOverlays(self.mapView.overlays)
Expand Down Expand Up @@ -47,16 +47,18 @@ final class MapInterpreter: NSObject {
{
coordinates.append(CLLocationCoordinate2D(latitude: Double(point.latitude), longitude: Double(point.longitude)))
pointIds.append(point.id!)
trailTimes.append(point.time as! [Double])
trailTimes.append(point.time)
}

let polyline = CustomPolyline(coordinates: coordinates, count: coordinates.count)
polyline.title = trail.name
polyline.color = color

let initialAnnotation = createAnnotation(title: trail.name, latitude: coordinates[0].latitude, longitude: coordinates[0].longitude, difficulty: difficulty)
initialAnnotation.id = trail.points[0].id
initialAnnotation.trailTimes = trailTimes
initialAnnotation.ids = pointIds
initialAnnotation.times = trail.points[0].time
self.mapView.addAnnotation(initialAnnotation)
polyline.initialAnnotation = initialAnnotation
polylines.append(polyline)
Expand All @@ -71,13 +73,15 @@ final class MapInterpreter: NSObject {
{
coordinates.append(CLLocationCoordinate2D(latitude: Double(point.latitude), longitude: Double(point.longitude)))
pointIds.append(point.id!)
trailTimes.append(point.time as! [Double])
trailTimes.append(point.time)
}

let initialAnnotation = createAnnotation(title: connector.name, latitude: coordinates[0].latitude, longitude: coordinates[0].longitude, difficulty: .easy)
initialAnnotation.id = connector.points[0].id
initialAnnotation.isConnector = true
initialAnnotation.trailTimes = trailTimes
initialAnnotation.ids = pointIds
initialAnnotation.times = connector.points[0].time

let polyline = CustomPolyline(coordinates: coordinates, count: coordinates.count)
polyline.title = connector.name
Expand All @@ -98,14 +102,17 @@ final class MapInterpreter: NSObject {
private func createVertices(polylines: [CustomPolyline]) -> [Vertex<ImageAnnotation>] {
var foundTrails : [String] = []
var vertices = [Vertex<ImageAnnotation>]()
self.mapView.removeAnnotations(self.mapView.overlays)
self.baseLiftVertexes.removeAll()

for polylineIndex in 0...polylines.count - 1
{
guard let initialAnnotation = polylines[polylineIndex].initialAnnotation else {
let overlay = polylines[polylineIndex]

guard let initialAnnotation = overlay.initialAnnotation else {
print("Polyline Configured Incorrectly")
continue
}
let overlay = polylines[polylineIndex]
if !foundTrails.contains(overlay.title!)
{
self.mapView.addAnnotation(initialAnnotation)
Expand All @@ -119,9 +126,9 @@ final class MapInterpreter: NSObject {
for index in 0..<overlay.pointCount
{
vertex = Vertex<ImageAnnotation>(createAnnotation(title: overlay.title!, latitude: overlay.points()[index].coordinate.latitude, longitude: overlay.points()[index].coordinate.longitude, difficulty: overlay.initialAnnotation!.difficulty!))
vertex.value.id = overlay.initialAnnotation?.ids![index]
vertex.value.times = overlay.initialAnnotation?.trailTimes![index]
vertex.value.isConnector = overlay.initialAnnotation!.isConnector
vertex.value.id = initialAnnotation.ids![index]
vertex.value.times = initialAnnotation.trailTimes![index]
vertex.value.isConnector = initialAnnotation.isConnector
vertices.append(vertex)
}
}
Expand Down Expand Up @@ -173,7 +180,7 @@ final class MapInterpreter: NSObject {

private func timeWeightCalculation(_ vertex1: Vertex<ImageAnnotation>, _ vertex2: Vertex<ImageAnnotation>) -> Double {
let weightArray = vertex2.value.times!
return weightArray.reduce(0.0, +) / Double(weightArray.count + 1)
return Double(weightArray.reduce(0.0, +) / Double(weightArray.count + 1))
}

private func addIntersectingPointsTo(graph: EdgeWeightedDigraph<ImageAnnotation>)
Expand Down Expand Up @@ -231,8 +238,9 @@ final class MapInterpreter: NSObject {
guard InteractiveMapViewController.currentUser.alertSettings.contains(report.type) else { continue }
NotificationCenter.default.post(name: Notification.Name.Names.createNotification, object: nil, userInfo: ["report": report])
}
self.trailReports = trailReports
NotificationCenter.default.post(name: Notification.Name.Names.configureTrailSelector, object: nil)
NotificationCenter.default.post(Notification(name: Notification.Name.Names.updateInitialRegion, userInfo: ["initialRegionLatitude": Double(map.initialLocationLatitude), "initialRegionLongitude": Double(map.initialLocationLongitude), "trailReports": trailReports]))
NotificationCenter.default.post(Notification(name: Notification.Name.Names.updateInitialRegion, userInfo: ["initialRegionLatitude": Double(map.initialLocationLatitude), "initialRegionLongitude": Double(map.initialLocationLongitude)]))

})
}
Expand Down
Loading

0 comments on commit 23f4eaa

Please sign in to comment.