Skip to content

Commit

Permalink
misc cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
voynow committed Nov 10, 2024
1 parent 08b3e96 commit ffa1f66
Show file tree
Hide file tree
Showing 6 changed files with 2,443 additions and 65 deletions.
12 changes: 0 additions & 12 deletions lambda/src/frontend_router.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import time
from typing import Callable, Dict, Optional

import jwt
Expand All @@ -7,7 +6,6 @@
from src.activities import get_weekly_summaries
from src.auth_manager import get_strava_client
from src.supabase_client import (
get_training_week,
get_user,
get_user_auth,
update_preferences,
Expand All @@ -17,15 +15,6 @@
from src.update_pipeline import update_training_week


def get_training_week_handler(athlete_id: str, payload: dict) -> dict:
"""Handle get_training_week request."""
training_week = get_training_week(athlete_id)
return {
"success": True,
"training_week": training_week.json(),
}


def get_profile_handler(athlete_id: str, payload: dict) -> dict:
"""Handle get_profile request."""
user = get_user(athlete_id)
Expand Down Expand Up @@ -89,7 +78,6 @@ def update_device_token_handler(athlete_id: str, payload: dict) -> dict:


METHOD_HANDLERS: Dict[str, Callable[[str, Optional[dict]], dict]] = {
"get_training_week": get_training_week_handler,
"get_profile": get_profile_handler,
"update_preferences": update_preferences_handler,
"get_weekly_summaries": get_weekly_summaries_handler,
Expand Down
4 changes: 2 additions & 2 deletions mobile/mobile.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.6;
MARKETING_VERSION = 1.7;
PRODUCT_BUNDLE_IDENTIFIER = voynow.mobile;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
Expand Down Expand Up @@ -313,7 +313,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.6;
MARKETING_VERSION = 1.7;
PRODUCT_BUNDLE_IDENTIFIER = voynow.mobile;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
Expand Down
85 changes: 39 additions & 46 deletions mobile/mobile/APIManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ class APIManager {
private let apiURL = "http://trackflow-alb-499532887.us-east-1.elb.amazonaws.com"

func fetchProfileData(token: String, completion: @escaping (Result<ProfileData, Error>) -> Void) {
let startTime = CFAbsoluteTimeGetCurrent()
let body: [String: Any] = ["jwt_token": token, "method": "get_profile"]
performRequest(body: body, responseType: ProfileResponse.self) { result in
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("APIManager: fetchProfileData took \(timeElapsed) seconds")

switch result {
case .success(let response):
if response.success, let profile = response.profile {
Expand Down Expand Up @@ -53,52 +57,24 @@ class APIManager {

session.dataTask(with: request) { data, response, error in
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("fetchTrainingWeekData took \(timeElapsed) seconds")
print("APIManager: fetchTrainingWeekData took \(timeElapsed) seconds")

if let httpResponse = response as? HTTPURLResponse {
if let httpResponse = response as? HTTPURLResponse,
!(200..<300).contains(httpResponse.statusCode)
{
let message: String
switch httpResponse.statusCode {
case 401:
completion(
.failure(
NSError(
domain: "",
code: 401,
userInfo: [NSLocalizedDescriptionKey: "Invalid or expired token"]
)))
return
case 403:
completion(
.failure(
NSError(
domain: "",
code: 403,
userInfo: [
NSLocalizedDescriptionKey:
"Access forbidden - you don't have permission to access this resource"
]
)))
return
case 404:
completion(
.failure(
NSError(
domain: "",
code: 404,
userInfo: [NSLocalizedDescriptionKey: "Training week not found"]
)))
return
case 200..<300:
break
default:
completion(
.failure(
NSError(
domain: "",
code: httpResponse.statusCode,
userInfo: [NSLocalizedDescriptionKey: "Server error"]
)))
return
case 401: message = "Invalid or expired token"
case 403: message = "Access forbidden - you don't have permission to access this resource"
case 404: message = "Training week not found"
default: message = "Server error"
}
completion(
.failure(
NSError(
domain: "", code: httpResponse.statusCode,
userInfo: [NSLocalizedDescriptionKey: message])))
return
}

if let error = error {
Expand All @@ -119,9 +95,6 @@ class APIManager {
completion(.success(trainingWeek))
} catch {
print("Decoding error: \(error)")
if let json = try? JSONSerialization.jsonObject(with: data, options: []) {
print("JSON: \(json)")
}
completion(.failure(error))
}
}.resume()
Expand All @@ -130,6 +103,7 @@ class APIManager {
func savePreferences(
token: String, preferences: Preferences, completion: @escaping (Result<Void, Error>) -> Void
) {
let startTime = CFAbsoluteTimeGetCurrent()
let idealTrainingWeek = preferences.idealTrainingWeek?.map { day in
return [
"day": day.day.rawValue,
Expand All @@ -151,6 +125,9 @@ class APIManager {
]

performRequest(body: body, responseType: SavePreferencesResponse.self) { result in
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("APIManager: savePreferences took \(timeElapsed) seconds")

switch result {
case .success(let response):
if response.success {
Expand All @@ -168,8 +145,12 @@ class APIManager {
}

func refreshToken(token: String, completion: @escaping (Result<String, Error>) -> Void) {
let startTime = CFAbsoluteTimeGetCurrent()
let body: [String: Any] = ["jwt_token": token, "method": "refresh_token"]
performRequest(body: body, responseType: RefreshTokenResponse.self) { result in
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("APIManager: refreshToken took \(timeElapsed) seconds")

switch result {
case .success(let response):
if response.success, let newToken = response.jwt_token {
Expand All @@ -190,9 +171,13 @@ class APIManager {
func fetchWeeklySummaries(
token: String, completion: @escaping (Result<[WeekSummary], Error>) -> Void
) {
let startTime = CFAbsoluteTimeGetCurrent()
let body: [String: Any] = ["jwt_token": token, "method": "get_weekly_summaries"]

performRequest(body: body, responseType: WeeklySummariesResponse.self) { result in
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("APIManager: fetchWeeklySummaries took \(timeElapsed) seconds")

switch result {
case .success(let response):
if response.success, let summariesStrings = response.weekly_summaries {
Expand Down Expand Up @@ -260,8 +245,12 @@ class APIManager {
}

func startOnboarding(token: String, completion: @escaping (Result<Void, Error>) -> Void) {
let startTime = CFAbsoluteTimeGetCurrent()
let body: [String: Any] = ["jwt_token": token, "method": "start_onboarding"]
performRequest(body: body, responseType: GenericResponse.self) { result in
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("APIManager: startOnboarding took \(timeElapsed) seconds")

switch result {
case .success(let response):
if response.success {
Expand All @@ -281,13 +270,17 @@ class APIManager {
func updateDeviceToken(
token: String, deviceToken: String, completion: @escaping (Result<Void, Error>) -> Void
) {
let startTime = CFAbsoluteTimeGetCurrent()
let body: [String: Any] = [
"jwt_token": token,
"payload": ["device_token": deviceToken],
"method": "update_device_token",
]

performRequest(body: body, responseType: GenericResponse.self) { result in
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("APIManager: updateDeviceToken took \(timeElapsed) seconds")

switch result {
case .success(let response):
if response.success {
Expand Down
12 changes: 7 additions & 5 deletions mobile/mobile/NotificationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,32 @@ import os
class NotificationManager {
static let shared = NotificationManager()
private var deviceToken: String?
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "com.trackflow", category: "NotificationManager")
private let logger = Logger(
subsystem: Bundle.main.bundleIdentifier ?? "com.trackflow", category: "NotificationManager")

private init() {}

func updateDeviceToken(_ token: String) {
deviceToken = token
logger.info("Received new device token")
logger.info("NotificationManager: Received new device token")
sendTokenToServer()
}

private func sendTokenToServer() {
guard let token = deviceToken,
let jwtToken = UserDefaults.standard.string(forKey: "jwt_token")
else {
logger.error("Missing device token or JWT token")
logger.error("NotificationManager: Missing device token or JWT token")
return
}

APIManager.shared.updateDeviceToken(token: jwtToken, deviceToken: token) { result in
switch result {
case .success:
self.logger.info("Successfully registered device token with server")
self.logger.info("NotificationManager: Successfully registered device token with server")
case .failure(let error):
self.logger.error("Failed to register device token: \(error.localizedDescription)")
self.logger.error(
"NotificationManager: Failed to register device token: \(error.localizedDescription)")
}
}
}
Expand Down
Loading

0 comments on commit ffa1f66

Please sign in to comment.