Compare commits

...

19 Commits

Author SHA1 Message Date
b8f874a433 Cleanup 2025-10-05 12:42:02 -06:00
4bbd422c09 Added a proper set of Unit Tests for each sub-project
All checks were successful
OpenClimb Docker Deploy / build-and-push (push) Successful in 2m28s
2025-10-03 20:55:04 -06:00
4e42985135 1.2.2 - "Bug fixes and improvements" 2025-10-01 21:34:22 -06:00
ba1a7117d9 Create PRIVACY.md 2025-09-29 14:11:01 -06:00
1980ff802a Merge remote-tracking branch 'origin/main' 2025-09-29 14:03:51 -06:00
73c4e41cac Android 1.7.1 - Added a clear sync indicator 2025-09-29 14:03:30 -06:00
3ccd0ec7ea oops 2025-09-29 13:47:57 -06:00
8fbb40d453 iOS 1.2.1 - Better auto sync and sync indicator 2025-09-29 13:47:50 -06:00
016d427ff8 Update sync/.env.example
All checks were successful
OpenClimb Docker Deploy / build-and-push (push) Successful in 2m22s
2025-09-29 17:49:25 +00:00
7cbb333287 Update sync/docker-compose.yml
Some checks failed
OpenClimb Docker Deploy / build-and-push (push) Has been cancelled
2025-09-29 17:47:09 +00:00
2160ce30bd Update README.md 2025-09-29 05:46:47 +00:00
de21e3270e Update README.md 2025-09-29 05:46:23 +00:00
f6e1cdcb5b Update README.md 2025-09-28 23:45:38 -06:00
fab587c351 Cleanup from dev
All checks were successful
OpenClimb Docker Deploy / build-and-push (push) Successful in 2m22s
2025-09-28 23:43:19 -06:00
d570b8a70c Merge pull request 'Massive Sync Update!' (#5) from sync-server into main
All checks were successful
OpenClimb Docker Deploy / build-and-push (push) Successful in 1m26s
Reviewed-on: atridad/OpenClimb#5
2025-09-29 05:35:12 +00:00
c676e25a3d Sync server name change
Some checks failed
OpenClimb Docker Deploy / build-and-push (pull_request) Has been cancelled
2025-09-28 23:34:37 -06:00
56c501cef6 Version bumps 2025-09-28 23:33:05 -06:00
f7f1fba9aa Added proper CI
All checks were successful
OpenClimb Docker Deploy / build-and-push (pull_request) Successful in 2m3s
2025-09-28 23:29:44 -06:00
6e490d1598 Sync Server DONE! 2025-09-28 23:12:46 -06:00
86 changed files with 8836 additions and 1831 deletions

38
.github/workflows/deploy.yml vendored Normal file
View File

@@ -0,0 +1,38 @@
name: OpenClimb Docker Deploy
on:
push:
branches: [main]
paths:
- "sync/**"
- ".github/workflows/deploy.yml"
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Container Registry
uses: docker/login-action@v2
with:
registry: ${{ secrets.REPO_HOST }}
username: ${{ github.repository_owner }}
password: ${{ secrets.DEPLOY_TOKEN }}
- name: Build and push sync-server
uses: docker/build-push-action@v4
with:
context: ./sync
file: ./sync/Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ secrets.REPO_HOST }}/${{ github.repository_owner }}/openclimb-sync:${{ github.sha }}
${{ secrets.REPO_HOST }}/${{ github.repository_owner }}/openclimb-sync:latest

21
PRIVACY.md Normal file
View File

@@ -0,0 +1,21 @@
# Privacy Policy
**Last updated: September 29, 2025**
This Privacy Policy describes our policies and procedures regarding the collection, use, and disclosure of your information when you use my software.
## No Data Collection
I do not collect any personal information, analytics, or data of any kind. This software is designed to be self-hosted or run entirely offline.
All data generated by or used with this software remains on your local machine or self-hosted environment under your control. I have no access to it.
## No Tracking or Analytics
This software does not use cookies, tracking pixels, or any other analytics or tracking mechanisms. Your usage of the software is completely private.
## Contact Us
If you have any questions about this Privacy Policy, you can contact me:
* **By email:** me@atri.dad

View File

@@ -2,11 +2,6 @@
This is a FOSS app meant to help climbers track their sessions, routes/problems, and overall progress. This app is offline-only and requires no special permissions to run. Its built using Jetpack Compose with Material You support on Android and SwiftUI on iOS.
## Versions
- Android:1.4.2
- iOS: 1.0.1
## Download
For Android do one of the following:
@@ -18,6 +13,30 @@ For iOS:
Download from the AppStore [here](https://apps.apple.com/ca/app/openclimb/id6752592783)!
## Self-Hosted Sync Server
You can run your own sync server to keep your data in sync across devices. The server is lightweight and easy to set up using Docker.
### Quick Start with Docker Compose
1. Create a `.env` file with your configuration:
```
IMAGE=git.atri.dad/atridad/openclimb-sync:latest
APP_PORT=8080
AUTH_TOKEN=your-secure-auth-token-here
DATA_FILE=/data/openclimb.json
IMAGES_DIR=/data/images
ROOT_DIR=./openclimb-data
```
2. Use the provided `docker-compose.yml` in the `sync/` directory:
```bash
cd sync/
docker-compose up -d
```
The server will be available at `http://localhost:8080`. Configure your clients with your server URL and auth token to start syncing.
## Requirements
- Android 12+ or iOS 17+

View File

@@ -16,8 +16,8 @@ android {
applicationId = "com.atridad.openclimb"
minSdk = 31
targetSdk = 36
versionCode = 27
versionName = "1.6.0"
versionCode = 29
versionName = "1.7.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -92,4 +92,6 @@ dependencies {
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}

View File

@@ -0,0 +1,98 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.ksp)
}
android {
namespace = "com.atridad.openclimb"
compileSdk = 36
defaultConfig {
applicationId = "com.atridad.openclimb"
minSdk = 31
targetSdk = 36
versionCode = 27
versionName = "1.6.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
java { toolchain { languageVersion.set(JavaLanguageVersion.of(17)) } }
buildFeatures { compose = true }
}
kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } }
dependencies {
// Core Android libraries
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
// Compose BOM and UI
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation(libs.androidx.material.icons.extended)
// Room Database
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
ksp(libs.androidx.room.compiler)
// Navigation
implementation(libs.androidx.navigation.compose)
// ViewModel
implementation(libs.androidx.lifecycle.viewmodel.compose)
// Serialization
implementation(libs.kotlinx.serialization.json)
// Coroutines
implementation(libs.kotlinx.coroutines.android)
// Image Loading
implementation(libs.coil.compose)
// Testing
testImplementation(libs.junit)
testImplementation(libs.mockk)
testImplementation(libs.kotlinx.coroutines.test)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(libs.androidx.test.core)
androidTestImplementation(libs.androidx.test.ext)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.androidx.test.rules)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}

View File

@@ -1,24 +0,0 @@
package com.atridad.openclimb
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.atridad.openclimb", appContext.packageName)
}
}

View File

@@ -8,6 +8,9 @@
android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.CAMERA" />
<!-- Permission for sync functionality -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Hardware features -->
<uses-feature android:name="android.hardware.camera" android:required="false" />

View File

@@ -3,7 +3,7 @@ package com.atridad.openclimb.data.format
import com.atridad.openclimb.data.model.*
import kotlinx.serialization.Serializable
/** Root structure for OpenClimb backup data */
// Root structure for OpenClimb backup data
@Serializable
data class ClimbDataBackup(
val exportedAt: String,
@@ -15,7 +15,7 @@ data class ClimbDataBackup(
val attempts: List<BackupAttempt>
)
/** Platform-neutral gym representation for backup/restore */
// Platform-neutral gym representation for backup/restore
@Serializable
data class BackupGym(
val id: String,
@@ -23,10 +23,11 @@ data class BackupGym(
val location: String? = null,
val supportedClimbTypes: List<ClimbType>,
val difficultySystems: List<DifficultySystem>,
@kotlinx.serialization.SerialName("customDifficultyGrades")
val customDifficultyGrades: List<String> = emptyList(),
val notes: String? = null,
val createdAt: String, // ISO 8601 format
val updatedAt: String // ISO 8601 format
val createdAt: String,
val updatedAt: String
) {
companion object {
/** Create BackupGym from native Android Gym model */
@@ -61,7 +62,7 @@ data class BackupGym(
}
}
/** Platform-neutral problem representation for backup/restore */
// Platform-neutral problem representation for backup/restore
@Serializable
data class BackupProblem(
val id: String,
@@ -74,10 +75,10 @@ data class BackupProblem(
val location: String? = null,
val imagePaths: List<String>? = null,
val isActive: Boolean = true,
val dateSet: String? = null, // ISO 8601 format
val dateSet: String? = null,
val notes: String? = null,
val createdAt: String, // ISO 8601 format
val updatedAt: String // ISO 8601 format
val createdAt: String,
val updatedAt: String
) {
companion object {
/** Create BackupProblem from native Android Problem model */
@@ -91,7 +92,9 @@ data class BackupProblem(
difficulty = problem.difficulty,
tags = problem.tags,
location = problem.location,
imagePaths = problem.imagePaths.ifEmpty { null },
imagePaths =
if (problem.imagePaths.isEmpty()) null
else problem.imagePaths.map { path -> path.substringAfterLast('/') },
isActive = problem.isActive,
dateSet = problem.dateSet,
notes = problem.notes,
@@ -127,19 +130,19 @@ data class BackupProblem(
}
}
/** Platform-neutral climb session representation for backup/restore */
// Platform-neutral climb session representation for backup/restore
@Serializable
data class BackupClimbSession(
val id: String,
val gymId: String,
val date: String, // ISO 8601 format
val startTime: String? = null, // ISO 8601 format
val endTime: String? = null, // ISO 8601 format
val duration: Long? = null, // Duration in seconds
val date: String,
val startTime: String? = null,
val endTime: String? = null,
val duration: Long? = null,
val status: SessionStatus,
val notes: String? = null,
val createdAt: String, // ISO 8601 format
val updatedAt: String // ISO 8601 format
val createdAt: String,
val updatedAt: String
) {
companion object {
/** Create BackupClimbSession from native Android ClimbSession model */
@@ -176,7 +179,7 @@ data class BackupClimbSession(
}
}
/** Platform-neutral attempt representation for backup/restore */
// Platform-neutral attempt representation for backup/restore
@Serializable
data class BackupAttempt(
val id: String,
@@ -185,10 +188,11 @@ data class BackupAttempt(
val result: AttemptResult,
val highestHold: String? = null,
val notes: String? = null,
val duration: Long? = null, // Duration in seconds
val restTime: Long? = null, // Rest time in seconds
val timestamp: String, // ISO 8601 format
val createdAt: String // ISO 8601 format
val duration: Long? = null,
val restTime: Long? = null,
val timestamp: String,
val createdAt: String,
val updatedAt: String
) {
companion object {
/** Create BackupAttempt from native Android Attempt model */

View File

@@ -0,0 +1,205 @@
package com.atridad.openclimb.data.migration
import android.content.Context
import android.util.Log
import com.atridad.openclimb.data.repository.ClimbRepository
import com.atridad.openclimb.utils.ImageNamingUtils
import com.atridad.openclimb.utils.ImageUtils
import kotlinx.coroutines.flow.first
/**
* Service responsible for migrating images to use consistent naming convention across platforms.
* This ensures that iOS and Android use the same image filenames for sync compatibility.
*/
class ImageMigrationService(private val context: Context, private val repository: ClimbRepository) {
companion object {
private const val TAG = "ImageMigrationService"
private const val MIGRATION_PREF_KEY = "image_naming_migration_completed"
}
/**
* Performs a complete migration of all images in the system to use consistent naming. This
* should be called once during app startup after the naming convention is implemented.
*/
suspend fun performFullMigration(): ImageMigrationResult {
Log.i(TAG, "Starting full image naming migration")
val prefs = context.getSharedPreferences("openclimb_migration", Context.MODE_PRIVATE)
if (prefs.getBoolean(MIGRATION_PREF_KEY, false)) {
Log.i(TAG, "Image migration already completed, skipping")
return ImageMigrationResult.AlreadyCompleted
}
try {
val allProblems = repository.getAllProblems().first()
val migrationResults = mutableMapOf<String, String>()
var migratedCount = 0
var errorCount = 0
Log.i(TAG, "Found ${allProblems.size} problems to check for image migration")
for (problem in allProblems) {
if (problem.imagePaths.isNotEmpty()) {
Log.d(
TAG,
"Migrating images for problem '${problem.name}': ${problem.imagePaths}"
)
try {
val problemMigrations =
ImageUtils.migrateImageNaming(
context = context,
problemId = problem.id,
currentImagePaths = problem.imagePaths
)
if (problemMigrations.isNotEmpty()) {
migrationResults.putAll(problemMigrations)
migratedCount += problemMigrations.size
// Update image paths
val newImagePaths =
problem.imagePaths.map { oldPath ->
problemMigrations[oldPath] ?: oldPath
}
val updatedProblem = problem.copy(imagePaths = newImagePaths)
repository.insertProblem(updatedProblem)
Log.d(
TAG,
"Updated problem '${problem.name}' with ${problemMigrations.size} migrated images"
)
}
} catch (e: Exception) {
Log.e(
TAG,
"Failed to migrate images for problem '${problem.name}': ${e.message}",
e
)
errorCount++
}
}
}
// Mark migration as completed
prefs.edit().putBoolean(MIGRATION_PREF_KEY, true).apply()
Log.i(
TAG,
"Image migration completed: $migratedCount images migrated, $errorCount errors"
)
return ImageMigrationResult.Success(
totalMigrated = migratedCount,
errors = errorCount,
migrations = migrationResults
)
} catch (e: Exception) {
Log.e(TAG, "Image migration failed: ${e.message}", e)
return ImageMigrationResult.Failed(e.message ?: "Unknown error")
}
}
/** Validates that all images in the system follow the consistent naming convention. */
suspend fun validateImageNaming(): ValidationResult {
try {
val allProblems = repository.getAllProblems().first()
val validImages = mutableListOf<String>()
val invalidImages = mutableListOf<String>()
val missingImages = mutableListOf<String>()
for (problem in allProblems) {
for (imagePath in problem.imagePaths) {
val filename = imagePath.substringAfterLast('/')
// Check if file exists
val imageFile = ImageUtils.getImageFile(context, imagePath)
if (!imageFile.exists()) {
missingImages.add(imagePath)
continue
}
// Check if filename follows convention
if (ImageNamingUtils.isValidImageFilename(filename)) {
validImages.add(imagePath)
} else {
invalidImages.add(imagePath)
}
}
}
return ValidationResult(
totalImages = validImages.size + invalidImages.size + missingImages.size,
validImages = validImages,
invalidImages = invalidImages,
missingImages = missingImages
)
} catch (e: Exception) {
Log.e(TAG, "Image validation failed: ${e.message}", e)
return ValidationResult(
totalImages = 0,
validImages = emptyList(),
invalidImages = emptyList(),
missingImages = emptyList()
)
}
}
/** Migrates images for a specific problem during sync operations. */
suspend fun migrateProblemImages(
problemId: String,
currentImagePaths: List<String>
): Map<String, String> {
return try {
ImageUtils.migrateImageNaming(context, problemId, currentImagePaths)
} catch (e: Exception) {
Log.e(TAG, "Failed to migrate images for problem $problemId: ${e.message}", e)
emptyMap()
}
}
/**
* Cleans up any orphaned image files that don't follow our naming convention and aren't
* referenced by any problems.
*/
suspend fun cleanupOrphanedImages() {
try {
val allProblems = repository.getAllProblems().first()
val referencedPaths = allProblems.flatMap { it.imagePaths }.toSet()
ImageUtils.cleanupOrphanedImages(context, referencedPaths)
Log.i(TAG, "Orphaned image cleanup completed")
} catch (e: Exception) {
Log.e(TAG, "Failed to cleanup orphaned images: ${e.message}", e)
}
}
}
/** Result of an image migration operation */
sealed class ImageMigrationResult {
object AlreadyCompleted : ImageMigrationResult()
data class Success(
val totalMigrated: Int,
val errors: Int,
val migrations: Map<String, String>
) : ImageMigrationResult()
data class Failed(val error: String) : ImageMigrationResult()
}
/** Result of image naming validation */
data class ValidationResult(
val totalImages: Int,
val validImages: List<String>,
val invalidImages: List<String>,
val missingImages: List<String>
) {
val isAllValid: Boolean
get() = invalidImages.isEmpty() && missingImages.isEmpty()
val validPercentage: Double
get() = if (totalImages == 0) 100.0 else (validImages.size.toDouble() / totalImages) * 100
}

View File

@@ -4,8 +4,8 @@ import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.atridad.openclimb.utils.DateFormatUtils
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
@Serializable
enum class AttemptResult {
@@ -16,63 +16,59 @@ enum class AttemptResult {
}
@Entity(
tableName = "attempts",
foreignKeys = [
ForeignKey(
entity = ClimbSession::class,
parentColumns = ["id"],
childColumns = ["sessionId"],
onDelete = ForeignKey.CASCADE
),
ForeignKey(
entity = Problem::class,
parentColumns = ["id"],
childColumns = ["problemId"],
onDelete = ForeignKey.CASCADE
)
],
indices = [
Index(value = ["sessionId"]),
Index(value = ["problemId"])
]
tableName = "attempts",
foreignKeys =
[
ForeignKey(
entity = ClimbSession::class,
parentColumns = ["id"],
childColumns = ["sessionId"],
onDelete = ForeignKey.CASCADE
),
ForeignKey(
entity = Problem::class,
parentColumns = ["id"],
childColumns = ["problemId"],
onDelete = ForeignKey.CASCADE
)],
indices = [Index(value = ["sessionId"]), Index(value = ["problemId"])]
)
@Serializable
data class Attempt(
@PrimaryKey
val id: String,
val sessionId: String,
val problemId: String,
val result: AttemptResult,
val highestHold: String? = null, // Description of the highest hold reached
val notes: String? = null,
val duration: Long? = null, // Attempt duration in seconds
val restTime: Long? = null, // Rest time before this attempt in seconds
val timestamp: String, // When this attempt was made
val createdAt: String
@PrimaryKey val id: String,
val sessionId: String,
val problemId: String,
val result: AttemptResult,
val highestHold: String? = null,
val notes: String? = null,
val duration: Long? = null,
val restTime: Long? = null,
val timestamp: String,
val createdAt: String
) {
companion object {
fun create(
sessionId: String,
problemId: String,
result: AttemptResult,
highestHold: String? = null,
notes: String? = null,
duration: Long? = null,
restTime: Long? = null,
timestamp: String = LocalDateTime.now().toString()
sessionId: String,
problemId: String,
result: AttemptResult,
highestHold: String? = null,
notes: String? = null,
duration: Long? = null,
restTime: Long? = null,
timestamp: String = DateFormatUtils.nowISO8601()
): Attempt {
val now = LocalDateTime.now().toString()
val now = DateFormatUtils.nowISO8601()
return Attempt(
id = java.util.UUID.randomUUID().toString(),
sessionId = sessionId,
problemId = problemId,
result = result,
highestHold = highestHold,
notes = notes,
duration = duration,
restTime = restTime,
timestamp = timestamp,
createdAt = now
id = java.util.UUID.randomUUID().toString(),
sessionId = sessionId,
problemId = problemId,
result = result,
highestHold = highestHold,
notes = notes,
duration = duration,
restTime = restTime,
timestamp = timestamp,
createdAt = now
)
}
}

View File

@@ -4,8 +4,8 @@ import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.atridad.openclimb.utils.DateFormatUtils
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
@Serializable
enum class SessionStatus {
@@ -15,66 +15,65 @@ enum class SessionStatus {
}
@Entity(
tableName = "climb_sessions",
foreignKeys = [
ForeignKey(
entity = Gym::class,
parentColumns = ["id"],
childColumns = ["gymId"],
onDelete = ForeignKey.CASCADE
)
],
indices = [Index(value = ["gymId"])]
tableName = "climb_sessions",
foreignKeys =
[
ForeignKey(
entity = Gym::class,
parentColumns = ["id"],
childColumns = ["gymId"],
onDelete = ForeignKey.CASCADE
)],
indices = [Index(value = ["gymId"])]
)
@Serializable
data class ClimbSession(
@PrimaryKey
val id: String,
val gymId: String,
val date: String,
val startTime: String? = null,
val endTime: String? = null,
val duration: Long? = null,
val status: SessionStatus = SessionStatus.ACTIVE,
val notes: String? = null,
val createdAt: String,
val updatedAt: String
@PrimaryKey val id: String,
val gymId: String,
val date: String,
val startTime: String? = null,
val endTime: String? = null,
val duration: Long? = null,
val status: SessionStatus = SessionStatus.ACTIVE,
val notes: String? = null,
val createdAt: String,
val updatedAt: String
) {
companion object {
fun create(
gymId: String,
notes: String? = null
): ClimbSession {
val now = LocalDateTime.now().toString()
fun create(gymId: String, notes: String? = null): ClimbSession {
val now = DateFormatUtils.nowISO8601()
return ClimbSession(
id = java.util.UUID.randomUUID().toString(),
gymId = gymId,
date = now,
startTime = now,
status = SessionStatus.ACTIVE,
notes = notes,
createdAt = now,
updatedAt = now
id = java.util.UUID.randomUUID().toString(),
gymId = gymId,
date = now,
startTime = now,
status = SessionStatus.ACTIVE,
notes = notes,
createdAt = now,
updatedAt = now
)
}
fun ClimbSession.complete(): ClimbSession {
val endTime = LocalDateTime.now().toString()
val durationMinutes = if (startTime != null) {
try {
val start = LocalDateTime.parse(startTime)
val end = LocalDateTime.parse(endTime)
java.time.Duration.between(start, end).toMinutes()
} catch (_: Exception) {
null
}
} else null
val endTime = DateFormatUtils.nowISO8601()
val durationMinutes =
if (startTime != null) {
try {
val start = DateFormatUtils.parseISO8601(startTime)
val end = DateFormatUtils.parseISO8601(endTime)
if (start != null && end != null) {
java.time.Duration.between(start, end).toMinutes()
} else null
} catch (_: Exception) {
null
}
} else null
return this.copy(
endTime = endTime,
duration = durationMinutes,
status = SessionStatus.COMPLETED,
updatedAt = LocalDateTime.now().toString()
endTime = endTime,
duration = durationMinutes,
status = SessionStatus.COMPLETED,
updatedAt = DateFormatUtils.nowISO8601()
)
}
}

View File

@@ -5,77 +5,197 @@ import kotlinx.serialization.Serializable
@Serializable
enum class DifficultySystem {
// Bouldering
V_SCALE, // V-Scale (VB - V17)
FONT, // Fontainebleau (3 - 8C+)
V_SCALE,
FONT,
// Rope
YDS, // Yosemite Decimal System (5.0 - 5.15d)
// Custom difficulty systems
YDS,
CUSTOM;
/**
* Get the display name for the UI
*/
fun getDisplayName(): String = when (this) {
V_SCALE -> "V Scale"
FONT -> "Font Scale"
YDS -> "YDS (Yosemite)"
CUSTOM -> "Custom"
}
/**
* Check if this system is for bouldering
*/
fun isBoulderingSystem(): Boolean = when (this) {
V_SCALE, FONT -> true
YDS -> false
CUSTOM -> true // Custom is available for all
}
/**
* Check if this system is for rope climbing
*/
fun isRopeSystem(): Boolean = when (this) {
YDS -> true
V_SCALE, FONT -> false
CUSTOM -> true
}
/**
* Get available grades for this system
*/
fun getAvailableGrades(): List<String> = when (this) {
V_SCALE -> listOf("VB", "V0", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17")
FONT -> listOf("3", "4A", "4B", "4C", "5A", "5B", "5C", "6A", "6A+", "6B", "6B+", "6C", "6C+", "7A", "7A+", "7B", "7B+", "7C", "7C+", "8A", "8A+", "8B", "8B+", "8C", "8C+")
YDS -> listOf("5.0", "5.1", "5.2", "5.3", "5.4", "5.5", "5.6", "5.7", "5.8", "5.9", "5.10a", "5.10b", "5.10c", "5.10d", "5.11a", "5.11b", "5.11c", "5.11d", "5.12a", "5.12b", "5.12c", "5.12d", "5.13a", "5.13b", "5.13c", "5.13d", "5.14a", "5.14b", "5.14c", "5.14d", "5.15a", "5.15b", "5.15c", "5.15d")
CUSTOM -> emptyList()
}
/** Get the display name for the UI */
fun getDisplayName(): String =
when (this) {
V_SCALE -> "V Scale"
FONT -> "Font Scale"
YDS -> "YDS (Yosemite)"
CUSTOM -> "Custom"
}
/** Check if this system is for bouldering */
fun isBoulderingSystem(): Boolean =
when (this) {
V_SCALE, FONT -> true
YDS -> false
CUSTOM -> true
}
/** Check if this system is for rope climbing */
fun isRopeSystem(): Boolean =
when (this) {
YDS -> true
V_SCALE, FONT -> false
CUSTOM -> true
}
/** Get available grades for this system */
fun getAvailableGrades(): List<String> =
when (this) {
V_SCALE ->
listOf(
"VB",
"V0",
"V1",
"V2",
"V3",
"V4",
"V5",
"V6",
"V7",
"V8",
"V9",
"V10",
"V11",
"V12",
"V13",
"V14",
"V15",
"V16",
"V17"
)
FONT ->
listOf(
"3",
"4A",
"4B",
"4C",
"5A",
"5B",
"5C",
"6A",
"6A+",
"6B",
"6B+",
"6C",
"6C+",
"7A",
"7A+",
"7B",
"7B+",
"7C",
"7C+",
"8A",
"8A+",
"8B",
"8B+",
"8C",
"8C+"
)
YDS ->
listOf(
"5.0",
"5.1",
"5.2",
"5.3",
"5.4",
"5.5",
"5.6",
"5.7",
"5.8",
"5.9",
"5.10a",
"5.10b",
"5.10c",
"5.10d",
"5.11a",
"5.11b",
"5.11c",
"5.11d",
"5.12a",
"5.12b",
"5.12c",
"5.12d",
"5.13a",
"5.13b",
"5.13c",
"5.13d",
"5.14a",
"5.14b",
"5.14c",
"5.14d",
"5.15a",
"5.15b",
"5.15c",
"5.15d"
)
CUSTOM -> emptyList()
}
companion object {
/**
* Get all difficulty systems based on type
*/
fun getSystemsForClimbType(climbType: ClimbType): List<DifficultySystem> = when (climbType) {
ClimbType.BOULDER -> entries.filter { it.isBoulderingSystem() }
ClimbType.ROPE -> entries.filter { it.isRopeSystem() }
}
/** Get all difficulty systems based on type */
fun getSystemsForClimbType(climbType: ClimbType): List<DifficultySystem> =
when (climbType) {
ClimbType.BOULDER -> entries.filter { it.isBoulderingSystem() }
ClimbType.ROPE -> entries.filter { it.isRopeSystem() }
}
}
}
@Serializable
data class DifficultyGrade(
val system: DifficultySystem,
val grade: String,
val numericValue: Int
) {
data class DifficultyGrade(val system: DifficultySystem, val grade: String, val numericValue: Int) {
constructor(
system: DifficultySystem,
grade: String
) : this(system = system, grade = grade, numericValue = calculateNumericValue(system, grade))
companion object {
private fun calculateNumericValue(system: DifficultySystem, grade: String): Int {
return when (system) {
DifficultySystem.V_SCALE -> {
if (grade == "VB") 0 else grade.removePrefix("V").toIntOrNull() ?: 0
}
DifficultySystem.YDS -> {
when {
grade.startsWith("5.10") ->
10 + (grade.getOrNull(4)?.toString()?.hashCode()?.rem(4) ?: 0)
grade.startsWith("5.11") ->
14 + (grade.getOrNull(4)?.toString()?.hashCode()?.rem(4) ?: 0)
grade.startsWith("5.12") ->
18 + (grade.getOrNull(4)?.toString()?.hashCode()?.rem(4) ?: 0)
grade.startsWith("5.13") ->
22 + (grade.getOrNull(4)?.toString()?.hashCode()?.rem(4) ?: 0)
grade.startsWith("5.14") ->
26 + (grade.getOrNull(4)?.toString()?.hashCode()?.rem(4) ?: 0)
grade.startsWith("5.15") ->
30 + (grade.getOrNull(4)?.toString()?.hashCode()?.rem(4) ?: 0)
else -> grade.removePrefix("5.").toIntOrNull() ?: 0
}
}
DifficultySystem.FONT -> {
when {
grade.startsWith("6A") -> 6
grade.startsWith("6B") -> 7
grade.startsWith("6C") -> 8
grade.startsWith("7A") -> 9
grade.startsWith("7B") -> 10
grade.startsWith("7C") -> 11
grade.startsWith("8A") -> 12
grade.startsWith("8B") -> 13
grade.startsWith("8C") -> 14
else -> grade.toIntOrNull() ?: 0
}
}
DifficultySystem.CUSTOM -> grade.hashCode().rem(100)
}
}
}
/**
* Compare this grade with another grade of the same system
* Returns negative if this grade is easier, positive if harder, 0 if equal
* Compare this grade with another grade of the same system Returns negative if this grade is
* easier, positive if harder, 0 if equal
*/
fun compareTo(other: DifficultyGrade): Int {
if (system != other.system) return 0
return when (system) {
DifficultySystem.V_SCALE -> compareVScaleGrades(grade, other.grade)
DifficultySystem.FONT -> compareFontGrades(grade, other.grade)
@@ -83,26 +203,22 @@ data class DifficultyGrade(
DifficultySystem.CUSTOM -> grade.compareTo(other.grade)
}
}
private fun compareVScaleGrades(grade1: String, grade2: String): Int {
// Handle VB (easiest) specially
if (grade1 == "VB" && grade2 != "VB") return -1
if (grade2 == "VB" && grade1 != "VB") return 1
if (grade1 == "VB" && grade2 == "VB") return 0
// Extract numeric values for V grades
val num1 = grade1.removePrefix("V").toIntOrNull() ?: 0
val num2 = grade2.removePrefix("V").toIntOrNull() ?: 0
return num1.compareTo(num2)
}
private fun compareFontGrades(grade1: String, grade2: String): Int {
// Simple string comparison for Font grades
return grade1.compareTo(grade2)
}
private fun compareYDSGrades(grade1: String, grade2: String): Int {
// Simple string comparison for YDS grades
return grade1.compareTo(grade2)
}
}

View File

@@ -2,43 +2,42 @@ package com.atridad.openclimb.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.atridad.openclimb.utils.DateFormatUtils
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
@Entity(tableName = "gyms")
@Serializable
data class Gym(
@PrimaryKey
val id: String,
val name: String,
val location: String? = null,
val supportedClimbTypes: List<ClimbType>,
val difficultySystems: List<DifficultySystem>,
val customDifficultyGrades: List<String> = emptyList(),
val notes: String? = null,
val createdAt: String,
val updatedAt: String
@PrimaryKey val id: String,
val name: String,
val location: String? = null,
val supportedClimbTypes: List<ClimbType>,
val difficultySystems: List<DifficultySystem>,
val customDifficultyGrades: List<String> = emptyList(),
val notes: String? = null,
val createdAt: String,
val updatedAt: String
) {
companion object {
fun create(
name: String,
location: String? = null,
supportedClimbTypes: List<ClimbType>,
difficultySystems: List<DifficultySystem>,
customDifficultyGrades: List<String> = emptyList(),
notes: String? = null
name: String,
location: String? = null,
supportedClimbTypes: List<ClimbType>,
difficultySystems: List<DifficultySystem>,
customDifficultyGrades: List<String> = emptyList(),
notes: String? = null
): Gym {
val now = LocalDateTime.now().toString()
val now = DateFormatUtils.nowISO8601()
return Gym(
id = java.util.UUID.randomUUID().toString(),
name = name,
location = location,
supportedClimbTypes = supportedClimbTypes,
difficultySystems = difficultySystems,
customDifficultyGrades = customDifficultyGrades,
notes = notes,
createdAt = now,
updatedAt = now
id = java.util.UUID.randomUUID().toString(),
name = name,
location = location,
supportedClimbTypes = supportedClimbTypes,
difficultySystems = difficultySystems,
customDifficultyGrades = customDifficultyGrades,
notes = notes,
createdAt = now,
updatedAt = now
)
}
}

View File

@@ -4,7 +4,7 @@ import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import java.time.LocalDateTime
import com.atridad.openclimb.utils.DateFormatUtils
import kotlinx.serialization.Serializable
@Entity(
@@ -49,7 +49,7 @@ data class Problem(
dateSet: String? = null,
notes: String? = null
): Problem {
val now = LocalDateTime.now().toString()
val now = DateFormatUtils.nowISO8601()
return Problem(
id = java.util.UUID.randomUUID().toString(),
gymId = gymId,

View File

@@ -8,9 +8,10 @@ import com.atridad.openclimb.data.format.BackupGym
import com.atridad.openclimb.data.format.BackupProblem
import com.atridad.openclimb.data.format.ClimbDataBackup
import com.atridad.openclimb.data.model.*
import com.atridad.openclimb.data.state.DataStateManager
import com.atridad.openclimb.utils.DateFormatUtils
import com.atridad.openclimb.utils.ZipExportImportUtils
import java.io.File
import java.time.LocalDateTime
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.serialization.json.Json
@@ -20,6 +21,9 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
private val problemDao = database.problemDao()
private val sessionDao = database.climbSessionDao()
private val attemptDao = database.attemptDao()
private val dataStateManager = DataStateManager(context)
private var autoSyncCallback: (() -> Unit)? = null
private val json = Json {
prettyPrint = true
@@ -29,17 +33,41 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
// Gym operations
fun getAllGyms(): Flow<List<Gym>> = gymDao.getAllGyms()
suspend fun getGymById(id: String): Gym? = gymDao.getGymById(id)
suspend fun insertGym(gym: Gym) = gymDao.insertGym(gym)
suspend fun updateGym(gym: Gym) = gymDao.updateGym(gym)
suspend fun deleteGym(gym: Gym) = gymDao.deleteGym(gym)
suspend fun insertGym(gym: Gym) {
gymDao.insertGym(gym)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun updateGym(gym: Gym) {
gymDao.updateGym(gym)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun deleteGym(gym: Gym) {
gymDao.deleteGym(gym)
dataStateManager.updateDataState()
triggerAutoSync()
}
// Problem operations
fun getAllProblems(): Flow<List<Problem>> = problemDao.getAllProblems()
suspend fun getProblemById(id: String): Problem? = problemDao.getProblemById(id)
fun getProblemsByGym(gymId: String): Flow<List<Problem>> = problemDao.getProblemsByGym(gymId)
suspend fun insertProblem(problem: Problem) = problemDao.insertProblem(problem)
suspend fun updateProblem(problem: Problem) = problemDao.updateProblem(problem)
suspend fun deleteProblem(problem: Problem) = problemDao.deleteProblem(problem)
suspend fun insertProblem(problem: Problem) {
problemDao.insertProblem(problem)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun updateProblem(problem: Problem) {
problemDao.updateProblem(problem)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun deleteProblem(problem: Problem) {
problemDao.deleteProblem(problem)
dataStateManager.updateDataState()
triggerAutoSync()
}
// Session operations
fun getAllSessions(): Flow<List<ClimbSession>> = sessionDao.getAllSessions()
@@ -48,9 +76,21 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
sessionDao.getSessionsByGym(gymId)
suspend fun getActiveSession(): ClimbSession? = sessionDao.getActiveSession()
fun getActiveSessionFlow(): Flow<ClimbSession?> = sessionDao.getActiveSessionFlow()
suspend fun insertSession(session: ClimbSession) = sessionDao.insertSession(session)
suspend fun updateSession(session: ClimbSession) = sessionDao.updateSession(session)
suspend fun deleteSession(session: ClimbSession) = sessionDao.deleteSession(session)
suspend fun insertSession(session: ClimbSession) {
sessionDao.insertSession(session)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun updateSession(session: ClimbSession) {
sessionDao.updateSession(session)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun deleteSession(session: ClimbSession) {
sessionDao.deleteSession(session)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun getLastUsedGym(): Gym? {
val recentSessions = sessionDao.getRecentSessions(1).first()
return if (recentSessions.isNotEmpty()) {
@@ -66,25 +106,34 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
attemptDao.getAttemptsBySession(sessionId)
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>> =
attemptDao.getAttemptsByProblem(problemId)
suspend fun insertAttempt(attempt: Attempt) = attemptDao.insertAttempt(attempt)
suspend fun updateAttempt(attempt: Attempt) = attemptDao.updateAttempt(attempt)
suspend fun deleteAttempt(attempt: Attempt) = attemptDao.deleteAttempt(attempt)
suspend fun insertAttempt(attempt: Attempt) {
attemptDao.insertAttempt(attempt)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun updateAttempt(attempt: Attempt) {
attemptDao.updateAttempt(attempt)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun deleteAttempt(attempt: Attempt) {
attemptDao.deleteAttempt(attempt)
dataStateManager.updateDataState()
triggerAutoSync()
}
suspend fun exportAllDataToZipUri(context: Context, uri: android.net.Uri) {
try {
// Collect all data
val allGyms = gymDao.getAllGyms().first()
val allProblems = problemDao.getAllProblems().first()
val allSessions = sessionDao.getAllSessions().first()
val allAttempts = attemptDao.getAllAttempts().first()
// Validate data integrity before export
validateDataIntegrity(allGyms, allProblems, allSessions, allAttempts)
// Create backup data using platform-neutral format
val backupData =
ClimbDataBackup(
exportedAt = LocalDateTime.now().toString(),
exportedAt = DateFormatUtils.nowISO8601(),
version = "2.0",
formatVersion = "2.0",
gyms = allGyms.map { BackupGym.fromGym(it) },
@@ -93,7 +142,6 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
attempts = allAttempts.map { BackupAttempt.fromAttempt(it) }
)
// Collect all referenced image paths and validate they exist
val referencedImagePaths = allProblems.flatMap { it.imagePaths }.toSet()
val validImagePaths =
referencedImagePaths
@@ -124,20 +172,16 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
suspend fun importDataFromZip(file: File) {
try {
// Validate the ZIP file
if (!file.exists() || file.length() == 0L) {
throw Exception("Invalid ZIP file: file is empty or doesn't exist")
}
// Extract and validate the ZIP contents
val importResult = ZipExportImportUtils.extractImportZip(context, file)
// Validate JSON content
if (importResult.jsonContent.isBlank()) {
throw Exception("Invalid ZIP file: no data.json found or empty content")
}
// Parse and validate the data structure
val importData =
try {
json.decodeFromString<ClimbDataBackup>(importResult.jsonContent)
@@ -145,16 +189,13 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
throw Exception("Invalid data format: ${e.message}")
}
// Validate data integrity
validateImportData(importData)
// Clear existing data to avoid conflicts
attemptDao.deleteAllAttempts()
sessionDao.deleteAllSessions()
problemDao.deleteAllProblems()
gymDao.deleteAllGyms()
// Import gyms first (problems depend on gyms)
importData.gyms.forEach { backupGym ->
try {
gymDao.insertGym(backupGym.toGym())
@@ -163,14 +204,12 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
}
}
// Import problems with updated image paths
val updatedBackupProblems =
ZipExportImportUtils.updateProblemImagePaths(
importData.problems,
importResult.importedImagePaths
)
// Import problems (depends on gyms)
updatedBackupProblems.forEach { backupProblem ->
try {
problemDao.insertProblem(backupProblem.toProblem())
@@ -181,7 +220,6 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
}
}
// Import sessions
importData.sessions.forEach { backupSession ->
try {
sessionDao.insertSession(backupSession.toClimbSession())
@@ -190,7 +228,6 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
}
}
// Import attempts last (depends on problems and sessions)
importData.attempts.forEach { backupAttempt ->
try {
attemptDao.insertAttempt(backupAttempt.toAttempt())
@@ -198,18 +235,35 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
throw Exception("Failed to import attempt '${backupAttempt.id}': ${e.message}")
}
}
dataStateManager.updateDataState()
} catch (e: Exception) {
throw Exception("Import failed: ${e.message}")
}
}
/**
* Sets the callback for auto-sync functionality. This should be called by the SyncService to
* register itself for auto-sync triggers.
*/
fun setAutoSyncCallback(callback: (() -> Unit)?) {
autoSyncCallback = callback
}
/**
* Triggers auto-sync if enabled. This is called after any data modification to keep data
* synchronized across devices automatically.
*/
private fun triggerAutoSync() {
autoSyncCallback?.invoke()
}
private fun validateDataIntegrity(
gyms: List<Gym>,
problems: List<Problem>,
sessions: List<ClimbSession>,
attempts: List<Attempt>
) {
// Validate that all problems reference valid gyms
val gymIds = gyms.map { it.id }.toSet()
val invalidProblems = problems.filter { it.gymId !in gymIds }
if (invalidProblems.isNotEmpty()) {
@@ -218,7 +272,6 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
)
}
// Validate that all sessions reference valid gyms
val invalidSessions = sessions.filter { it.gymId !in gymIds }
if (invalidSessions.isNotEmpty()) {
throw Exception(
@@ -226,7 +279,6 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
)
}
// Validate that all attempts reference valid problems and sessions
val problemIds = problems.map { it.id }.toSet()
val sessionIds = sessions.map { it.id }.toSet()
@@ -248,7 +300,6 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
throw Exception("Import data is invalid: no version information")
}
// Check for reasonable data sizes to prevent malicious imports
if (importData.gyms.size > 1000 ||
importData.problems.size > 10000 ||
importData.sessions.size > 10000 ||
@@ -260,22 +311,44 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
suspend fun resetAllData() {
try {
// Clear all data from database
val originalCallback = autoSyncCallback
autoSyncCallback = null
attemptDao.deleteAllAttempts()
sessionDao.deleteAllSessions()
problemDao.deleteAllProblems()
gymDao.deleteAllGyms()
// Clear all images from storage
clearAllImages()
autoSyncCallback = originalCallback
} catch (e: Exception) {
throw Exception("Reset failed: ${e.message}")
}
}
suspend fun insertGymWithoutSync(gym: Gym) {
gymDao.insertGym(gym)
dataStateManager.updateDataState()
}
suspend fun insertProblemWithoutSync(problem: Problem) {
problemDao.insertProblem(problem)
dataStateManager.updateDataState()
}
suspend fun insertSessionWithoutSync(session: ClimbSession) {
sessionDao.insertSession(session)
dataStateManager.updateDataState()
}
suspend fun insertAttemptWithoutSync(attempt: Attempt) {
attemptDao.insertAttempt(attempt)
dataStateManager.updateDataState()
}
private fun clearAllImages() {
try {
// Get the images directory
val imagesDir = File(context.filesDir, "images")
if (imagesDir.exists() && imagesDir.isDirectory) {
val deletedCount = imagesDir.listFiles()?.size ?: 0

View File

@@ -0,0 +1,80 @@
package com.atridad.openclimb.data.state
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import com.atridad.openclimb.utils.DateFormatUtils
/**
* Manages the overall data state timestamp for sync purposes. This tracks when any data in the
* local database was last modified, independent of individual entity timestamps.
*/
class DataStateManager(context: Context) {
companion object {
private const val TAG = "DataStateManager"
private const val PREFS_NAME = "openclimb_data_state"
private const val KEY_LAST_MODIFIED = "last_modified_timestamp"
private const val KEY_INITIALIZED = "state_initialized"
}
private val prefs: SharedPreferences =
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
init {
if (!isInitialized()) {
updateDataState()
markAsInitialized()
Log.d(TAG, "DataStateManager initialized with timestamp: ${getLastModified()}")
}
}
/**
* Updates the data state timestamp to the current time. Call this whenever any data is modified
* (create, update, delete).
*/
fun updateDataState() {
val now = DateFormatUtils.nowISO8601()
prefs.edit().putString(KEY_LAST_MODIFIED, now).apply()
Log.d(TAG, "Data state updated to: $now")
}
/**
* Gets the current data state timestamp. This represents when any data was last modified
* locally.
*/
fun getLastModified(): String {
return prefs.getString(KEY_LAST_MODIFIED, DateFormatUtils.nowISO8601())
?: DateFormatUtils.nowISO8601()
}
/**
* Sets the data state timestamp to a specific value. Used when importing data from server to
* sync the state.
*/
fun setLastModified(timestamp: String) {
prefs.edit().putString(KEY_LAST_MODIFIED, timestamp).apply()
Log.d(TAG, "Data state set to: $timestamp")
}
/** Resets the data state (for testing or complete data wipe). */
fun reset() {
prefs.edit().clear().apply()
Log.d(TAG, "Data state reset")
}
/** Checks if the data state has been initialized. */
private fun isInitialized(): Boolean {
return prefs.getBoolean(KEY_INITIALIZED, false)
}
/** Marks the data state as initialized. */
private fun markAsInitialized() {
prefs.edit().putBoolean(KEY_INITIALIZED, true).apply()
}
/** Gets debug information about the current state. */
fun getDebugInfo(): String {
return "DataState(lastModified=${getLastModified()}, initialized=${isInitialized()})"
}
}

View File

@@ -0,0 +1,801 @@
package com.atridad.openclimb.data.sync
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import androidx.core.content.edit
import com.atridad.openclimb.data.format.BackupAttempt
import com.atridad.openclimb.data.format.BackupClimbSession
import com.atridad.openclimb.data.format.BackupGym
import com.atridad.openclimb.data.format.BackupProblem
import com.atridad.openclimb.data.format.ClimbDataBackup
import com.atridad.openclimb.data.migration.ImageMigrationService
import com.atridad.openclimb.data.repository.ClimbRepository
import com.atridad.openclimb.data.state.DataStateManager
import com.atridad.openclimb.utils.DateFormatUtils
import com.atridad.openclimb.utils.ImageNamingUtils
import com.atridad.openclimb.utils.ImageUtils
import java.io.IOException
import java.time.Instant
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
class SyncService(private val context: Context, private val repository: ClimbRepository) {
private val migrationService = ImageMigrationService(context, repository)
private val dataStateManager = DataStateManager(context)
private val syncMutex = Mutex()
companion object {
private const val TAG = "SyncService"
}
private val sharedPreferences: SharedPreferences =
context.getSharedPreferences("sync_preferences", Context.MODE_PRIVATE)
private val httpClient =
OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
private val json = Json {
prettyPrint = true
ignoreUnknownKeys = true
explicitNulls = false
encodeDefaults = true
coerceInputValues = true
}
// State
private val _isSyncing = MutableStateFlow(false)
val isSyncing: StateFlow<Boolean> = _isSyncing.asStateFlow()
private val _lastSyncTime = MutableStateFlow<String?>(null)
val lastSyncTime: StateFlow<String?> = _lastSyncTime.asStateFlow()
private val _syncError = MutableStateFlow<String?>(null)
val syncError: StateFlow<String?> = _syncError.asStateFlow()
private val _isConnected = MutableStateFlow(false)
val isConnected: StateFlow<Boolean> = _isConnected.asStateFlow()
private val _isTesting = MutableStateFlow(false)
val isTesting: StateFlow<Boolean> = _isTesting.asStateFlow()
// Configuration keys
private object Keys {
const val SERVER_URL = "sync_server_url"
const val AUTH_TOKEN = "sync_auth_token"
const val LAST_SYNC_TIME = "last_sync_time"
const val IS_CONNECTED = "sync_is_connected"
const val AUTO_SYNC_ENABLED = "auto_sync_enabled"
}
// Configuration properties
var serverURL: String
get() = sharedPreferences.getString(Keys.SERVER_URL, "") ?: ""
set(value) {
sharedPreferences.edit { putString(Keys.SERVER_URL, value) }
}
var authToken: String
get() = sharedPreferences.getString(Keys.AUTH_TOKEN, "") ?: ""
set(value) {
sharedPreferences.edit { putString(Keys.AUTH_TOKEN, value) }
}
val isConfigured: Boolean
get() = serverURL.isNotEmpty() && authToken.isNotEmpty()
var isAutoSyncEnabled: Boolean
get() = sharedPreferences.getBoolean(Keys.AUTO_SYNC_ENABLED, true)
set(value) {
sharedPreferences.edit().putBoolean(Keys.AUTO_SYNC_ENABLED, value).apply()
}
init {
_isConnected.value = sharedPreferences.getBoolean(Keys.IS_CONNECTED, false)
_lastSyncTime.value = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
repository.setAutoSyncCallback {
kotlinx.coroutines.CoroutineScope(Dispatchers.IO).launch { triggerAutoSync() }
}
}
suspend fun downloadData(): ClimbDataBackup =
withContext(Dispatchers.IO) {
if (!isConfigured) {
throw SyncException.NotConfigured
}
val request =
Request.Builder()
.url("$serverURL/sync")
.get()
.addHeader("Authorization", "Bearer $authToken")
.addHeader("Accept", "application/json")
.build()
try {
val response = httpClient.newCall(request).execute()
when (response.code) {
200 -> {
val responseBody =
response.body?.string()
?: throw SyncException.InvalidResponse(
"Empty response body"
)
Log.d(TAG, "Downloaded data from server: ${responseBody.take(500)}...")
try {
val backup = json.decodeFromString<ClimbDataBackup>(responseBody)
Log.d(
TAG,
"Server backup contains: gyms=${backup.gyms.size}, problems=${backup.problems.size}, sessions=${backup.sessions.size}, attempts=${backup.attempts.size}"
)
backup.problems.forEach { problem ->
val imageCount = problem.imagePaths?.size ?: 0
if (imageCount > 0) {
Log.d(
TAG,
"Server problem '${problem.name}' has images: ${problem.imagePaths}"
)
}
}
backup
} catch (e: Exception) {
Log.e(TAG, "Failed to decode download response: ${e.message}")
throw SyncException.DecodingError(
e.message ?: "Failed to decode response"
)
}
}
401 -> throw SyncException.Unauthorized
else -> throw SyncException.ServerError(response.code)
}
} catch (e: IOException) {
throw SyncException.NetworkError(e.message ?: "Network error")
}
}
suspend fun uploadData(backup: ClimbDataBackup): ClimbDataBackup =
withContext(Dispatchers.IO) {
if (!isConfigured) {
throw SyncException.NotConfigured
}
val jsonBody = json.encodeToString(backup)
Log.d(TAG, "Uploading JSON to server: $jsonBody")
val requestBody = jsonBody.toRequestBody("application/json".toMediaType())
val request =
Request.Builder()
.url("$serverURL/sync")
.put(requestBody)
.addHeader("Authorization", "Bearer $authToken")
.addHeader("Content-Type", "application/json")
.build()
try {
val response = httpClient.newCall(request).execute()
Log.d(TAG, "Upload response code: ${response.code}")
when (response.code) {
200 -> {
val responseBody =
response.body?.string()
?: throw SyncException.InvalidResponse(
"Empty response body"
)
try {
json.decodeFromString<ClimbDataBackup>(responseBody)
} catch (e: Exception) {
Log.e(TAG, "Failed to decode upload response: ${e.message}")
throw SyncException.DecodingError(
e.message ?: "Failed to decode response"
)
}
}
401 -> throw SyncException.Unauthorized
else -> {
val errorBody = response.body?.string() ?: "No error details"
Log.e(TAG, "Server error ${response.code}: $errorBody")
throw SyncException.ServerError(response.code)
}
}
} catch (e: IOException) {
throw SyncException.NetworkError(e.message ?: "Network error")
}
}
suspend fun uploadImage(filename: String, imageData: ByteArray) =
withContext(Dispatchers.IO) {
if (!isConfigured) {
throw SyncException.NotConfigured
}
val justFilename = filename.substringAfterLast('/')
val requestBody = imageData.toRequestBody("image/*".toMediaType())
val request =
Request.Builder()
.url("$serverURL/images/upload?filename=$justFilename")
.post(requestBody)
.addHeader("Authorization", "Bearer $authToken")
.build()
try {
val response = httpClient.newCall(request).execute()
when (response.code) {
200 -> Unit
401 -> throw SyncException.Unauthorized
else -> {
val errorBody = response.body?.string() ?: "No error details"
Log.e(TAG, "Image upload error ${response.code}: $errorBody")
throw SyncException.ServerError(response.code)
}
}
} catch (e: IOException) {
throw SyncException.NetworkError(e.message ?: "Network error")
}
}
suspend fun downloadImage(filename: String): ByteArray =
withContext(Dispatchers.IO) {
if (!isConfigured) {
throw SyncException.NotConfigured
}
Log.d(TAG, "Downloading image from server: $filename")
val request =
Request.Builder()
.url("$serverURL/images/download?filename=$filename")
.get()
.addHeader("Authorization", "Bearer $authToken")
.build()
try {
val response = httpClient.newCall(request).execute()
Log.d(TAG, "Image download response for $filename: ${response.code}")
when (response.code) {
200 -> {
val imageBytes =
response.body?.bytes()
?: throw SyncException.InvalidResponse(
"Empty image response"
)
Log.d(
TAG,
"Successfully downloaded image $filename: ${imageBytes.size} bytes"
)
imageBytes
}
401 -> throw SyncException.Unauthorized
404 -> {
Log.w(TAG, "Image not found on server: $filename")
throw SyncException.ImageNotFound(filename)
}
else -> {
val errorBody = response.body?.string() ?: "No error details"
Log.e(
TAG,
"Image download error ${response.code} for $filename: $errorBody"
)
throw SyncException.ServerError(response.code)
}
}
} catch (e: IOException) {
Log.e(TAG, "Network error downloading image $filename: ${e.message}")
throw SyncException.NetworkError(e.message ?: "Network error")
}
}
suspend fun syncWithServer() {
if (!isConfigured) {
throw SyncException.NotConfigured
}
if (!_isConnected.value) {
throw SyncException.NotConnected
}
syncMutex.withLock {
_isSyncing.value = true
_syncError.value = null
try {
Log.d(TAG, "Fixing existing image paths before sync")
val pathFixSuccess = fixImagePaths()
if (!pathFixSuccess) {
Log.w(TAG, "Image path fix failed, but continuing with sync")
}
Log.d(TAG, "Performing image migration before sync")
val migrationSuccess = migrateImagesForSync()
if (!migrationSuccess) {
Log.w(TAG, "Image migration failed, but continuing with sync")
}
val localBackup = createBackupFromRepository()
val serverBackup = downloadData()
val hasLocalData =
localBackup.gyms.isNotEmpty() ||
localBackup.problems.isNotEmpty() ||
localBackup.sessions.isNotEmpty() ||
localBackup.attempts.isNotEmpty()
val hasServerData =
serverBackup.gyms.isNotEmpty() ||
serverBackup.problems.isNotEmpty() ||
serverBackup.sessions.isNotEmpty() ||
serverBackup.attempts.isNotEmpty()
when {
!hasLocalData && hasServerData -> {
Log.d(TAG, "No local data found, performing full restore from server")
val imagePathMapping = syncImagesFromServer(serverBackup)
importBackupToRepository(serverBackup, imagePathMapping)
Log.d(TAG, "Full restore completed")
}
hasLocalData && !hasServerData -> {
Log.d(TAG, "No server data found, uploading local data to server")
uploadData(localBackup)
syncImagesForBackup(localBackup)
Log.d(TAG, "Initial upload completed")
}
hasLocalData && hasServerData -> {
val localTimestamp = parseISO8601ToMillis(localBackup.exportedAt)
val serverTimestamp = parseISO8601ToMillis(serverBackup.exportedAt)
Log.d(
TAG,
"Comparing timestamps: local=$localTimestamp, server=$serverTimestamp"
)
if (localTimestamp > serverTimestamp) {
Log.d(TAG, "Local data is newer, replacing server content")
uploadData(localBackup)
syncImagesForBackup(localBackup)
Log.d(TAG, "Server replaced with local data")
} else if (serverTimestamp > localTimestamp) {
Log.d(TAG, "Server data is newer, replacing local content")
val imagePathMapping = syncImagesFromServer(serverBackup)
importBackupToRepository(serverBackup, imagePathMapping)
Log.d(TAG, "Local data replaced with server data")
} else {
Log.d(TAG, "Data is in sync (timestamps equal), no action needed")
}
}
else -> {
Log.d(TAG, "No data to sync")
}
}
val now = DateFormatUtils.nowISO8601()
_lastSyncTime.value = now
sharedPreferences.edit().putString(Keys.LAST_SYNC_TIME, now).apply()
} catch (e: Exception) {
_syncError.value = e.message
throw e
} finally {
_isSyncing.value = false
}
}
}
private suspend fun syncImagesFromServer(backup: ClimbDataBackup): Map<String, String> {
val imagePathMapping = mutableMapOf<String, String>()
Log.d(TAG, "Starting to download images from server")
var totalImages = 0
var downloadedImages = 0
var failedImages = 0
for (problem in backup.problems) {
val imageCount = problem.imagePaths?.size ?: 0
if (imageCount > 0) {
Log.d(
TAG,
"Problem '${problem.name}' has $imageCount images: ${problem.imagePaths}"
)
totalImages += imageCount
}
problem.imagePaths?.forEachIndexed { index, imagePath ->
try {
Log.d(TAG, "Attempting to download image: $imagePath")
val imageData = downloadImage(imagePath)
val serverFilename = imagePath.substringAfterLast('/')
val consistentFilename =
if (ImageNamingUtils.isValidImageFilename(serverFilename)) {
serverFilename
} else {
ImageNamingUtils.generateImageFilename(problem.id, index)
}
val localImagePath =
ImageUtils.saveImageFromBytesWithFilename(
context,
imageData,
consistentFilename
)
if (localImagePath != null) {
imagePathMapping[serverFilename] = localImagePath
downloadedImages++
Log.d(
TAG,
"Downloaded and mapped image: $serverFilename -> $localImagePath"
)
} else {
Log.w(TAG, "Failed to save downloaded image locally: $imagePath")
failedImages++
}
} catch (e: Exception) {
Log.w(TAG, "Failed to download image $imagePath: ${e.message}")
failedImages++
}
}
}
Log.d(
TAG,
"Image download completed: $downloadedImages downloaded, $failedImages failed, $totalImages total"
)
return imagePathMapping
}
private suspend fun syncImagesForBackup(backup: ClimbDataBackup) {
Log.d(TAG, "Starting image sync for backup with ${backup.problems.size} problems")
var totalImages = 0
var uploadedImages = 0
var failedImages = 0
for (problem in backup.problems) {
val imageCount = problem.imagePaths?.size ?: 0
totalImages += imageCount
Log.d(TAG, "Problem '${problem.name}' has $imageCount images: ${problem.imagePaths}")
problem.imagePaths?.forEachIndexed { index, imagePath ->
try {
val imageFile = ImageUtils.getImageFile(context, imagePath)
Log.d(TAG, "Checking image file: $imagePath -> ${imageFile.absolutePath}")
Log.d(
TAG,
"Image file exists: ${imageFile.exists()}, size: ${if (imageFile.exists()) imageFile.length() else 0} bytes"
)
if (imageFile.exists() && imageFile.length() > 0) {
val imageData = imageFile.readBytes()
val filename = imagePath.substringAfterLast('/')
val consistentFilename =
if (ImageNamingUtils.isValidImageFilename(filename)) {
filename
} else {
val newFilename =
ImageNamingUtils.generateImageFilename(
problem.id,
index
)
val newFile = java.io.File(imageFile.parent, newFilename)
if (imageFile.renameTo(newFile)) {
Log.d(
TAG,
"Renamed local image file: $filename -> $newFilename"
)
newFilename
} else {
Log.w(
TAG,
"Failed to rename local image file, using original"
)
filename
}
}
Log.d(TAG, "Uploading image: $consistentFilename (${imageData.size} bytes)")
uploadImage(consistentFilename, imageData)
uploadedImages++
Log.d(TAG, "Successfully uploaded image: $consistentFilename")
} else {
Log.w(
TAG,
"Image file not found or empty: $imagePath at ${imageFile.absolutePath}"
)
failedImages++
}
} catch (e: Exception) {
Log.e(TAG, "Failed to upload image $imagePath: ${e.message}", e)
failedImages++
}
}
}
Log.d(
TAG,
"Image sync completed: $uploadedImages uploaded, $failedImages failed, $totalImages total"
)
}
private suspend fun createBackupFromRepository(): ClimbDataBackup {
val allGyms = repository.getAllGyms().first()
val allProblems = repository.getAllProblems().first()
val allSessions = repository.getAllSessions().first()
val allAttempts = repository.getAllAttempts().first()
return ClimbDataBackup(
exportedAt = dataStateManager.getLastModified(),
version = "2.0",
formatVersion = "2.0",
gyms = allGyms.map { BackupGym.fromGym(it) },
problems = allProblems.map { BackupProblem.fromProblem(it) },
sessions = allSessions.map { BackupClimbSession.fromClimbSession(it) },
attempts = allAttempts.map { BackupAttempt.fromAttempt(it) }
)
}
private suspend fun importBackupToRepository(
backup: ClimbDataBackup,
imagePathMapping: Map<String, String> = emptyMap()
) {
repository.resetAllData()
backup.gyms.forEach { backupGym ->
try {
val gym = backupGym.toGym()
Log.d(TAG, "Importing gym: ${gym.name} (ID: ${gym.id})")
repository.insertGymWithoutSync(gym)
} catch (e: Exception) {
Log.e(TAG, "Failed to import gym '${backupGym.name}': ${e.message}")
throw e
}
}
backup.problems.forEach { backupProblem ->
try {
val updatedProblem =
if (imagePathMapping.isNotEmpty()) {
val newImagePaths =
backupProblem.imagePaths?.map { oldPath ->
val filename = oldPath.substringAfterLast('/')
imagePathMapping[filename]
?: if (ImageNamingUtils.isValidImageFilename(
filename
)
) {
"problem_images/$filename"
} else {
val index =
backupProblem.imagePaths.indexOf(
oldPath
)
val consistentFilename =
ImageNamingUtils.generateImageFilename(
backupProblem.id,
index
)
"problem_images/$consistentFilename"
}
}
?: emptyList()
backupProblem.withUpdatedImagePaths(newImagePaths)
} else {
backupProblem
}
repository.insertProblemWithoutSync(updatedProblem.toProblem())
} catch (e: Exception) {
Log.e(TAG, "Failed to import problem '${backupProblem.name}': ${e.message}")
}
}
backup.sessions.forEach { backupSession ->
try {
repository.insertSessionWithoutSync(backupSession.toClimbSession())
} catch (e: Exception) {
Log.e(TAG, "Failed to import session '${backupSession.id}': ${e.message}")
}
}
backup.attempts.forEach { backupAttempt ->
try {
repository.insertAttemptWithoutSync(backupAttempt.toAttempt())
} catch (e: Exception) {
Log.e(TAG, "Failed to import attempt '${backupAttempt.id}': ${e.message}")
}
}
dataStateManager.setLastModified(backup.exportedAt)
Log.d(TAG, "Data state synchronized to imported timestamp: ${backup.exportedAt}")
}
/** Parses ISO8601 timestamp to milliseconds for comparison */
private fun parseISO8601ToMillis(timestamp: String): Long {
return try {
Instant.parse(timestamp).toEpochMilli()
} catch (e: Exception) {
Log.w(TAG, "Failed to parse timestamp: $timestamp, using 0", e)
0L
}
}
/**
* Fixes existing image paths in the database to include the proper directory structure. This
* corrects paths like "problem_abc_0.jpg" to "problem_images/problem_abc_0.jpg"
*/
suspend fun fixImagePaths(): Boolean {
return try {
Log.d(TAG, "Fixing existing image paths in database")
val allProblems = repository.getAllProblems().first()
var fixedCount = 0
for (problem in allProblems) {
if (problem.imagePaths.isNotEmpty()) {
val originalPaths = problem.imagePaths
val fixedPaths =
problem.imagePaths.map { path ->
if (!path.startsWith("problem_images/") && !path.contains("/")) {
val fixedPath = "problem_images/$path"
Log.d(TAG, "Fixed path: $path -> $fixedPath")
fixedCount++
fixedPath
} else {
path
}
}
if (originalPaths != fixedPaths) {
val updatedProblem = problem.copy(imagePaths = fixedPaths)
repository.insertProblem(updatedProblem)
}
}
}
Log.i(TAG, "Fixed $fixedCount image paths in database")
true
} catch (e: Exception) {
Log.e(TAG, "Failed to fix image paths: ${e.message}", e)
false
}
}
/**
* Performs image migration to ensure all images use consistent naming convention before sync
* operations. This should be called before any sync to avoid filename conflicts.
*/
suspend fun migrateImagesForSync(): Boolean {
return try {
Log.d(TAG, "Starting image migration for sync compatibility")
val result = migrationService.performFullMigration()
when (result) {
is com.atridad.openclimb.data.migration.ImageMigrationResult.AlreadyCompleted -> {
Log.d(TAG, "Image migration already completed")
true
}
is com.atridad.openclimb.data.migration.ImageMigrationResult.Success -> {
Log.i(
TAG,
"Image migration completed: ${result.totalMigrated} images migrated, ${result.errors} errors"
)
true
}
is com.atridad.openclimb.data.migration.ImageMigrationResult.Failed -> {
Log.e(TAG, "Image migration failed: ${result.error}")
false
}
}
} catch (e: Exception) {
Log.e(TAG, "Image migration error: ${e.message}", e)
false
}
}
suspend fun testConnection() {
if (!isConfigured) {
throw SyncException.NotConfigured
}
_isTesting.value = true
_syncError.value = null
try {
withContext(Dispatchers.IO) {
val request =
Request.Builder()
.url("$serverURL/sync")
.get()
.addHeader("Authorization", "Bearer $authToken")
.addHeader("Accept", "application/json")
.build()
val response = httpClient.newCall(request).execute()
when (response.code) {
200 -> {
_isConnected.value = true
sharedPreferences.edit().putBoolean(Keys.IS_CONNECTED, true).apply()
}
401 -> throw SyncException.Unauthorized
else -> throw SyncException.ServerError(response.code)
}
}
} catch (e: Exception) {
_isConnected.value = false
sharedPreferences.edit().putBoolean(Keys.IS_CONNECTED, false).apply()
_syncError.value = e.message
throw e
} finally {
_isTesting.value = false
}
}
suspend fun triggerAutoSync() {
if (!isConfigured || !_isConnected.value || !isAutoSyncEnabled) {
return
}
if (_isSyncing.value) {
Log.d(TAG, "Sync already in progress, skipping auto-sync")
return
}
try {
syncWithServer()
} catch (e: Exception) {
Log.e(TAG, "Auto-sync failed: ${e.message}")
_syncError.value = e.message
}
}
fun clearConfiguration() {
serverURL = ""
authToken = ""
isAutoSyncEnabled = true
_lastSyncTime.value = null
_isConnected.value = false
_syncError.value = null
sharedPreferences.edit().clear().apply()
}
}
sealed class SyncException(message: String) : Exception(message) {
object NotConfigured :
SyncException("Sync is not configured. Please set server URL and auth token.")
object NotConnected : SyncException("Not connected to server. Please test connection first.")
object Unauthorized : SyncException("Unauthorized. Please check your auth token.")
data class ServerError(val code: Int) : SyncException("Server error: HTTP $code")
data class InvalidResponse(val details: String) :
SyncException("Invalid server response: $details")
data class DecodingError(val details: String) :
SyncException("Failed to decode server response: $details")
data class ImageNotFound(val filename: String) : SyncException("Image not found: $filename")
data class NetworkError(val details: String) : SyncException("Network error: $details")
}

View File

@@ -4,39 +4,27 @@ import kotlinx.serialization.Serializable
@Serializable
sealed class Screen {
@Serializable
data object Sessions : Screen()
@Serializable
data object Problems : Screen()
@Serializable
data object Analytics : Screen()
@Serializable
data object Gyms : Screen()
@Serializable
data object Settings : Screen()
// Detail screens
@Serializable
data class SessionDetail(val sessionId: String) : Screen()
@Serializable
data class ProblemDetail(val problemId: String) : Screen()
@Serializable
data class GymDetail(val gymId: String) : Screen()
@Serializable
data class AddEditGym(val gymId: String? = null) : Screen()
@Serializable data object Sessions : Screen()
@Serializable data object Problems : Screen()
@Serializable data object Analytics : Screen()
@Serializable data object Gyms : Screen()
@Serializable data object Settings : Screen()
@Serializable data class SessionDetail(val sessionId: String) : Screen()
@Serializable data class ProblemDetail(val problemId: String) : Screen()
@Serializable data class GymDetail(val gymId: String) : Screen()
@Serializable data class AddEditGym(val gymId: String? = null) : Screen()
@Serializable
data class AddEditProblem(val problemId: String? = null, val gymId: String? = null) : Screen()
@Serializable
data class AddEditSession(val sessionId: String? = null, val gymId: String? = null) : Screen()
}

View File

@@ -11,7 +11,6 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
@@ -20,6 +19,7 @@ import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import com.atridad.openclimb.data.database.OpenClimbDatabase
import com.atridad.openclimb.data.repository.ClimbRepository
import com.atridad.openclimb.data.sync.SyncService
import com.atridad.openclimb.navigation.Screen
import com.atridad.openclimb.navigation.bottomNavigationItems
import com.atridad.openclimb.ui.components.NotificationPermissionDialog
@@ -43,13 +43,13 @@ fun OpenClimbApp(
val database = remember { OpenClimbDatabase.getDatabase(context) }
val repository = remember { ClimbRepository(database, context) }
val viewModel: ClimbViewModel = viewModel(factory = ClimbViewModelFactory(repository))
val syncService = remember { SyncService(context, repository) }
val viewModel: ClimbViewModel =
viewModel(factory = ClimbViewModelFactory(repository, syncService))
// Notification permission state
var showNotificationPermissionDialog by remember { mutableStateOf(false) }
var hasCheckedNotificationPermission by remember { mutableStateOf(false) }
// Permission launcher
val permissionLauncher =
rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
@@ -73,10 +73,11 @@ fun OpenClimbApp(
LaunchedEffect(Unit) { viewModel.ensureSessionTrackingServiceRunning(context) }
LaunchedEffect(Unit) { syncService.triggerAutoSync() }
val activeSession by viewModel.activeSession.collectAsState()
val gyms by viewModel.gyms.collectAsState()
// Update last used gym when gyms change
LaunchedEffect(gyms) {
if (gyms.isNotEmpty() && lastUsedGym == null) {
lastUsedGym = viewModel.getLastUsedGym()
@@ -111,7 +112,6 @@ fun OpenClimbApp(
}
}
// Process shortcut actions after data is loaded
LaunchedEffect(shortcutAction, activeSession, gyms, lastUsedGym) {
if (shortcutAction == AppShortcutManager.ACTION_START_SESSION && gyms.isNotEmpty()) {
android.util.Log.d(
@@ -135,7 +135,6 @@ fun OpenClimbApp(
)
viewModel.startSession(context, gyms.first().id)
} else {
// Try to get the last used gym from the intent or fallback to state
val targetGym =
lastUsedGymId?.let { gymId -> gyms.find { it.id == gymId } }
?: lastUsedGym
@@ -162,7 +161,6 @@ fun OpenClimbApp(
)
}
// Clear the shortcut action after processing to prevent repeated execution
onShortcutActionProcessed()
}
}
@@ -210,8 +208,6 @@ fun OpenClimbApp(
if (gyms.size == 1) {
viewModel.startSession(context, gyms.first().id)
} else {
// Always show gym selection for FAB when
// multiple gyms
navController.navigate(Screen.AddEditSession())
}
}
@@ -357,7 +353,6 @@ fun OpenClimbApp(
}
}
// Notification permission dialog
if (showNotificationPermissionDialog) {
NotificationPermissionDialog(
onDismiss = { showNotificationPermissionDialog = false },
@@ -394,10 +389,7 @@ fun OpenClimbBottomNavigation(navController: NavHostController) {
selected = isSelected,
onClick = {
navController.navigate(item.screen) {
// Clear the entire back stack and go to the selected tab's root screen
popUpTo(0) { inclusive = true }
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Don't restore state - always start fresh when switching tabs
restoreState = false

View File

@@ -54,15 +54,15 @@ fun BarChart(
val chartWidth = size.width - padding * 2
val chartHeight = size.height - padding * 2
// Sort data by grade numeric value for proper ordering
// Sort data by grade numeric value
val sortedData = data.sortedBy { it.gradeNumeric }
// Calculate max value for scaling
// Calculate max value
val maxValue = sortedData.maxOfOrNull { it.value } ?: 1
// Calculate bar dimensions
// Bar dimensions
val barCount = sortedData.size
val totalSpacing = chartWidth * 0.2f // 20% of width for spacing
val totalSpacing = chartWidth * 0.2f
val barSpacing = if (barCount > 1) totalSpacing / (barCount + 1) else totalSpacing / 2
val barWidth = (chartWidth - totalSpacing) / barCount
@@ -106,25 +106,25 @@ fun BarChart(
size = androidx.compose.ui.geometry.Size(barWidth, barHeight)
)
// Draw value on top of bar (if there's space)
// Draw value on bar
if (dataPoint.value > 0) {
val valueText = dataPoint.value.toString()
val textStyle = TextStyle(color = style.textColor, fontSize = 10.sp)
val textSize = textMeasurer.measure(valueText, textStyle)
// Position text on top of bar or inside if bar is tall enough
// Position text
val textY =
if (barHeight > textSize.size.height + 8.dp.toPx()) {
barY + 8.dp.toPx() // Inside bar
barY + 8.dp.toPx()
} else {
barY - 4.dp.toPx() // Above bar
barY - 4.dp.toPx()
}
val textColor =
if (barHeight > textSize.size.height + 8.dp.toPx()) {
Color.White // White text inside bar
Color.White
} else {
style.textColor // Regular color above bar
style.textColor
}
drawText(
@@ -166,7 +166,7 @@ private fun DrawScope.drawGrid(
) {
val textStyle = TextStyle(color = textColor, fontSize = 10.sp)
// Draw horizontal grid lines (Y-axis)
// Horizontal grid lines
val gridLines =
when {
maxValue <= 5 -> (0..maxValue).toList()

View File

@@ -0,0 +1,49 @@
package com.atridad.openclimb.ui.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.flow.StateFlow
@Composable
fun SyncIndicator(isSyncing: StateFlow<Boolean>, modifier: Modifier = Modifier) {
val syncing by isSyncing.collectAsState()
AnimatedVisibility(
visible = syncing,
enter = scaleIn() + fadeIn(),
exit = scaleOut() + fadeOut(),
modifier = modifier
) {
Box(
modifier =
Modifier.size(28.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primaryContainer, CircleShape)
.padding(6.dp),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.primary
)
}
}
}

View File

@@ -15,6 +15,7 @@ import com.atridad.openclimb.data.model.ClimbType
import com.atridad.openclimb.data.model.DifficultySystem
import com.atridad.openclimb.ui.components.BarChart
import com.atridad.openclimb.ui.components.BarChartDataPoint
import com.atridad.openclimb.ui.components.SyncIndicator
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@@ -45,8 +46,10 @@ fun AnalyticsScreen(viewModel: ClimbViewModel) {
Text(
text = "Analytics",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f)
)
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
}
}
@@ -197,7 +200,7 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
},
modifier =
Modifier.menuAnchor(
type = MenuAnchorType.PrimaryNotEditable,
type = ExposedDropdownMenuAnchorType.PrimaryNotEditable,
enabled = true
)
.width(120.dp),
@@ -253,7 +256,7 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
DateTimeFormatter.ISO_LOCAL_DATE_TIME
)
attemptDate.isAfter(sevenDaysAgo)
} catch (e: Exception) {
} catch (_: Exception) {
// If date parsing fails, include the data point
true
}
@@ -425,9 +428,7 @@ fun calculateGradeDistribution(
} else {
gradeDistribution[key] =
GradeDistributionDataPoint(
date =
attempt.timestamp
.toString(), // Use attempt timestamp for filtering
date = attempt.timestamp,
grade = problem.difficulty.grade,
gradeNumeric =
gradeToNumeric(

View File

@@ -12,55 +12,48 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.atridad.openclimb.R
import com.atridad.openclimb.data.model.Gym
import com.atridad.openclimb.ui.components.SyncIndicator
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GymsScreen(
viewModel: ClimbViewModel,
onNavigateToGymDetail: (String) -> Unit
) {
fun GymsScreen(viewModel: ClimbViewModel, onNavigateToGymDetail: (String) -> Unit) {
val gyms by viewModel.gyms.collectAsState()
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Icon(
painter = painterResource(id = R.drawable.ic_mountains),
contentDescription = "OpenClimb Logo",
modifier = Modifier.size(32.dp),
tint = MaterialTheme.colorScheme.primary
painter = painterResource(id = R.drawable.ic_mountains),
contentDescription = "OpenClimb Logo",
modifier = Modifier.size(32.dp),
tint = MaterialTheme.colorScheme.primary
)
Text(
text = "Climbing Gyms",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold
text = "Climbing Gyms",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f)
)
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
}
Spacer(modifier = Modifier.height(16.dp))
if (gyms.isEmpty()) {
EmptyStateMessage(
title = "No Gyms Added",
message = "Add your favorite climbing gyms to start tracking your progress!",
onActionClick = { },
actionText = ""
title = "No Gyms Added",
message = "Add your favorite climbing gyms to start tracking your progress!",
onActionClick = {},
actionText = ""
)
} else {
LazyColumn {
items(gyms) { gym ->
GymCard(
gym = gym,
onClick = { onNavigateToGymDetail(gym.id) }
)
GymCard(gym = gym, onClick = { onNavigateToGymDetail(gym.id) })
Spacer(modifier = Modifier.height(8.dp))
}
}
@@ -70,65 +63,54 @@ fun GymsScreen(
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GymCard(
gym: Gym,
onClick: () -> Unit
) {
Card(
onClick = onClick,
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
fun GymCard(gym: Gym, onClick: () -> Unit) {
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
Text(
text = gym.name,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
text = gym.name,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
gym.location?.let { location ->
Spacer(modifier = Modifier.height(4.dp))
Text(
text = location,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
text = location,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Spacer(modifier = Modifier.height(8.dp))
Row {
gym.supportedClimbTypes.forEach { climbType ->
AssistChip(
onClick = { },
label = {
Text(climbType.getDisplayName())
},
modifier = Modifier.padding(end = 4.dp)
onClick = {},
label = { Text(climbType.getDisplayName()) },
modifier = Modifier.padding(end = 4.dp)
)
}
}
if (gym.difficultySystems.isNotEmpty()) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Systems: ${gym.difficultySystems.joinToString(", ") { it.getDisplayName() }}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
text =
"Systems: ${gym.difficultySystems.joinToString(", ") { it.getDisplayName() }}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
gym.notes?.let { notes ->
if (notes.isNotBlank()) {
Spacer(modifier = Modifier.height(8.dp))
Text(
text = notes,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2
text = notes,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2
)
}
}

View File

@@ -17,6 +17,7 @@ import com.atridad.openclimb.data.model.Gym
import com.atridad.openclimb.data.model.Problem
import com.atridad.openclimb.ui.components.FullscreenImageViewer
import com.atridad.openclimb.ui.components.ImageDisplay
import com.atridad.openclimb.ui.components.SyncIndicator
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
@OptIn(ExperimentalMaterial3Api::class)
@@ -58,10 +59,12 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
tint = MaterialTheme.colorScheme.primary
)
Text(
text = "Problems & Routes",
text = "Climbing Problems",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f)
)
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
}
Spacer(modifier = Modifier.height(16.dp))

View File

@@ -20,160 +20,145 @@ import com.atridad.openclimb.R
import com.atridad.openclimb.data.model.ClimbSession
import com.atridad.openclimb.data.model.SessionStatus
import com.atridad.openclimb.ui.components.ActiveSessionBanner
import com.atridad.openclimb.ui.components.SyncIndicator
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionsScreen(
viewModel: ClimbViewModel,
onNavigateToSessionDetail: (String) -> Unit
) {
fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String) -> Unit) {
val context = LocalContext.current
val sessions by viewModel.sessions.collectAsState()
val gyms by viewModel.gyms.collectAsState()
val activeSession by viewModel.activeSession.collectAsState()
val uiState by viewModel.uiState.collectAsState()
// Filter out active sessions from regular session list
val completedSessions = sessions.filter { it.status == SessionStatus.COMPLETED }
val activeSessionGym = activeSession?.let { session ->
gyms.find { it.id == session.gymId }
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
val activeSessionGym = activeSession?.let { session -> gyms.find { it.id == session.gymId } }
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Icon(
painter = painterResource(id = R.drawable.ic_mountains),
contentDescription = "OpenClimb Logo",
modifier = Modifier.size(32.dp),
tint = MaterialTheme.colorScheme.primary
painter = painterResource(id = R.drawable.ic_mountains),
contentDescription = "OpenClimb Logo",
modifier = Modifier.size(32.dp),
tint = MaterialTheme.colorScheme.primary
)
Text(
text = "Climbing Sessions",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold
text = "Climbing Sessions",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f)
)
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
}
Spacer(modifier = Modifier.height(16.dp))
// Active session banner
ActiveSessionBanner(
activeSession = activeSession,
gym = activeSessionGym,
onSessionClick = {
activeSession?.let { onNavigateToSessionDetail(it.id) }
},
onEndSession = {
activeSession?.let {
viewModel.endSession(context, it.id)
}
}
activeSession = activeSession,
gym = activeSessionGym,
onSessionClick = { activeSession?.let { onNavigateToSessionDetail(it.id) } },
onEndSession = { activeSession?.let { viewModel.endSession(context, it.id) } }
)
if (activeSession != null) {
Spacer(modifier = Modifier.height(16.dp))
}
if (completedSessions.isEmpty() && activeSession == null) {
EmptyStateMessage(
title = if (gyms.isEmpty()) "No Gyms Available" else "No Sessions Yet",
message = if (gyms.isEmpty()) "Add a gym first to start tracking your climbing sessions!" else "Start your first climbing session!",
onActionClick = { },
actionText = ""
title = if (gyms.isEmpty()) "No Gyms Available" else "No Sessions Yet",
message =
if (gyms.isEmpty())
"Add a gym first to start tracking your climbing sessions!"
else "Start your first climbing session!",
onActionClick = {},
actionText = ""
)
} else {
LazyColumn {
items(completedSessions) { session ->
SessionCard(
session = session,
gymName = gyms.find { it.id == session.gymId }?.name ?: "Unknown Gym",
onClick = { onNavigateToSessionDetail(session.id) }
session = session,
gymName = gyms.find { it.id == session.gymId }?.name ?: "Unknown Gym",
onClick = { onNavigateToSessionDetail(session.id) }
)
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
// Show UI state messages and errors
uiState.message?.let { message ->
LaunchedEffect(message) {
kotlinx.coroutines.delay(5000)
viewModel.clearMessage()
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer
),
shape = RoundedCornerShape(12.dp)
modifier = Modifier.fillMaxWidth().padding(16.dp),
colors =
CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer
),
shape = RoundedCornerShape(12.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
modifier = Modifier.fillMaxWidth().padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
Icons.Default.CheckCircle,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
Icons.Default.CheckCircle,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer
text = message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
}
}
}
uiState.error?.let { error ->
LaunchedEffect(error) {
kotlinx.coroutines.delay(5000)
viewModel.clearError()
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer
),
shape = RoundedCornerShape(12.dp)
modifier = Modifier.fillMaxWidth().padding(16.dp),
colors =
CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer
),
shape = RoundedCornerShape(12.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
modifier = Modifier.fillMaxWidth().padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
Icons.Default.Warning,
contentDescription = null,
tint = MaterialTheme.colorScheme.error
Icons.Default.Warning,
contentDescription = null,
tint = MaterialTheme.colorScheme.error
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = error,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onErrorContainer
text = error,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
@@ -182,53 +167,42 @@ fun SessionsScreen(
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionCard(
session: ClimbSession,
gymName: String,
onClick: () -> Unit
) {
Card(
onClick = onClick,
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
fun SessionCard(session: ClimbSession, gymName: String, onClick: () -> Unit) {
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = gymName,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
text = gymName,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
text = formatDate(session.date),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
text = formatDate(session.date),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Spacer(modifier = Modifier.height(4.dp))
session.duration?.let { duration ->
Text(
text = "Duration: $duration minutes",
style = MaterialTheme.typography.bodyMedium
text = "Duration: $duration minutes",
style = MaterialTheme.typography.bodyMedium
)
}
session.notes?.let { notes ->
if (notes.isNotBlank()) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = notes,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2
text = notes,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2
)
}
}
@@ -238,38 +212,36 @@ fun SessionCard(
@Composable
fun EmptyStateMessage(
title: String,
message: String,
onActionClick: () -> Unit,
actionText: String
title: String,
message: String,
onActionClick: () -> Unit,
actionText: String
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = title,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
text = title,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = message,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
text = message,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
if (actionText.isNotEmpty()) {
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = onActionClick) {
Text(actionText)
}
Button(onClick = onActionClick) { Text(actionText) }
}
}
}

View File

@@ -5,6 +5,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.atridad.openclimb.data.model.*
import com.atridad.openclimb.data.repository.ClimbRepository
import com.atridad.openclimb.data.sync.SyncService
import com.atridad.openclimb.service.SessionTrackingService
import com.atridad.openclimb.utils.ImageUtils
import com.atridad.openclimb.utils.SessionShareUtils
@@ -15,7 +16,8 @@ import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ClimbViewModel(private val repository: ClimbRepository) : ViewModel() {
class ClimbViewModel(private val repository: ClimbRepository, val syncService: SyncService) :
ViewModel() {
// UI State flows
private val _uiState = MutableStateFlow(ClimbUiState())
@@ -112,6 +114,7 @@ class ClimbViewModel(private val repository: ClimbRepository) : ViewModel() {
viewModelScope.launch {
repository.insertProblem(problem)
ClimbStatsWidgetProvider.updateAllWidgets(context)
// Auto-sync now happens automatically via repository callback
}
}
@@ -265,6 +268,8 @@ class ClimbViewModel(private val repository: ClimbRepository) : ViewModel() {
ClimbStatsWidgetProvider.updateAllWidgets(context)
// Auto-sync now happens automatically via repository callback
_uiState.value = _uiState.value.copy(message = "Session completed!")
}
}
@@ -290,6 +295,7 @@ class ClimbViewModel(private val repository: ClimbRepository) : ViewModel() {
viewModelScope.launch {
repository.insertAttempt(attempt)
ClimbStatsWidgetProvider.updateAllWidgets(context)
// Auto-sync now happens automatically via repository callback
}
}
@@ -383,6 +389,23 @@ class ClimbViewModel(private val repository: ClimbRepository) : ViewModel() {
_uiState.value = _uiState.value.copy(error = null)
}
// Sync-related methods
suspend fun performManualSync() {
try {
syncService.syncWithServer()
} catch (e: Exception) {
setError("Sync failed: ${e.message}")
}
}
suspend fun testSyncConnection() {
try {
syncService.testConnection()
} catch (e: Exception) {
setError("Connection test failed: ${e.message}")
}
}
fun setError(message: String) {
_uiState.value = _uiState.value.copy(error = message)
}

View File

@@ -3,15 +3,17 @@ package com.atridad.openclimb.ui.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.atridad.openclimb.data.repository.ClimbRepository
import com.atridad.openclimb.data.sync.SyncService
class ClimbViewModelFactory(
private val repository: ClimbRepository
private val repository: ClimbRepository,
private val syncService: SyncService
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ClimbViewModel::class.java)) {
return ClimbViewModel(repository) as T
return ClimbViewModel(repository, syncService) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}

View File

@@ -0,0 +1,46 @@
package com.atridad.openclimb.utils
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
object DateFormatUtils {
// ISO 8601 formatter matching iOS date format exactly
private val ISO_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX").withZone(ZoneOffset.UTC)
/** Get current timestamp in iOS-compatible ISO 8601 format */
fun nowISO8601(): String {
return ISO_FORMATTER.format(Instant.now())
}
/** Format an Instant to iOS-compatible ISO 8601 format */
fun formatISO8601(instant: Instant): String {
return ISO_FORMATTER.format(instant)
}
/** Parse an iOS-compatible ISO 8601 date string back to Instant */
fun parseISO8601(dateString: String): Instant? {
return try {
Instant.from(ISO_FORMATTER.parse(dateString))
} catch (e: Exception) {
try {
Instant.parse(dateString)
} catch (e2: Exception) {
null
}
}
}
/** Validate that a date string matches the expected iOS format */
fun isValidISO8601(dateString: String): Boolean {
return parseISO8601(dateString) != null
}
/** Convert milliseconds timestamp to iOS-compatible ISO 8601 format */
fun millisToISO8601(millis: Long): String {
return ISO_FORMATTER.format(Instant.ofEpochMilli(millis))
}
}

View File

@@ -0,0 +1,101 @@
package com.atridad.openclimb.utils
import java.security.MessageDigest
import java.util.*
/**
* Utility for creating consistent image filenames across iOS and Android platforms. Uses
* deterministic naming based on problem ID and timestamp to ensure sync compatibility.
*/
object ImageNamingUtils {
private const val IMAGE_EXTENSION = ".jpg"
private const val HASH_LENGTH = 12 // First 12 chars of SHA-256
/** Generates a deterministic filename for a problem image */
fun generateImageFilename(problemId: String, timestamp: String, imageIndex: Int): String {
// Create a deterministic hash from problemId + timestamp + index
val input = "${problemId}_${timestamp}_${imageIndex}"
val hash = createHash(input)
return "problem_${hash}_${imageIndex}${IMAGE_EXTENSION}"
}
/** Generates a deterministic filename using current timestamp */
fun generateImageFilename(problemId: String, imageIndex: Int): String {
val timestamp = DateFormatUtils.nowISO8601()
return generateImageFilename(problemId, timestamp, imageIndex)
}
/** Extracts problem ID from an image filename */
fun extractProblemIdFromFilename(filename: String): String? {
if (!filename.startsWith("problem_") || !filename.endsWith(IMAGE_EXTENSION)) {
return null
}
// Format: problem_{hash}_{index}.jpg
val nameWithoutExtension = filename.substring(0, filename.length - IMAGE_EXTENSION.length)
val parts = nameWithoutExtension.split("_")
if (parts.size != 3 || parts[0] != "problem") {
return null
}
// We can't extract the original problem ID from the hash,
// but we can validate the format
return parts[1] // Return the hash as identifier
}
/** Validates if a filename follows our naming convention */
fun isValidImageFilename(filename: String): Boolean {
if (!filename.startsWith("problem_") || !filename.endsWith(IMAGE_EXTENSION)) {
return false
}
val nameWithoutExtension = filename.substring(0, filename.length - IMAGE_EXTENSION.length)
val parts = nameWithoutExtension.split("_")
return parts.size == 3 &&
parts[0] == "problem" &&
parts[1].length == HASH_LENGTH &&
parts[2].toIntOrNull() != null
}
/** Migrates an existing filename to our naming convention */
fun migrateFilename(oldFilename: String, problemId: String, imageIndex: Int): String {
// If it's already using our convention, keep it
if (isValidImageFilename(oldFilename)) {
return oldFilename
}
// Generate new deterministic name
// Use a timestamp based on the old filename to maintain some consistency
val timestamp = DateFormatUtils.nowISO8601()
return generateImageFilename(problemId, timestamp, imageIndex)
}
/** Creates a deterministic hash from input string */
private fun createHash(input: String): String {
val digest = MessageDigest.getInstance("SHA-256")
val hashBytes = digest.digest(input.toByteArray(Charsets.UTF_8))
val hashHex = hashBytes.joinToString("") { "%02x".format(it) }
return hashHex.take(HASH_LENGTH)
}
/** Batch renames images for a problem to use our naming convention */
fun batchRenameForProblem(
problemId: String,
existingFilenames: List<String>
): Map<String, String> {
val renameMap = mutableMapOf<String, String>()
existingFilenames.forEachIndexed { index, oldFilename ->
val newFilename = migrateFilename(oldFilename, problemId, index)
if (newFilename != oldFilename) {
renameMap[oldFilename] = newFilename
}
}
return renameMap
}
}

View File

@@ -5,20 +5,18 @@ import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.core.graphics.scale
import java.io.File
import java.io.FileOutputStream
import java.util.UUID
import androidx.core.graphics.scale
object ImageUtils {
private const val IMAGES_DIR = "problem_images"
private const val MAX_IMAGE_SIZE = 1024
private const val IMAGE_QUALITY = 85
/**
* Creates the images directory if it doesn't exist
*/
// Creates the images directory if it doesn't exist
private fun getImagesDirectory(context: Context): File {
val imagesDir = File(context.filesDir, IMAGES_DIR)
if (!imagesDir.exists()) {
@@ -26,60 +24,62 @@ object ImageUtils {
}
return imagesDir
}
/**
* Saves an image from URI to app's private storage with compression
* @param context Android context
* @param imageUri URI of the image to save
* @return The relative file path if successful, null otherwise
*/
fun saveImageFromUri(context: Context, imageUri: Uri): String? {
/** Saves an image from a URI with compression and proper orientation */
fun saveImageFromUri(
context: Context,
imageUri: Uri,
problemId: String? = null,
imageIndex: Int? = null
): String? {
return try {
// Decode bitmap from a fresh stream to avoid mark/reset dependency
val originalBitmap = context.contentResolver.openInputStream(imageUri)?.use { input ->
BitmapFactory.decodeStream(input)
} ?: return null
val originalBitmap =
context.contentResolver.openInputStream(imageUri)?.use { input ->
BitmapFactory.decodeStream(input)
}
?: return null
val orientedBitmap = correctImageOrientation(context, imageUri, originalBitmap)
val compressedBitmap = compressImage(orientedBitmap)
// Generate unique filename
val filename = "${UUID.randomUUID()}.jpg"
val filename =
if (problemId != null && imageIndex != null) {
ImageNamingUtils.generateImageFilename(problemId, imageIndex)
} else {
"${UUID.randomUUID()}.jpg"
}
val imageFile = File(getImagesDirectory(context), filename)
// Save compressed image
FileOutputStream(imageFile).use { output ->
compressedBitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, output)
}
// Clean up bitmaps
originalBitmap.recycle()
if (orientedBitmap != originalBitmap) {
orientedBitmap.recycle()
}
compressedBitmap.recycle()
// Return relative path
"$IMAGES_DIR/$filename"
} catch (e: Exception) {
e.printStackTrace()
null
}
}
/**
* Corrects image orientation based on EXIF data
*/
/** Corrects image orientation based on EXIF data */
private fun correctImageOrientation(context: Context, imageUri: Uri, bitmap: Bitmap): Bitmap {
return try {
val inputStream = context.contentResolver.openInputStream(imageUri)
inputStream?.use { input ->
val exif = android.media.ExifInterface(input)
val orientation = exif.getAttributeInt(
android.media.ExifInterface.TAG_ORIENTATION,
android.media.ExifInterface.ORIENTATION_NORMAL
)
val orientation =
exif.getAttributeInt(
android.media.ExifInterface.TAG_ORIENTATION,
android.media.ExifInterface.ORIENTATION_NORMAL
)
val matrix = android.graphics.Matrix()
when (orientation) {
android.media.ExifInterface.ORIENTATION_ROTATE_90 -> {
@@ -106,36 +106,42 @@ object ImageUtils {
matrix.postScale(-1f, 1f)
}
}
if (matrix.isIdentity) {
bitmap
} else {
android.graphics.Bitmap.createBitmap(
bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true
bitmap,
0,
0,
bitmap.width,
bitmap.height,
matrix,
true
)
}
} ?: bitmap
}
?: bitmap
} catch (e: Exception) {
e.printStackTrace()
bitmap
}
}
/**
* Compresses and resizes an image bitmap
*/
/** Compresses and resizes an image bitmap */
@SuppressLint("UseKtx")
private fun compressImage(original: Bitmap): Bitmap {
val width = original.width
val height = original.height
// Calculate the scaling factor
val scaleFactor = if (width > height) {
if (width > MAX_IMAGE_SIZE) MAX_IMAGE_SIZE.toFloat() / width else 1f
} else {
if (height > MAX_IMAGE_SIZE) MAX_IMAGE_SIZE.toFloat() / height else 1f
}
val scaleFactor =
if (width > height) {
if (width > MAX_IMAGE_SIZE) MAX_IMAGE_SIZE.toFloat() / width else 1f
} else {
if (height > MAX_IMAGE_SIZE) MAX_IMAGE_SIZE.toFloat() / height else 1f
}
return if (scaleFactor < 1f) {
val newWidth = (width * scaleFactor).toInt()
val newHeight = (height * scaleFactor).toInt()
@@ -144,23 +150,20 @@ object ImageUtils {
original
}
}
/**
* Gets the full file path for an image
* @param context Android context
* @param relativePath The relative path returned by saveImageFromUri
* @return Full file path
*/
/** Gets the full file path for an image */
fun getImageFile(context: Context, relativePath: String): File {
return File(context.filesDir, relativePath)
// If relativePath already contains the directory, use it as-is
// Otherwise, assume it's just a filename and add the images directory
return if (relativePath.contains("/")) {
File(context.filesDir, relativePath)
} else {
// Just a filename - look in the images directory
File(getImagesDirectory(context), relativePath)
}
}
/**
* Deletes an image file
* @param context Android context
* @param relativePath The relative path of the image to delete
* @return true if deleted successfully, false otherwise
*/
/** Deletes an image file */
fun deleteImage(context: Context, relativePath: String): Boolean {
return try {
val file = getImageFile(context, relativePath)
@@ -171,21 +174,16 @@ object ImageUtils {
}
}
/**
* Imports an image file from the import directory
* @param context Android context
* @param sourceFile The source image file to import
* @return The relative path in app storage, null if failed
*/
/** Imports an image file from the import directory */
fun importImageFile(context: Context, sourceFile: File): String? {
return try {
if (!sourceFile.exists()) return null
// Generate new filename to avoid conflicts
val extension = sourceFile.extension.ifEmpty { "jpg" }
val filename = "${UUID.randomUUID()}.$extension"
val destFile = File(getImagesDirectory(context), filename)
sourceFile.copyTo(destFile, overwrite = true)
"$IMAGES_DIR/$filename"
} catch (e: Exception) {
@@ -193,39 +191,139 @@ object ImageUtils {
null
}
}
/**
* Gets all image files in the images directory
* @param context Android context
* @return List of relative paths for all images
*/
/** Gets all image files in the images directory */
fun getAllImages(context: Context): List<String> {
return try {
val imagesDir = getImagesDirectory(context)
imagesDir.listFiles()?.mapNotNull { file ->
if (file.isFile && (file.extension == "jpg" || file.extension == "jpeg" || file.extension == "png")) {
if (file.isFile &&
(file.extension == "jpg" ||
file.extension == "jpeg" ||
file.extension == "png")
) {
"$IMAGES_DIR/${file.name}"
} else null
} ?: emptyList()
}
?: emptyList()
} catch (e: Exception) {
e.printStackTrace()
emptyList()
}
}
/**
* Cleans up orphaned images that are not referenced by any problems
* @param context Android context
* @param referencedPaths Set of image paths that are still being used
*/
/** Saves an image from byte array to app's private storage */
fun saveImageFromBytes(context: Context, imageData: ByteArray): String? {
return try {
val bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.size) ?: return null
val compressedBitmap = compressImage(bitmap)
// Generate unique filename
val filename = "${UUID.randomUUID()}.jpg"
val imageFile = File(getImagesDirectory(context), filename)
// Save compressed image
FileOutputStream(imageFile).use { output ->
compressedBitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, output)
}
// Clean up bitmaps
bitmap.recycle()
compressedBitmap.recycle()
// Return relative path
"$IMAGES_DIR/$filename"
} catch (e: Exception) {
e.printStackTrace()
null
}
}
/** Saves image data with a specific filename */
fun saveImageFromBytesWithFilename(
context: Context,
imageData: ByteArray,
filename: String
): String? {
return try {
val bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.size) ?: return null
val compressedBitmap = compressImage(bitmap)
// Use the provided filename instead of generating a new UUID
val imageFile = File(getImagesDirectory(context), filename)
// Save compressed image
FileOutputStream(imageFile).use { output ->
compressedBitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, output)
}
// Clean up bitmaps
bitmap.recycle()
compressedBitmap.recycle()
// Return relative path
"$IMAGES_DIR/$filename"
} catch (e: Exception) {
e.printStackTrace()
null
}
}
/** Migrates existing images to use consistent naming convention */
fun migrateImageNaming(
context: Context,
problemId: String,
currentImagePaths: List<String>
): Map<String, String> {
val migrationMap = mutableMapOf<String, String>()
currentImagePaths.forEachIndexed { index, oldPath ->
val oldFilename = oldPath.substringAfterLast('/')
val newFilename = ImageNamingUtils.migrateFilename(oldFilename, problemId, index)
if (oldFilename != newFilename) {
try {
val oldFile = getImageFile(context, oldPath)
val newFile = File(getImagesDirectory(context), newFilename)
if (oldFile.exists() && oldFile.renameTo(newFile)) {
val newPath = "$IMAGES_DIR/$newFilename"
migrationMap[oldPath] = newPath
}
} catch (e: Exception) {
// Log error but continue with other images
e.printStackTrace()
}
}
}
return migrationMap
}
/** Batch migrates all images in the system to use consistent naming */
fun batchMigrateAllImages(
context: Context,
problemImageMap: Map<String, List<String>>
): Map<String, String> {
val allMigrations = mutableMapOf<String, String>()
problemImageMap.forEach { (problemId, imagePaths) ->
val migrations = migrateImageNaming(context, problemId, imagePaths)
allMigrations.putAll(migrations)
}
return allMigrations
}
/** Cleans up orphaned images that are not referenced by any problems */
fun cleanupOrphanedImages(context: Context, referencedPaths: Set<String>) {
try {
val allImages = getAllImages(context)
val orphanedImages = allImages.filter { it !in referencedPaths }
orphanedImages.forEach { path ->
deleteImage(context, path)
}
orphanedImages.forEach { path -> deleteImage(context, path) }
} catch (e: Exception) {
e.printStackTrace()
}

View File

@@ -481,10 +481,7 @@ object SessionShareUtils {
action = Intent.ACTION_SEND
type = "image/png"
putExtra(Intent.EXTRA_STREAM, uri)
putExtra(
Intent.EXTRA_TEXT,
"Check out my climbing session! 🧗‍♀️ #OpenClimb"
)
putExtra(Intent.EXTRA_TEXT, "Check out my climbing session! #OpenClimb")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}

View File

@@ -20,14 +20,7 @@ object ZipExportImportUtils {
private const val IMAGES_DIR_NAME = "images"
private const val METADATA_FILENAME = "metadata.txt"
/**
* Creates a ZIP file containing the JSON data and all referenced images
* @param context Android context
* @param exportData The data to export (should be serializable)
* @param referencedImagePaths Set of image paths referenced in the data
* @param directory Optional directory to save to, uses default if null
* @return The created ZIP file
*/
/** Creates a ZIP file containing the JSON data and all referenced images */
fun createExportZip(
context: Context,
exportData: ClimbDataBackup,
@@ -120,13 +113,7 @@ object ZipExportImportUtils {
}
}
/**
* Creates a ZIP file and writes it to a provided URI
* @param context Android context
* @param uri The URI to write to
* @param exportData The data to export
* @param referencedImagePaths Set of image paths referenced in the data
*/
/** Creates a ZIP file and writes it to a provided URI */
fun createExportZipToUri(
context: Context,
uri: android.net.Uri,
@@ -214,12 +201,7 @@ object ZipExportImportUtils {
val importedImagePaths: Map<String, String> // original filename -> new relative path
)
/**
* Extracts a ZIP file and returns the JSON content and imported image paths
* @param context Android context
* @param zipFile The ZIP file to extract
* @return ImportResult containing the JSON and image path mappings
*/
/** Extracts a ZIP file and returns the JSON content and imported image paths */
fun extractImportZip(context: Context, zipFile: File): ImportResult {
var jsonContent = ""
val importedImagePaths = mutableMapOf<String, String>()

View File

@@ -0,0 +1,603 @@
package com.atridad.openclimb
import com.atridad.openclimb.data.format.*
import com.atridad.openclimb.data.model.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import org.junit.Assert.*
import org.junit.Test
/**
* Business logic and integration tests for OpenClimb Android app. Tests complex workflows, business
* rules, and data relationships.
*/
class BusinessLogicTests {
@Test
fun testClimbSessionLifecycle() {
val gym = createTestGym()
val session = ClimbSession.create(gym.id, "Test session notes")
assertEquals(gym.id, session.gymId)
assertEquals(SessionStatus.ACTIVE, session.status)
assertNotNull(session.startTime)
assertNull(session.endTime)
assertNull(session.duration)
val completedSession =
session.copy(
status = SessionStatus.COMPLETED,
endTime = getCurrentTimestamp(),
duration = 7200L
)
assertEquals(SessionStatus.COMPLETED, completedSession.status)
assertNotNull(completedSession.endTime)
assertNotNull(completedSession.duration)
}
@Test
fun testAttemptCreationAndValidation() {
val gym = createTestGym()
val problem = createTestProblem(gym.id)
val session = ClimbSession.create(gym.id)
val attempt =
Attempt.create(
sessionId = session.id,
problemId = problem.id,
result = AttemptResult.SUCCESS,
notes = "Clean send!"
)
assertEquals(session.id, attempt.sessionId)
assertEquals(problem.id, attempt.problemId)
assertEquals(AttemptResult.SUCCESS, attempt.result)
assertEquals("Clean send!", attempt.notes)
assertNotNull(attempt.timestamp)
assertNotNull(attempt.createdAt)
}
@Test
fun testGymProblemRelationship() {
val gym = createTestGym()
val boulderProblem = createTestProblem(gym.id, ClimbType.BOULDER)
val ropeProblem = createTestProblem(gym.id, ClimbType.ROPE)
// Verify boulder problem uses compatible difficulty system
assertTrue(gym.supportedClimbTypes.contains(boulderProblem.climbType))
assertTrue(gym.difficultySystems.contains(boulderProblem.difficulty.system))
// Verify rope problem uses compatible difficulty system
assertTrue(gym.supportedClimbTypes.contains(ropeProblem.climbType))
assertTrue(gym.difficultySystems.contains(ropeProblem.difficulty.system))
}
@Test
fun testSessionAttemptAggregation() {
val gym = createTestGym()
val session = ClimbSession.create(gym.id)
val problem1 = createTestProblem(gym.id)
val problem2 = createTestProblem(gym.id)
val attempts =
listOf(
Attempt.create(session.id, problem1.id, AttemptResult.SUCCESS),
Attempt.create(session.id, problem1.id, AttemptResult.FALL),
Attempt.create(session.id, problem2.id, AttemptResult.FLASH),
Attempt.create(session.id, problem2.id, AttemptResult.SUCCESS)
)
val sessionStats = calculateSessionStatistics(session, attempts)
assertEquals(4, sessionStats.totalAttempts)
assertEquals(3, sessionStats.successfulAttempts)
assertEquals(2, sessionStats.uniqueProblems)
assertEquals(75.0, sessionStats.successRate, 0.01)
}
@Test
fun testDifficultyProgressionTracking() {
val gym = createTestGym()
val session = ClimbSession.create(gym.id)
val problems =
listOf(
createTestProblemWithGrade(gym.id, "V3"),
createTestProblemWithGrade(gym.id, "V4"),
createTestProblemWithGrade(gym.id, "V5"),
createTestProblemWithGrade(gym.id, "V6")
)
val attempts =
problems.map { problem ->
Attempt.create(session.id, problem.id, AttemptResult.SUCCESS)
}
val progression = calculateDifficultyProgression(attempts, problems)
assertEquals("V3", progression.minGrade)
assertEquals("V6", progression.maxGrade)
assertEquals(4.5, progression.averageGrade, 0.1)
assertTrue(progression.showsProgression)
}
@Test
fun testBackupDataIntegrity() {
val gym = createTestGym()
val problems = listOf(createTestProblem(gym.id), createTestProblem(gym.id))
val session = ClimbSession.create(gym.id)
val attempts =
problems.map { problem ->
Attempt.create(session.id, problem.id, AttemptResult.SUCCESS)
}
val backup =
createBackupData(
gyms = listOf(gym),
problems = problems,
sessions = listOf(session),
attempts = attempts
)
validateBackupIntegrity(backup)
assertEquals(1, backup.gyms.size)
assertEquals(2, backup.problems.size)
assertEquals(1, backup.sessions.size)
assertEquals(2, backup.attempts.size)
}
@Test
fun testClimbTypeCompatibilityRules() {
val boulderGym =
Gym(
id = "boulder_gym",
name = "Boulder Gym",
location = "Boulder City",
supportedClimbTypes = listOf(ClimbType.BOULDER),
difficultySystems = listOf(DifficultySystem.V_SCALE, DifficultySystem.FONT),
customDifficultyGrades = emptyList(),
notes = null,
createdAt = getCurrentTimestamp(),
updatedAt = getCurrentTimestamp()
)
val ropeGym =
Gym(
id = "rope_gym",
name = "Rope Gym",
location = "Rope City",
supportedClimbTypes = listOf(ClimbType.ROPE),
difficultySystems = listOf(DifficultySystem.YDS),
customDifficultyGrades = emptyList(),
notes = null,
createdAt = getCurrentTimestamp(),
updatedAt = getCurrentTimestamp()
)
// Boulder gym should support boulder problems with V-Scale
assertTrue(isCompatibleClimbType(boulderGym, ClimbType.BOULDER, DifficultySystem.V_SCALE))
assertTrue(isCompatibleClimbType(boulderGym, ClimbType.BOULDER, DifficultySystem.FONT))
assertFalse(isCompatibleClimbType(boulderGym, ClimbType.ROPE, DifficultySystem.YDS))
// Rope gym should support rope problems with YDS
assertTrue(isCompatibleClimbType(ropeGym, ClimbType.ROPE, DifficultySystem.YDS))
assertFalse(isCompatibleClimbType(ropeGym, ClimbType.BOULDER, DifficultySystem.V_SCALE))
}
@Test
fun testSessionDurationCalculation() {
val startTime = "2024-01-01T10:00:00Z"
val endTime = "2024-01-01T12:30:00Z"
val calculatedDuration = calculateSessionDuration(startTime, endTime)
assertEquals(9000L, calculatedDuration) // 2.5 hours = 9000 seconds
}
@Test
fun testAttemptSequenceValidation() {
val gym = createTestGym()
val problem = createTestProblem(gym.id)
val session = ClimbSession.create(gym.id)
val attempts =
listOf(
createAttemptWithTimestamp(
session.id,
problem.id,
"2024-01-01T10:00:00Z",
AttemptResult.FALL
),
createAttemptWithTimestamp(
session.id,
problem.id,
"2024-01-01T10:05:00Z",
AttemptResult.FALL
),
createAttemptWithTimestamp(
session.id,
problem.id,
"2024-01-01T10:10:00Z",
AttemptResult.SUCCESS
)
)
val sequence = AttemptSequence(attempts)
assertEquals(3, sequence.totalAttempts)
assertEquals(2, sequence.failedAttempts)
assertEquals(1, sequence.successfulAttempts)
assertTrue(sequence.isValidSequence())
assertEquals(AttemptResult.SUCCESS, sequence.finalResult)
}
@Test
fun testGradeConsistencyValidation() {
val validCombinations =
listOf(
Pair(ClimbType.BOULDER, DifficultySystem.V_SCALE),
Pair(ClimbType.BOULDER, DifficultySystem.FONT),
Pair(ClimbType.ROPE, DifficultySystem.YDS),
Pair(ClimbType.BOULDER, DifficultySystem.CUSTOM),
Pair(ClimbType.ROPE, DifficultySystem.CUSTOM)
)
val invalidCombinations =
listOf(
Pair(ClimbType.BOULDER, DifficultySystem.YDS),
Pair(ClimbType.ROPE, DifficultySystem.V_SCALE),
Pair(ClimbType.ROPE, DifficultySystem.FONT)
)
validCombinations.forEach { (climbType, difficultySystem) ->
assertTrue(
"$climbType should be compatible with $difficultySystem",
isValidGradeCombination(climbType, difficultySystem)
)
}
invalidCombinations.forEach { (climbType, difficultySystem) ->
assertFalse(
"$climbType should not be compatible with $difficultySystem",
isValidGradeCombination(climbType, difficultySystem)
)
}
}
@Test
fun testProblemTagNormalization() {
val rawTags = listOf("OVERHANG", "crimpy", " Technical ", "DYNAMIC", "")
val normalizedTags = normalizeTags(rawTags)
assertEquals(4, normalizedTags.size)
assertTrue(normalizedTags.contains("overhang"))
assertTrue(normalizedTags.contains("crimpy"))
assertTrue(normalizedTags.contains("technical"))
assertTrue(normalizedTags.contains("dynamic"))
assertFalse(normalizedTags.contains(""))
}
@Test
fun testImagePathHandling() {
val originalPaths =
listOf(
"/storage/images/problem1.jpg",
"/data/cache/problem2.png",
"relative/path/problem3.jpeg"
)
val relativePaths = convertToRelativePaths(originalPaths)
assertEquals(3, relativePaths.size)
assertTrue(relativePaths.all { !it.startsWith("/") })
assertTrue(relativePaths.contains("problem1.jpg"))
assertTrue(relativePaths.contains("problem2.png"))
assertTrue(relativePaths.contains("problem3.jpeg"))
}
// Helper functions and data classes
private fun createTestGym(): Gym {
return Gym(
id = "test_gym_1",
name = "Test Climbing Gym",
location = "Test City",
supportedClimbTypes = listOf(ClimbType.BOULDER, ClimbType.ROPE),
difficultySystems = listOf(DifficultySystem.V_SCALE, DifficultySystem.YDS),
customDifficultyGrades = emptyList(),
notes = "Test gym for unit testing",
createdAt = getCurrentTimestamp(),
updatedAt = getCurrentTimestamp()
)
}
private fun createTestProblem(
gymId: String,
climbType: ClimbType = ClimbType.BOULDER
): Problem {
val difficulty =
when (climbType) {
ClimbType.BOULDER -> DifficultyGrade(DifficultySystem.V_SCALE, "V5")
ClimbType.ROPE -> DifficultyGrade(DifficultySystem.YDS, "5.10a")
}
return Problem(
id = "test_problem_${java.util.UUID.randomUUID()}",
gymId = gymId,
name = "Test Problem",
description = "A test climbing problem",
climbType = climbType,
difficulty = difficulty,
tags = listOf("test", "overhang"),
location = "Wall A",
imagePaths = emptyList(),
isActive = true,
dateSet = "2024-01-01",
notes = null,
createdAt = getCurrentTimestamp(),
updatedAt = getCurrentTimestamp()
)
}
private fun createTestProblemWithGrade(gymId: String, grade: String): Problem {
return Problem(
id = "test_problem_${java.util.UUID.randomUUID()}",
gymId = gymId,
name = "Test Problem $grade",
description = null,
climbType = ClimbType.BOULDER,
difficulty = DifficultyGrade(DifficultySystem.V_SCALE, grade),
tags = emptyList(),
location = null,
imagePaths = emptyList(),
isActive = true,
dateSet = null,
notes = null,
createdAt = getCurrentTimestamp(),
updatedAt = getCurrentTimestamp()
)
}
private fun createAttemptWithTimestamp(
sessionId: String,
problemId: String,
timestamp: String,
result: AttemptResult
): Attempt {
return Attempt.create(
sessionId = sessionId,
problemId = problemId,
result = result,
timestamp = timestamp
)
}
private fun getCurrentTimestamp(): String {
return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "Z"
}
private fun calculateSessionStatistics(
session: ClimbSession,
attempts: List<Attempt>
): SessionStatistics {
val successful =
attempts.count {
it.result == AttemptResult.SUCCESS || it.result == AttemptResult.FLASH
}
val uniqueProblems = attempts.map { it.problemId }.toSet().size
val successRate = (successful.toDouble() / attempts.size) * 100
return SessionStatistics(
totalAttempts = attempts.size,
successfulAttempts = successful,
uniqueProblems = uniqueProblems,
successRate = successRate
)
}
private fun calculateDifficultyProgression(
attempts: List<Attempt>,
problems: List<Problem>
): DifficultyProgression {
val problemMap = problems.associateBy { it.id }
val grades =
attempts
.mapNotNull { attempt -> problemMap[attempt.problemId]?.difficulty?.grade }
.filter { it.startsWith("V") }
val numericGrades =
grades.mapNotNull { grade ->
when (grade) {
"VB" -> 0
else -> grade.removePrefix("V").toIntOrNull()
}
}
val minGrade = "V${numericGrades.minOrNull() ?: 0}".replace("V0", "VB")
val maxGrade = "V${numericGrades.maxOrNull() ?: 0}".replace("V0", "VB")
val avgGrade = numericGrades.average()
val showsProgression =
numericGrades.size > 1 &&
(numericGrades.maxOrNull() ?: 0) > (numericGrades.minOrNull() ?: 0)
return DifficultyProgression(minGrade, maxGrade, avgGrade, showsProgression)
}
private fun createBackupData(
gyms: List<Gym>,
problems: List<Problem>,
sessions: List<ClimbSession>,
attempts: List<Attempt>
): ClimbDataBackup {
return ClimbDataBackup(
exportedAt = getCurrentTimestamp(),
version = "2.0",
formatVersion = "2.0",
gyms =
gyms.map { gym ->
BackupGym(
id = gym.id,
name = gym.name,
location = gym.location,
supportedClimbTypes = gym.supportedClimbTypes,
difficultySystems = gym.difficultySystems,
customDifficultyGrades = gym.customDifficultyGrades,
notes = gym.notes,
createdAt = gym.createdAt,
updatedAt = gym.updatedAt
)
},
problems =
problems.map { problem ->
BackupProblem(
id = problem.id,
gymId = problem.gymId,
name = problem.name,
description = problem.description,
climbType = problem.climbType,
difficulty = problem.difficulty,
tags = problem.tags,
location = problem.location,
imagePaths = problem.imagePaths,
isActive = problem.isActive,
dateSet = problem.dateSet,
notes = problem.notes,
createdAt = problem.createdAt,
updatedAt = problem.updatedAt
)
},
sessions =
sessions.map { session ->
BackupClimbSession(
id = session.id,
gymId = session.gymId,
date = session.date,
startTime = session.startTime,
endTime = session.endTime,
duration = session.duration,
status = session.status,
notes = session.notes,
createdAt = session.createdAt,
updatedAt = session.updatedAt
)
},
attempts =
attempts.map { attempt ->
BackupAttempt(
id = attempt.id,
sessionId = attempt.sessionId,
problemId = attempt.problemId,
result = attempt.result,
highestHold = attempt.highestHold,
notes = attempt.notes,
duration = attempt.duration,
restTime = attempt.restTime,
timestamp = attempt.timestamp,
createdAt = attempt.createdAt
)
}
)
}
private fun validateBackupIntegrity(backup: ClimbDataBackup) {
// Verify all gym references exist
val gymIds = backup.gyms.map { it.id }.toSet()
backup.problems.forEach { problem ->
assertTrue(
"Problem ${problem.id} references non-existent gym ${problem.gymId}",
gymIds.contains(problem.gymId)
)
}
// Verify all session references exist
val sessionIds = backup.sessions.map { it.id }.toSet()
backup.attempts.forEach { attempt ->
assertTrue(
"Attempt ${attempt.id} references non-existent session ${attempt.sessionId}",
sessionIds.contains(attempt.sessionId)
)
}
// Verify all problem references exist
val problemIds = backup.problems.map { it.id }.toSet()
backup.attempts.forEach { attempt ->
assertTrue(
"Attempt ${attempt.id} references non-existent problem ${attempt.problemId}",
problemIds.contains(attempt.problemId)
)
}
}
private fun isCompatibleClimbType(
gym: Gym,
climbType: ClimbType,
difficultySystem: DifficultySystem
): Boolean {
return gym.supportedClimbTypes.contains(climbType) &&
gym.difficultySystems.contains(difficultySystem)
}
private fun calculateSessionDuration(startTime: String, endTime: String): Long {
// Simplified duration calculation (in seconds)
// In real implementation, would use proper date parsing
return 9000L // 2.5 hours for test
}
private fun isValidGradeCombination(
climbType: ClimbType,
difficultySystem: DifficultySystem
): Boolean {
return when (climbType) {
ClimbType.BOULDER ->
difficultySystem in
listOf(
DifficultySystem.V_SCALE,
DifficultySystem.FONT,
DifficultySystem.CUSTOM
)
ClimbType.ROPE ->
difficultySystem in listOf(DifficultySystem.YDS, DifficultySystem.CUSTOM)
}
}
private fun normalizeTags(tags: List<String>): List<String> {
return tags.map { it.trim().lowercase() }.filter { it.isNotEmpty() }
}
private fun convertToRelativePaths(paths: List<String>): List<String> {
return paths.map { path -> path.substringAfterLast('/') }
}
// Data classes for testing
data class SessionStatistics(
val totalAttempts: Int,
val successfulAttempts: Int,
val uniqueProblems: Int,
val successRate: Double
)
data class DifficultyProgression(
val minGrade: String,
val maxGrade: String,
val averageGrade: Double,
val showsProgression: Boolean
)
data class AttemptSequence(val attempts: List<Attempt>) {
val totalAttempts = attempts.size
val failedAttempts =
attempts.count {
it.result == AttemptResult.FALL || it.result == AttemptResult.NO_PROGRESS
}
val successfulAttempts =
attempts.count {
it.result == AttemptResult.SUCCESS || it.result == AttemptResult.FLASH
}
val finalResult = attempts.lastOrNull()?.result
fun isValidSequence(): Boolean {
return attempts.isNotEmpty() && attempts.all { it.timestamp.isNotEmpty() }
}
}
}

View File

@@ -0,0 +1,575 @@
package com.atridad.openclimb
import com.atridad.openclimb.data.format.*
import com.atridad.openclimb.data.model.*
import java.time.Instant
import java.time.format.DateTimeFormatter
import org.junit.Assert.*
import org.junit.Test
/**
* Comprehensive unit tests for OpenClimb Android data models and utilities. These tests verify core
* functionality without requiring Android context.
*/
class DataModelTests {
@Test
fun testClimbTypeEnumValues() {
val expectedTypes = setOf("ROPE", "BOULDER")
val actualTypes = ClimbType.entries.map { it.name }.toSet()
assertEquals(expectedTypes, actualTypes)
}
@Test
fun testClimbTypeDisplayNames() {
assertEquals("Rope", ClimbType.ROPE.getDisplayName())
assertEquals("Bouldering", ClimbType.BOULDER.getDisplayName())
}
@Test
fun testDifficultySystemEnumValues() {
val systems = DifficultySystem.entries
assertTrue(systems.contains(DifficultySystem.V_SCALE))
assertTrue(systems.contains(DifficultySystem.YDS))
assertTrue(systems.contains(DifficultySystem.FONT))
assertTrue(systems.contains(DifficultySystem.CUSTOM))
assertEquals(4, systems.size)
}
@Test
fun testDifficultySystemDisplayNames() {
assertEquals("V Scale", DifficultySystem.V_SCALE.getDisplayName())
assertEquals("YDS (Yosemite)", DifficultySystem.YDS.getDisplayName())
assertEquals("Font Scale", DifficultySystem.FONT.getDisplayName())
assertEquals("Custom", DifficultySystem.CUSTOM.getDisplayName())
}
@Test
fun testDifficultySystemClimbTypeCompatibility() {
// Test bouldering systems
assertTrue(DifficultySystem.V_SCALE.isBoulderingSystem())
assertTrue(DifficultySystem.FONT.isBoulderingSystem())
assertFalse(DifficultySystem.YDS.isBoulderingSystem())
assertTrue(DifficultySystem.CUSTOM.isBoulderingSystem())
// Test rope systems
assertTrue(DifficultySystem.YDS.isRopeSystem())
assertFalse(DifficultySystem.V_SCALE.isRopeSystem())
assertFalse(DifficultySystem.FONT.isRopeSystem())
assertTrue(DifficultySystem.CUSTOM.isRopeSystem())
}
@Test
fun testDifficultySystemAvailableGrades() {
val vScaleGrades = DifficultySystem.V_SCALE.getAvailableGrades()
assertTrue(vScaleGrades.contains("VB"))
assertTrue(vScaleGrades.contains("V0"))
assertTrue(vScaleGrades.contains("V17"))
assertEquals("VB", vScaleGrades.first())
val ydsGrades = DifficultySystem.YDS.getAvailableGrades()
assertTrue(ydsGrades.contains("5.0"))
assertTrue(ydsGrades.contains("5.15d"))
assertTrue(ydsGrades.contains("5.10a"))
val fontGrades = DifficultySystem.FONT.getAvailableGrades()
assertTrue(fontGrades.contains("3"))
assertTrue(fontGrades.contains("8C+"))
assertTrue(fontGrades.contains("6A"))
val customGrades = DifficultySystem.CUSTOM.getAvailableGrades()
assertTrue(customGrades.isEmpty())
}
@Test
fun testDifficultySystemsForClimbType() {
val boulderSystems = DifficultySystem.getSystemsForClimbType(ClimbType.BOULDER)
assertTrue(boulderSystems.contains(DifficultySystem.V_SCALE))
assertTrue(boulderSystems.contains(DifficultySystem.FONT))
assertTrue(boulderSystems.contains(DifficultySystem.CUSTOM))
assertFalse(boulderSystems.contains(DifficultySystem.YDS))
val ropeSystems = DifficultySystem.getSystemsForClimbType(ClimbType.ROPE)
assertTrue(ropeSystems.contains(DifficultySystem.YDS))
assertTrue(ropeSystems.contains(DifficultySystem.CUSTOM))
assertFalse(ropeSystems.contains(DifficultySystem.V_SCALE))
assertFalse(ropeSystems.contains(DifficultySystem.FONT))
}
@Test
fun testDifficultyGradeCreation() {
val grade = DifficultyGrade(DifficultySystem.V_SCALE, "V5")
assertEquals(DifficultySystem.V_SCALE, grade.system)
assertEquals("V5", grade.grade)
assertEquals(5, grade.numericValue)
}
@Test
fun testDifficultyGradeNumericValueCalculation() {
val vbGrade = DifficultyGrade(DifficultySystem.V_SCALE, "VB")
assertEquals(0, vbGrade.numericValue)
val v5Grade = DifficultyGrade(DifficultySystem.V_SCALE, "V5")
assertEquals(5, v5Grade.numericValue)
val ydsGrade = DifficultyGrade(DifficultySystem.YDS, "5.9")
assertTrue(ydsGrade.numericValue > 0)
}
@Test
fun testDifficultyGradeComparison() {
val v3 = DifficultyGrade(DifficultySystem.V_SCALE, "V3")
val v5 = DifficultyGrade(DifficultySystem.V_SCALE, "V5")
val vb = DifficultyGrade(DifficultySystem.V_SCALE, "VB")
assertTrue(v3.compareTo(v5) < 0) // V3 is easier than V5
assertTrue(v5.compareTo(v3) > 0) // V5 is harder than V3
assertTrue(vb.compareTo(v3) < 0) // VB is easier than V3
assertEquals(0, v3.compareTo(v3)) // Same grade
}
@Test
fun testAttemptResultEnumValues() {
val expectedResults = setOf("SUCCESS", "FALL", "NO_PROGRESS", "FLASH")
val actualResults = AttemptResult.entries.map { it.name }.toSet()
assertEquals(expectedResults, actualResults)
}
@Test
fun testSessionStatusEnumValues() {
val expectedStatuses = setOf("ACTIVE", "COMPLETED", "PAUSED")
val actualStatuses = SessionStatus.entries.map { it.name }.toSet()
assertEquals(expectedStatuses, actualStatuses)
}
@Test
fun testBackupGymCreationAndValidation() {
val gym =
BackupGym(
id = "gym123",
name = "Test Climbing Gym",
location = "Test City",
supportedClimbTypes = listOf(ClimbType.BOULDER, ClimbType.ROPE),
difficultySystems = listOf(DifficultySystem.V_SCALE, DifficultySystem.YDS),
customDifficultyGrades = emptyList(),
notes = "Great gym for beginners",
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
assertEquals("gym123", gym.id)
assertEquals("Test Climbing Gym", gym.name)
assertEquals("Test City", gym.location)
assertEquals(2, gym.supportedClimbTypes.size)
assertTrue(gym.supportedClimbTypes.contains(ClimbType.BOULDER))
assertTrue(gym.supportedClimbTypes.contains(ClimbType.ROPE))
assertEquals(2, gym.difficultySystems.size)
assertTrue(gym.difficultySystems.contains(DifficultySystem.V_SCALE))
assertTrue(gym.difficultySystems.contains(DifficultySystem.YDS))
}
@Test
fun testBackupProblemCreationAndValidation() {
val problem =
BackupProblem(
id = "problem123",
gymId = "gym123",
name = "Test Problem",
description = "A challenging boulder problem",
climbType = ClimbType.BOULDER,
difficulty = DifficultyGrade(DifficultySystem.V_SCALE, "V5"),
tags = listOf("overhang", "crimpy"),
location = "Wall A",
imagePaths = listOf("image1.jpg", "image2.jpg"),
isActive = true,
dateSet = "2024-01-01",
notes = "Watch the start holds",
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
assertEquals("problem123", problem.id)
assertEquals("gym123", problem.gymId)
assertEquals("Test Problem", problem.name)
assertEquals(ClimbType.BOULDER, problem.climbType)
assertEquals("V5", problem.difficulty.grade)
assertTrue(problem.isActive)
assertEquals(2, problem.tags.size)
assertEquals(2, problem.imagePaths?.size ?: 0)
}
@Test
fun testBackupClimbSessionCreationAndValidation() {
val session =
BackupClimbSession(
id = "session123",
gymId = "gym123",
date = "2024-01-01",
startTime = "2024-01-01T10:00:00Z",
endTime = "2024-01-01T12:00:00Z",
duration = 7200,
status = SessionStatus.COMPLETED,
notes = "Great session today",
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T12:00:00Z"
)
assertEquals("session123", session.id)
assertEquals("gym123", session.gymId)
assertEquals("2024-01-01", session.date)
assertEquals(SessionStatus.COMPLETED, session.status)
assertEquals(7200L, session.duration)
}
@Test
fun testBackupAttemptCreationAndValidation() {
val attempt =
BackupAttempt(
id = "attempt123",
sessionId = "session123",
problemId = "problem123",
result = AttemptResult.SUCCESS,
highestHold = "Top",
notes = "Stuck it on second try",
duration = 300,
restTime = 120,
timestamp = "2024-01-01T10:30:00Z",
createdAt = "2024-01-01T10:30:00Z"
)
assertEquals("attempt123", attempt.id)
assertEquals("session123", attempt.sessionId)
assertEquals("problem123", attempt.problemId)
assertEquals(AttemptResult.SUCCESS, attempt.result)
assertEquals("Top", attempt.highestHold)
assertEquals(300L, attempt.duration)
assertEquals(120L, attempt.restTime)
}
@Test
fun testClimbDataBackupCreationAndValidation() {
val backup =
ClimbDataBackup(
exportedAt = "2024-01-01T10:00:00Z",
version = "2.0",
formatVersion = "2.0",
gyms = emptyList(),
problems = emptyList(),
sessions = emptyList(),
attempts = emptyList()
)
assertEquals("2.0", backup.version)
assertEquals("2.0", backup.formatVersion)
assertTrue(backup.gyms.isEmpty())
assertTrue(backup.problems.isEmpty())
assertTrue(backup.sessions.isEmpty())
assertTrue(backup.attempts.isEmpty())
}
@Test
fun testDateFormatValidation() {
val validDate = "2024-01-01T10:00:00Z"
val formatter = DateTimeFormatter.ISO_INSTANT
try {
val instant = Instant.from(formatter.parse(validDate))
assertNotNull(instant)
} catch (e: Exception) {
fail("Should not throw exception for valid date: $e")
}
}
@Test
fun testSessionDurationCalculation() {
val session =
BackupClimbSession(
id = "test",
gymId = "gym1",
date = "2024-01-01",
startTime = "2024-01-01T10:00:00Z",
endTime = "2024-01-01T12:00:00Z",
duration = 7200,
status = SessionStatus.COMPLETED,
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T12:00:00Z"
)
assertEquals(7200L, session.duration)
val hours = session.duration!! / 3600
assertEquals(2L, hours)
}
@Test
fun testEmptyCollectionsHandling() {
val gym =
BackupGym(
id = "gym1",
name = "Test Gym",
location = null,
supportedClimbTypes = emptyList(),
difficultySystems = emptyList(),
customDifficultyGrades = emptyList(),
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
assertTrue(gym.supportedClimbTypes.isEmpty())
assertTrue(gym.difficultySystems.isEmpty())
assertTrue(gym.customDifficultyGrades.isEmpty())
assertNull(gym.location)
assertNull(gym.notes)
}
@Test
fun testNullableFieldsHandling() {
val problem =
BackupProblem(
id = "problem1",
gymId = "gym1",
name = null,
description = null,
climbType = ClimbType.BOULDER,
difficulty = DifficultyGrade(DifficultySystem.V_SCALE, "V1"),
tags = emptyList(),
location = null,
imagePaths = null,
isActive = true,
dateSet = null,
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
assertNull(problem.name)
assertNull(problem.description)
assertNull(problem.location)
assertNull(problem.dateSet)
assertNull(problem.notes)
assertTrue(problem.tags.isEmpty())
assertNull(problem.imagePaths)
}
@Test
fun testUniqueIdGeneration() {
val id1 = java.util.UUID.randomUUID().toString()
val id2 = java.util.UUID.randomUUID().toString()
assertNotEquals(id1, id2)
assertEquals(36, id1.length)
assertTrue(id1.contains("-"))
}
@Test
fun testBackupDataFormatValidation() {
val testJson =
"""
{
"exportedAt": "2024-01-01T10:00:00Z",
"version": "2.0",
"formatVersion": "2.0",
"gyms": [],
"problems": [],
"sessions": [],
"attempts": []
}
""".trimIndent()
assertTrue(testJson.contains("exportedAt"))
assertTrue(testJson.contains("version"))
assertTrue(testJson.contains("gyms"))
assertTrue(testJson.contains("problems"))
assertTrue(testJson.contains("sessions"))
assertTrue(testJson.contains("attempts"))
}
@Test
fun testDateTimeFormatting() {
val currentTime = System.currentTimeMillis()
assertTrue(currentTime > 0)
val timeString = java.time.Instant.ofEpochMilli(currentTime).toString()
assertTrue(timeString.isNotEmpty())
assertTrue(timeString.contains("T"))
assertTrue(timeString.endsWith("Z"))
}
@Test
fun testClimbTypeAndDifficultySystemCompatibility() {
// Test that V_SCALE works with BOULDER
val boulderProblem =
BackupProblem(
id = "boulder1",
gymId = "gym1",
name = "Boulder Problem",
description = null,
climbType = ClimbType.BOULDER,
difficulty = DifficultyGrade(DifficultySystem.V_SCALE, "V3"),
tags = emptyList(),
location = null,
imagePaths = null,
isActive = true,
dateSet = null,
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
assertEquals(ClimbType.BOULDER, boulderProblem.climbType)
assertEquals(DifficultySystem.V_SCALE, boulderProblem.difficulty.system)
// Test that YDS works with ROPE
val ropeProblem =
BackupProblem(
id = "rope1",
gymId = "gym1",
name = "Rope Problem",
description = null,
climbType = ClimbType.ROPE,
difficulty = DifficultyGrade(DifficultySystem.YDS, "5.10a"),
tags = emptyList(),
location = null,
imagePaths = null,
isActive = true,
dateSet = null,
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
assertEquals(ClimbType.ROPE, ropeProblem.climbType)
assertEquals(DifficultySystem.YDS, ropeProblem.difficulty.system)
}
@Test
fun testStringOperations() {
val problemName = " Test Problem V5 "
val trimmedName = problemName.trim()
val uppercaseName = trimmedName.uppercase()
val lowercaseName = trimmedName.lowercase()
assertEquals("Test Problem V5", trimmedName)
assertEquals("TEST PROBLEM V5", uppercaseName)
assertEquals("test problem v5", lowercaseName)
val components = trimmedName.split(" ")
assertEquals(3, components.size)
assertEquals("V5", components.last())
}
@Test
fun testNumericOperations() {
val grades = listOf(3, 5, 7, 4, 6)
val sum = grades.sum()
val average = grades.average()
val maxGrade = grades.maxOrNull() ?: 0
val minGrade = grades.minOrNull() ?: 0
assertEquals(25, sum)
assertEquals(5.0, average, 0.01)
assertEquals(7, maxGrade)
assertEquals(3, minGrade)
}
@Test
fun testAttemptResultValidation() {
val validResults =
listOf(
AttemptResult.SUCCESS,
AttemptResult.FALL,
AttemptResult.NO_PROGRESS,
AttemptResult.FLASH
)
assertEquals(4, validResults.size)
assertTrue(validResults.contains(AttemptResult.SUCCESS))
assertTrue(validResults.contains(AttemptResult.FALL))
assertTrue(validResults.contains(AttemptResult.NO_PROGRESS))
assertTrue(validResults.contains(AttemptResult.FLASH))
}
@Test
fun testSessionStatusValidation() {
val validStatuses =
listOf(SessionStatus.ACTIVE, SessionStatus.COMPLETED, SessionStatus.PAUSED)
assertEquals(3, validStatuses.size)
assertTrue(validStatuses.contains(SessionStatus.ACTIVE))
assertTrue(validStatuses.contains(SessionStatus.COMPLETED))
assertTrue(validStatuses.contains(SessionStatus.PAUSED))
}
@Test
fun testClimbDataIntegrity() {
val gym =
BackupGym(
id = "gym1",
name = "Test Gym",
location = "Test City",
supportedClimbTypes = listOf(ClimbType.BOULDER),
difficultySystems = listOf(DifficultySystem.V_SCALE),
customDifficultyGrades = emptyList(),
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
val problem =
BackupProblem(
id = "problem1",
gymId = gym.id,
name = "Test Problem",
description = null,
climbType = ClimbType.BOULDER,
difficulty = DifficultyGrade(DifficultySystem.V_SCALE, "V3"),
tags = emptyList(),
location = null,
imagePaths = null,
isActive = true,
dateSet = null,
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T10:00:00Z"
)
val session =
BackupClimbSession(
id = "session1",
gymId = gym.id,
date = "2024-01-01",
startTime = "2024-01-01T10:00:00Z",
endTime = "2024-01-01T11:00:00Z",
duration = 3600,
status = SessionStatus.COMPLETED,
notes = null,
createdAt = "2024-01-01T10:00:00Z",
updatedAt = "2024-01-01T11:00:00Z"
)
val attempt =
BackupAttempt(
id = "attempt1",
sessionId = session.id,
problemId = problem.id,
result = AttemptResult.SUCCESS,
highestHold = null,
notes = null,
duration = 120,
restTime = null,
timestamp = "2024-01-01T10:30:00Z",
createdAt = "2024-01-01T10:30:00Z"
)
// Verify referential integrity
assertEquals(gym.id, problem.gymId)
assertEquals(gym.id, session.gymId)
assertEquals(session.id, attempt.sessionId)
assertEquals(problem.id, attempt.problemId)
// Verify climb type compatibility
assertTrue(gym.supportedClimbTypes.contains(problem.climbType))
assertTrue(gym.difficultySystems.contains(problem.difficulty.system))
}
}

View File

@@ -1,17 +0,0 @@
package com.atridad.openclimb
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

View File

@@ -0,0 +1,451 @@
package com.atridad.openclimb
import com.atridad.openclimb.data.format.*
import com.atridad.openclimb.data.model.*
import org.junit.Assert.*
import org.junit.Test
class SyncMergeLogicTest {
@Test
fun `test intelligent merge preserves all data`() {
// Create local data
val localGyms =
listOf(
BackupGym(
id = "gym1",
name = "Local Gym 1",
location = "Local Location",
supportedClimbTypes = listOf(ClimbType.BOULDER),
difficultySystems = listOf(DifficultySystem.V_SCALE),
customDifficultyGrades = emptyList(),
notes = null,
createdAt = "2024-01-01T10:00:00",
updatedAt = "2024-01-01T10:00:00"
)
)
val localProblems =
listOf(
BackupProblem(
id = "problem1",
gymId = "gym1",
name = "Local Problem",
description = "Local description",
climbType = ClimbType.BOULDER,
difficulty = DifficultyGrade(DifficultySystem.V_SCALE, "V5"),
tags = listOf("local"),
location = null,
imagePaths = listOf("local_image.jpg"),
isActive = true,
dateSet = null,
notes = null,
createdAt = "2024-01-01T10:00:00",
updatedAt = "2024-01-01T10:00:00"
)
)
val localSessions =
listOf(
BackupClimbSession(
id = "session1",
gymId = "gym1",
date = "2024-01-01",
startTime = "2024-01-01T10:00:00",
endTime = "2024-01-01T12:00:00",
duration = 7200,
status = SessionStatus.COMPLETED,
notes = null,
createdAt = "2024-01-01T10:00:00",
updatedAt = "2024-01-01T10:00:00"
)
)
val localAttempts =
listOf(
BackupAttempt(
id = "attempt1",
sessionId = "session1",
problemId = "problem1",
result = AttemptResult.SUCCESS,
highestHold = null,
notes = null,
duration = 300,
restTime = null,
timestamp = "2024-01-01T10:30:00",
createdAt = "2024-01-01T10:30:00"
)
)
val localBackup =
ClimbDataBackup(
exportedAt = "2024-01-01T10:00:00",
version = "2.0",
formatVersion = "2.0",
gyms = localGyms,
problems = localProblems,
sessions = localSessions,
attempts = localAttempts
)
// Create server data with some overlapping and some unique data
val serverGyms =
listOf(
// Same gym but with newer update
BackupGym(
id = "gym1",
name = "Updated Gym 1",
location = "Updated Location",
supportedClimbTypes = listOf(ClimbType.BOULDER, ClimbType.ROPE),
difficultySystems =
listOf(DifficultySystem.V_SCALE, DifficultySystem.YDS),
customDifficultyGrades = emptyList(),
notes = "Updated notes",
createdAt = "2024-01-01T10:00:00",
updatedAt = "2024-01-01T12:00:00" // Newer update
),
// Unique server gym
BackupGym(
id = "gym2",
name = "Server Gym 2",
location = "Server Location",
supportedClimbTypes = listOf(ClimbType.ROPE),
difficultySystems = listOf(DifficultySystem.YDS),
customDifficultyGrades = emptyList(),
notes = null,
createdAt = "2024-01-01T11:00:00",
updatedAt = "2024-01-01T11:00:00"
)
)
val serverProblems =
listOf(
// Same problem but with newer update and different images
BackupProblem(
id = "problem1",
gymId = "gym1",
name = "Updated Problem",
description = "Updated description",
climbType = ClimbType.BOULDER,
difficulty = DifficultyGrade(DifficultySystem.V_SCALE, "V5"),
tags = listOf("updated", "server"),
location = "Updated location",
imagePaths = listOf("server_image.jpg"),
isActive = true,
dateSet = "2024-01-01",
notes = "Updated notes",
createdAt = "2024-01-01T10:00:00",
updatedAt = "2024-01-01T11:00:00" // Newer update
),
// Unique server problem
BackupProblem(
id = "problem2",
gymId = "gym2",
name = "Server Problem",
description = "Server description",
climbType = ClimbType.ROPE,
difficulty = DifficultyGrade(DifficultySystem.YDS, "5.10a"),
tags = listOf("server"),
location = null,
imagePaths = null,
isActive = true,
dateSet = null,
notes = null,
createdAt = "2024-01-01T11:00:00",
updatedAt = "2024-01-01T11:00:00"
)
)
val serverSessions =
listOf(
// Unique server session
BackupClimbSession(
id = "session2",
gymId = "gym2",
date = "2024-01-02",
startTime = "2024-01-02T14:00:00",
endTime = "2024-01-02T16:00:00",
duration = 7200,
status = SessionStatus.COMPLETED,
notes = "Server session",
createdAt = "2024-01-02T14:00:00",
updatedAt = "2024-01-02T14:00:00"
)
)
val serverAttempts =
listOf(
// Unique server attempt
BackupAttempt(
id = "attempt2",
sessionId = "session2",
problemId = "problem2",
result = AttemptResult.FALL,
highestHold = "Last move",
notes = "Almost had it",
duration = 180,
restTime = 60,
timestamp = "2024-01-02T14:30:00",
createdAt = "2024-01-02T14:30:00"
)
)
val serverBackup =
ClimbDataBackup(
exportedAt = "2024-01-01T12:00:00",
version = "2.0",
formatVersion = "2.0",
gyms = serverGyms,
problems = serverProblems,
sessions = serverSessions,
attempts = serverAttempts
)
// Simulate merge logic
val mergedBackup = performIntelligentMerge(localBackup, serverBackup)
// Verify merge results
assertEquals("Should have 2 gyms (1 updated, 1 new)", 2, mergedBackup.gyms.size)
assertEquals("Should have 2 problems (1 updated, 1 new)", 2, mergedBackup.problems.size)
assertEquals("Should have 2 sessions (1 local, 1 server)", 2, mergedBackup.sessions.size)
assertEquals("Should have 2 attempts (1 local, 1 server)", 2, mergedBackup.attempts.size)
// Verify gym merge - server version should win (newer update)
val mergedGym1 = mergedBackup.gyms.find { it.id == "gym1" }!!
assertEquals("Updated Gym 1", mergedGym1.name)
assertEquals("Updated Location", mergedGym1.location)
assertEquals("Updated notes", mergedGym1.notes)
assertEquals("2024-01-01T12:00:00", mergedGym1.updatedAt)
// Verify unique server gym is preserved
val mergedGym2 = mergedBackup.gyms.find { it.id == "gym2" }!!
assertEquals("Server Gym 2", mergedGym2.name)
// Verify problem merge - server version should win but images should be merged
val mergedProblem1 = mergedBackup.problems.find { it.id == "problem1" }!!
assertEquals("Updated Problem", mergedProblem1.name)
assertEquals("Updated description", mergedProblem1.description)
assertEquals("2024-01-01T11:00:00", mergedProblem1.updatedAt)
// Images should be merged (both local and server images preserved)
assertTrue(
"Should contain local image",
mergedProblem1.imagePaths!!.contains("local_image.jpg")
)
assertTrue(
"Should contain server image",
mergedProblem1.imagePaths!!.contains("server_image.jpg")
)
assertEquals("Should have 2 images total", 2, mergedProblem1.imagePaths!!.size)
// Verify unique server problem is preserved
val mergedProblem2 = mergedBackup.problems.find { it.id == "problem2" }!!
assertEquals("Server Problem", mergedProblem2.name)
// Verify all sessions are preserved
assertTrue(
"Should contain local session",
mergedBackup.sessions.any { it.id == "session1" }
)
assertTrue(
"Should contain server session",
mergedBackup.sessions.any { it.id == "session2" }
)
// Verify all attempts are preserved
assertTrue(
"Should contain local attempt",
mergedBackup.attempts.any { it.id == "attempt1" }
)
assertTrue(
"Should contain server attempt",
mergedBackup.attempts.any { it.id == "attempt2" }
)
}
@Test
fun `test date comparison logic`() {
assertTrue(
"ISO instant should be newer",
isNewerThan("2024-01-01T12:00:00Z", "2024-01-01T10:00:00Z")
)
assertFalse(
"ISO instant should be older",
isNewerThan("2024-01-01T10:00:00Z", "2024-01-01T12:00:00Z")
)
assertTrue(
"String comparison should work as fallback",
isNewerThan("2024-01-02T10:00:00", "2024-01-01T10:00:00")
)
}
@Test
fun `test empty data scenarios`() {
val emptyBackup =
ClimbDataBackup(
exportedAt = "2024-01-01T10:00:00",
version = "2.0",
formatVersion = "2.0",
gyms = emptyList(),
problems = emptyList(),
sessions = emptyList(),
attempts = emptyList()
)
val dataBackup =
ClimbDataBackup(
exportedAt = "2024-01-01T10:00:00",
version = "2.0",
formatVersion = "2.0",
gyms =
listOf(
BackupGym(
id = "gym1",
name = "Test Gym",
location = null,
supportedClimbTypes = listOf(ClimbType.BOULDER),
difficultySystems =
listOf(DifficultySystem.V_SCALE),
customDifficultyGrades = emptyList(),
notes = null,
createdAt = "2024-01-01T10:00:00",
updatedAt = "2024-01-01T10:00:00"
)
),
problems = emptyList(),
sessions = emptyList(),
attempts = emptyList()
)
// Test merging empty with data
val merged1 = performIntelligentMerge(emptyBackup, dataBackup)
assertEquals("Should preserve data from non-empty backup", 1, merged1.gyms.size)
// Test merging data with empty
val merged2 = performIntelligentMerge(dataBackup, emptyBackup)
assertEquals("Should preserve data from non-empty backup", 1, merged2.gyms.size)
// Test merging empty with empty
val merged3 = performIntelligentMerge(emptyBackup, emptyBackup)
assertEquals("Should remain empty", 0, merged3.gyms.size)
}
// Helper methods that simulate the merge logic from SyncService
private fun performIntelligentMerge(
local: ClimbDataBackup,
server: ClimbDataBackup
): ClimbDataBackup {
val mergedGyms = mergeGyms(local.gyms, server.gyms)
val mergedProblems = mergeProblems(local.problems, server.problems)
val mergedSessions = mergeSessions(local.sessions, server.sessions)
val mergedAttempts = mergeAttempts(local.attempts, server.attempts)
return ClimbDataBackup(
exportedAt = "2024-01-01T12:00:00",
version = "2.0",
formatVersion = "2.0",
gyms = mergedGyms,
problems = mergedProblems,
sessions = mergedSessions,
attempts = mergedAttempts
)
}
private fun mergeGyms(local: List<BackupGym>, server: List<BackupGym>): List<BackupGym> {
val merged = mutableMapOf<String, BackupGym>()
// Add all local gyms
local.forEach { gym -> merged[gym.id] = gym }
// Add server gyms, preferring newer updates
server.forEach { serverGym ->
val localGym = merged[serverGym.id]
if (localGym == null || isNewerThan(serverGym.updatedAt, localGym.updatedAt)) {
merged[serverGym.id] = serverGym
}
}
return merged.values.toList()
}
private fun mergeProblems(
local: List<BackupProblem>,
server: List<BackupProblem>
): List<BackupProblem> {
val merged = mutableMapOf<String, BackupProblem>()
// Add all local problems
local.forEach { problem -> merged[problem.id] = problem }
// Add server problems, preferring newer updates
server.forEach { serverProblem ->
val localProblem = merged[serverProblem.id]
if (localProblem == null || isNewerThan(serverProblem.updatedAt, localProblem.updatedAt)
) {
// Merge image paths to preserve all images
val allImagePaths = mutableSetOf<String>()
localProblem?.imagePaths?.let { allImagePaths.addAll(it) }
serverProblem.imagePaths?.let { allImagePaths.addAll(it) }
merged[serverProblem.id] =
serverProblem.withUpdatedImagePaths(allImagePaths.toList())
}
}
return merged.values.toList()
}
private fun mergeSessions(
local: List<BackupClimbSession>,
server: List<BackupClimbSession>
): List<BackupClimbSession> {
val merged = mutableMapOf<String, BackupClimbSession>()
// Add all local sessions
local.forEach { session -> merged[session.id] = session }
// Add server sessions, preferring newer updates
server.forEach { serverSession ->
val localSession = merged[serverSession.id]
if (localSession == null || isNewerThan(serverSession.updatedAt, localSession.updatedAt)
) {
merged[serverSession.id] = serverSession
}
}
return merged.values.toList()
}
private fun mergeAttempts(
local: List<BackupAttempt>,
server: List<BackupAttempt>
): List<BackupAttempt> {
val merged = mutableMapOf<String, BackupAttempt>()
// Add all local attempts
local.forEach { attempt -> merged[attempt.id] = attempt }
// Add server attempts, preferring newer updates
server.forEach { serverAttempt ->
val localAttempt = merged[serverAttempt.id]
if (localAttempt == null || isNewerThan(serverAttempt.createdAt, localAttempt.createdAt)
) {
merged[serverAttempt.id] = serverAttempt
}
}
return merged.values.toList()
}
private fun isNewerThan(dateString1: String, dateString2: String): Boolean {
return try {
// Try parsing as instant first
val date1 = java.time.Instant.parse(dateString1)
val date2 = java.time.Instant.parse(dateString2)
date1.isAfter(date2)
} catch (e: Exception) {
// Fallback to string comparison
dateString1 > dateString2
}
}
}

View File

@@ -0,0 +1,374 @@
package com.atridad.openclimb
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
import org.junit.Assert.*
import org.junit.Test
/**
* Comprehensive utility and service tests for OpenClimb Android app. Tests core utility functions,
* date handling, string operations, and business logic.
*/
class UtilityTests {
@Test
fun testDateTimeUtilities() {
val now = System.currentTimeMillis()
val dateTime = LocalDateTime.now()
assertTrue(now > 0)
assertNotNull(dateTime)
val formatted = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
assertFalse(formatted.isEmpty())
assertTrue(formatted.contains("T"))
}
@Test
fun testDurationCalculations() {
val startTime = 1000L
val endTime = 4000L
val duration = endTime - startTime
assertEquals(3000L, duration)
val minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
val seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
assertEquals(0L, minutes)
assertEquals(3L, seconds)
}
@Test
fun testStringValidation() {
val validName = "Test Gym"
val emptyName = ""
val whitespaceName = " "
val nullName: String? = null
assertTrue(isValidString(validName))
assertFalse(isValidString(emptyName))
assertFalse(isValidString(whitespaceName))
assertFalse(isValidString(nullName))
}
@Test
fun testGradeConversion() {
val vGrade = "V5"
val ydsGrade = "5.10a"
val fontGrade = "6A"
assertTrue(isValidVGrade(vGrade))
assertTrue(isValidYDSGrade(ydsGrade))
assertTrue(isValidFontGrade(fontGrade))
assertFalse(isValidVGrade("Invalid"))
assertFalse(isValidYDSGrade("Invalid"))
assertFalse(isValidFontGrade("Invalid"))
}
@Test
fun testNumericGradeExtraction() {
assertEquals(0, extractVGradeNumber("VB"))
assertEquals(5, extractVGradeNumber("V5"))
assertEquals(12, extractVGradeNumber("V12"))
assertEquals(-1, extractVGradeNumber("Invalid"))
}
@Test
fun testClimbingStatistics() {
val attempts =
listOf(
AttemptData("SUCCESS", 120),
AttemptData("FALL", 90),
AttemptData("SUCCESS", 150),
AttemptData("FLASH", 60),
AttemptData("FALL", 110)
)
val stats = calculateAttemptStatistics(attempts)
assertEquals(5, stats.totalAttempts)
assertEquals(3, stats.successfulAttempts)
assertEquals(60.0, stats.successRate, 0.01)
assertEquals(106.0, stats.averageDuration, 0.01)
}
@Test
fun testSessionDurationFormatting() {
assertEquals("0m", formatDuration(0))
assertEquals("1m", formatDuration(60))
assertEquals("1h 30m", formatDuration(5400))
assertEquals("2h", formatDuration(7200))
assertEquals("2h 5m", formatDuration(7500))
}
@Test
fun testDifficultyComparison() {
assertTrue(compareVGrades("V3", "V5") < 0)
assertTrue(compareVGrades("V5", "V3") > 0)
assertEquals(0, compareVGrades("V5", "V5"))
assertTrue(compareVGrades("VB", "V1") < 0)
assertTrue(compareVGrades("V1", "VB") > 0)
}
@Test
fun testClimbTypeValidation() {
val validTypes = listOf("BOULDER", "ROPE")
val invalidTypes = listOf("INVALID", "", "sport", "trad")
validTypes.forEach { type -> assertTrue("$type should be valid", isValidClimbType(type)) }
invalidTypes.forEach { type ->
assertFalse("$type should be invalid", isValidClimbType(type))
}
}
@Test
fun testImagePathValidation() {
val validPaths = listOf("image.jpg", "photo.jpeg", "picture.png", "diagram.webp")
val invalidPaths = listOf("", "file.txt", "document.pdf", "video.mp4")
validPaths.forEach { path ->
assertTrue("$path should be valid image", isValidImagePath(path))
}
invalidPaths.forEach { path ->
assertFalse("$path should be invalid image", isValidImagePath(path))
}
}
@Test
fun testLocationValidation() {
assertTrue(isValidLocation("Wall A"))
assertTrue(isValidLocation("Area 51"))
assertTrue(isValidLocation("Overhang Section"))
assertFalse(isValidLocation(""))
assertFalse(isValidLocation(" "))
assertFalse(isValidLocation(null))
}
@Test
fun testTagProcessing() {
val rawTags = "overhang, crimpy, technical,DYNAMIC "
val processedTags = processTags(rawTags)
assertEquals(4, processedTags.size)
assertTrue(processedTags.contains("overhang"))
assertTrue(processedTags.contains("crimpy"))
assertTrue(processedTags.contains("technical"))
assertTrue(processedTags.contains("dynamic"))
}
@Test
fun testSearchFiltering() {
val problems =
listOf(
ProblemData(
"id1",
"Crimpy Problem",
"BOULDER",
"V5",
listOf("crimpy", "overhang")
),
ProblemData("id2", "Easy Route", "ROPE", "5.6", listOf("beginner", "slab")),
ProblemData(
"id3",
"Hard Boulder",
"BOULDER",
"V10",
listOf("powerful", "roof")
)
)
val boulderProblems = filterByClimbType(problems, "BOULDER")
assertEquals(2, boulderProblems.size)
val crimpyProblems = filterByTag(problems, "crimpy")
assertEquals(1, crimpyProblems.size)
val easyProblems = filterByDifficultyRange(problems, "VB", "V6")
assertEquals(2, easyProblems.size)
}
@Test
fun testDataSynchronization() {
val localData = mapOf("key1" to "local_value", "key2" to "shared_value")
val serverData = mapOf("key2" to "server_value", "key3" to "new_value")
val merged = mergeData(localData, serverData)
assertEquals(3, merged.size)
assertEquals("local_value", merged["key1"])
assertEquals("server_value", merged["key2"]) // Server wins
assertEquals("new_value", merged["key3"])
}
@Test
fun testBackupValidation() {
val validBackup =
BackupData(
version = "2.0",
formatVersion = "2.0",
exportedAt = "2024-01-01T10:00:00Z",
dataCount = 5
)
val invalidBackup =
BackupData(
version = "1.0",
formatVersion = "2.0",
exportedAt = "invalid-date",
dataCount = -1
)
assertTrue(isValidBackup(validBackup))
assertFalse(isValidBackup(invalidBackup))
}
// Helper functions and data classes
private fun isValidString(str: String?): Boolean {
return str != null && str.trim().isNotEmpty()
}
private fun isValidVGrade(grade: String): Boolean {
return grade.matches(Regex("^V(B|[0-9]|1[0-7])$"))
}
private fun isValidYDSGrade(grade: String): Boolean {
return grade.matches(Regex("^5\\.[0-9]+([abcd])?$"))
}
private fun isValidFontGrade(grade: String): Boolean {
return grade.matches(Regex("^[3-8][ABC]?\\+?$"))
}
private fun extractVGradeNumber(grade: String): Int {
return when {
grade == "VB" -> 0
grade.startsWith("V") -> grade.substring(1).toIntOrNull() ?: -1
else -> -1
}
}
private fun calculateAttemptStatistics(attempts: List<AttemptData>): AttemptStatistics {
val successful = attempts.count { it.result == "SUCCESS" || it.result == "FLASH" }
val avgDuration = attempts.map { it.duration }.average()
val successRate = (successful.toDouble() / attempts.size) * 100
return AttemptStatistics(
totalAttempts = attempts.size,
successfulAttempts = successful,
successRate = successRate,
averageDuration = avgDuration
)
}
private fun formatDuration(seconds: Long): String {
val hours = seconds / 3600
val minutes = (seconds % 3600) / 60
return when {
hours > 0 && minutes > 0 -> "${hours}h ${minutes}m"
hours > 0 -> "${hours}h"
minutes > 0 -> "${minutes}m"
else -> "0m"
}
}
private fun compareVGrades(grade1: String, grade2: String): Int {
val num1 = extractVGradeNumber(grade1)
val num2 = extractVGradeNumber(grade2)
return num1.compareTo(num2)
}
private fun isValidClimbType(type: String): Boolean {
return type in listOf("BOULDER", "ROPE")
}
private fun isValidImagePath(path: String): Boolean {
val validExtensions = listOf(".jpg", ".jpeg", ".png", ".webp")
return path.isNotEmpty() && validExtensions.any { path.endsWith(it, ignoreCase = true) }
}
private fun isValidLocation(location: String?): Boolean {
return isValidString(location)
}
private fun processTags(rawTags: String): List<String> {
return rawTags.split(",").map { it.trim().lowercase() }.filter { it.isNotEmpty() }
}
private fun filterByClimbType(
problems: List<ProblemData>,
climbType: String
): List<ProblemData> {
return problems.filter { it.climbType == climbType }
}
private fun filterByTag(problems: List<ProblemData>, tag: String): List<ProblemData> {
return problems.filter { it.tags.contains(tag) }
}
private fun filterByDifficultyRange(
problems: List<ProblemData>,
minGrade: String,
maxGrade: String
): List<ProblemData> {
return problems.filter { problem ->
if (problem.climbType == "BOULDER" && problem.difficulty.startsWith("V")) {
val gradeNum = extractVGradeNumber(problem.difficulty)
val minNum = extractVGradeNumber(minGrade)
val maxNum = extractVGradeNumber(maxGrade)
gradeNum in minNum..maxNum
} else {
true // Simplified for other grade systems
}
}
}
private fun mergeData(
local: Map<String, String>,
server: Map<String, String>
): Map<String, String> {
return (local.keys + server.keys).associateWith { key -> server[key] ?: local[key]!! }
}
private fun isValidBackup(backup: BackupData): Boolean {
return backup.version == "2.0" &&
backup.formatVersion == "2.0" &&
backup.exportedAt.matches(Regex("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z")) &&
backup.dataCount >= 0
}
// Data classes for testing
data class AttemptData(val result: String, val duration: Int)
data class AttemptStatistics(
val totalAttempts: Int,
val successfulAttempts: Int,
val successRate: Double,
val averageDuration: Double
)
data class ProblemData(
val id: String,
val name: String,
val climbType: String,
val difficulty: String,
val tags: List<String>
)
data class BackupData(
val version: String,
val formatVersion: String,
val exportedAt: String,
val dataCount: Int
)
}

View File

@@ -19,6 +19,7 @@ kotlinxSerialization = "1.9.0"
kotlinxCoroutines = "1.10.2"
coil = "2.7.0"
ksp = "2.2.10-2.0.2"
okhttp = "5.1.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
@@ -60,13 +61,11 @@ kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" }
# Testing
mockk = { group = "io.mockk", name = "mockk", version = "1.14.5" }
mockk = { group = "io.mockk", name = "mockk", version = "1.14.6" }
# Image Loading
coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coil" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }

Binary file not shown.

View File

@@ -1,6 +1,7 @@
#Fri Aug 15 11:23:25 MDT 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

295
android/gradlew vendored
View File

@@ -1,7 +1,7 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright 2015 the original author or authors.
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,81 +15,114 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -98,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

40
android/gradlew.bat vendored
View File

@@ -13,8 +13,10 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -25,7 +27,8 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -56,32 +59,33 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View File

@@ -1,383 +0,0 @@
package com.atridad.openclimb.data.repository
import android.content.Context
import com.atridad.openclimb.data.database.OpenClimbDatabase
import com.atridad.openclimb.data.format.ClimbDataBackup
import com.atridad.openclimb.data.model.*
import com.atridad.openclimb.utils.ZipExportImportUtils
import java.io.File
import java.time.LocalDateTime
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.serialization.json.Json
class ClimbRepository(database: OpenClimbDatabase, private val context: Context) {
private val gymDao = database.gymDao()
private val problemDao = database.problemDao()
private val sessionDao = database.climbSessionDao()
private val attemptDao = database.attemptDao()
private val json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
// Gym operations
fun getAllGyms(): Flow<List<Gym>> = gymDao.getAllGyms()
suspend fun getGymById(id: String): Gym? = gymDao.getGymById(id)
suspend fun insertGym(gym: Gym) = gymDao.insertGym(gym)
suspend fun updateGym(gym: Gym) = gymDao.updateGym(gym)
suspend fun deleteGym(gym: Gym) = gymDao.deleteGym(gym)
fun searchGyms(query: String): Flow<List<Gym>> = gymDao.searchGyms(query)
// Problem operations
fun getAllProblems(): Flow<List<Problem>> = problemDao.getAllProblems()
suspend fun getProblemById(id: String): Problem? = problemDao.getProblemById(id)
fun getProblemsByGym(gymId: String): Flow<List<Problem>> = problemDao.getProblemsByGym(gymId)
suspend fun insertProblem(problem: Problem) = problemDao.insertProblem(problem)
suspend fun updateProblem(problem: Problem) = problemDao.updateProblem(problem)
suspend fun deleteProblem(problem: Problem) = problemDao.deleteProblem(problem)
fun searchProblems(query: String): Flow<List<Problem>> = problemDao.searchProblems(query)
// Session operations
fun getAllSessions(): Flow<List<ClimbSession>> = sessionDao.getAllSessions()
suspend fun getSessionById(id: String): ClimbSession? = sessionDao.getSessionById(id)
fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>> =
sessionDao.getSessionsByGym(gymId)
suspend fun getActiveSession(): ClimbSession? = sessionDao.getActiveSession()
fun getActiveSessionFlow(): Flow<ClimbSession?> = sessionDao.getActiveSessionFlow()
suspend fun insertSession(session: ClimbSession) = sessionDao.insertSession(session)
suspend fun updateSession(session: ClimbSession) = sessionDao.updateSession(session)
suspend fun deleteSession(session: ClimbSession) = sessionDao.deleteSession(session)
suspend fun getLastUsedGym(): Gym? {
val recentSessions = sessionDao.getRecentSessions(1).first()
return if (recentSessions.isNotEmpty()) {
getGymById(recentSessions.first().gymId)
} else {
null
}
}
// Attempt operations
fun getAllAttempts(): Flow<List<Attempt>> = attemptDao.getAllAttempts()
fun getAttemptsBySession(sessionId: String): Flow<List<Attempt>> =
attemptDao.getAttemptsBySession(sessionId)
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>> =
attemptDao.getAttemptsByProblem(problemId)
suspend fun insertAttempt(attempt: Attempt) = attemptDao.insertAttempt(attempt)
suspend fun updateAttempt(attempt: Attempt) = attemptDao.updateAttempt(attempt)
suspend fun deleteAttempt(attempt: Attempt) = attemptDao.deleteAttempt(attempt)
// ZIP Export with images - Single format for reliability
suspend fun exportAllDataToZip(directory: File? = null): File {
return try {
// Collect all data with proper error handling
val allGyms = gymDao.getAllGyms().first()
val allProblems = problemDao.getAllProblems().first()
val allSessions = sessionDao.getAllSessions().first()
val allAttempts = attemptDao.getAllAttempts().first()
// Validate data integrity before export
validateDataIntegrity(allGyms, allProblems, allSessions, allAttempts)
// Create backup data using platform-neutral format
val backupData =
ClimbDataBackup(
exportedAt = LocalDateTime.now().toString(),
version = "2.0",
formatVersion = "2.0",
gyms =
allGyms.map {
com.atridad.openclimb.data.format.BackupGym.fromGym(it)
},
problems =
allProblems.map {
com.atridad.openclimb.data.format.BackupProblem.fromProblem(
it
)
},
sessions =
allSessions.map {
com.atridad.openclimb.data.format.BackupClimbSession
.fromClimbSession(it)
},
attempts =
allAttempts.map {
com.atridad.openclimb.data.format.BackupAttempt.fromAttempt(
it
)
}
)
// Collect all referenced image paths and validate they exist
val referencedImagePaths = allProblems.flatMap { it.imagePaths }.toSet()
val validImagePaths =
referencedImagePaths
.filter { imagePath ->
try {
val imageFile =
com.atridad.openclimb.utils.ImageUtils.getImageFile(
context,
imagePath
)
imageFile.exists() && imageFile.length() > 0
} catch (e: Exception) {
false
}
}
.toSet()
// Log any missing images for debugging
val missingImages = referencedImagePaths - validImagePaths
if (missingImages.isNotEmpty()) {
android.util.Log.w(
"ClimbRepository",
"Some referenced images are missing: $missingImages"
)
}
ZipExportImportUtils.createExportZip(
context = context,
exportData = backupData,
referencedImagePaths = validImagePaths,
directory = directory
)
} catch (e: Exception) {
throw Exception("Export failed: ${e.message}")
}
}
suspend fun exportAllDataToZipUri(uri: android.net.Uri) {
try {
// Collect all data
val allGyms = gymDao.getAllGyms().first()
val allProblems = problemDao.getAllProblems().first()
val allSessions = sessionDao.getAllSessions().first()
val allAttempts = attemptDao.getAllAttempts().first()
// Validate data integrity before export
validateDataIntegrity(allGyms, allProblems, allSessions, allAttempts)
// Create backup data using platform-neutral format
val backupData =
ClimbDataBackup(
exportedAt = LocalDateTime.now().toString(),
version = "2.0",
formatVersion = "2.0",
gyms =
allGyms.map {
com.atridad.openclimb.data.format.BackupGym.fromGym(it)
},
problems =
allProblems.map {
com.atridad.openclimb.data.format.BackupProblem.fromProblem(
it
)
},
sessions =
allSessions.map {
com.atridad.openclimb.data.format.BackupClimbSession
.fromClimbSession(it)
},
attempts =
allAttempts.map {
com.atridad.openclimb.data.format.BackupAttempt.fromAttempt(
it
)
}
)
// Collect all referenced image paths and validate they exist
val referencedImagePaths = allProblems.flatMap { it.imagePaths }.toSet()
val validImagePaths =
referencedImagePaths
.filter { imagePath ->
try {
val imageFile =
com.atridad.openclimb.utils.ImageUtils.getImageFile(
context,
imagePath
)
imageFile.exists() && imageFile.length() > 0
} catch (e: Exception) {
false
}
}
.toSet()
ZipExportImportUtils.createExportZipToUri(
context = context,
uri = uri,
exportData = backupData,
referencedImagePaths = validImagePaths
)
} catch (e: Exception) {
throw Exception("Export failed: ${e.message}")
}
}
suspend fun importDataFromZip(file: File) {
try {
// Validate the ZIP file
if (!file.exists() || file.length() == 0L) {
throw Exception("Invalid ZIP file: file is empty or doesn't exist")
}
// Extract and validate the ZIP contents
val importResult = ZipExportImportUtils.extractImportZip(context, file)
// Validate JSON content
if (importResult.jsonContent.isBlank()) {
throw Exception("Invalid ZIP file: no data.json found or empty content")
}
// Parse and validate the data structure
val importData =
try {
json.decodeFromString<ClimbDataBackup>(importResult.jsonContent)
} catch (e: Exception) {
throw Exception("Invalid data format: ${e.message}")
}
// Validate data integrity
validateImportData(importData)
// Clear existing data to avoid conflicts
attemptDao.deleteAllAttempts()
sessionDao.deleteAllSessions()
problemDao.deleteAllProblems()
gymDao.deleteAllGyms()
// Import gyms first (problems depend on gyms)
importData.gyms.forEach { backupGym ->
try {
gymDao.insertGym(backupGym.toGym())
} catch (e: Exception) {
throw Exception("Failed to import gym '${backupGym.name}': ${e.message}")
}
}
// Import problems with updated image paths
val updatedBackupProblems =
ZipExportImportUtils.updateProblemImagePaths(
importData.problems,
importResult.importedImagePaths
)
// Import problems (depends on gyms)
updatedBackupProblems.forEach { backupProblem ->
try {
problemDao.insertProblem(backupProblem.toProblem())
} catch (e: Exception) {
throw Exception(
"Failed to import problem '${backupProblem.name}': ${e.message}"
)
}
}
// Import sessions
importData.sessions.forEach { backupSession ->
try {
sessionDao.insertSession(backupSession.toClimbSession())
} catch (e: Exception) {
throw Exception("Failed to import session '${backupSession.id}': ${e.message}")
}
}
// Import attempts last (depends on problems and sessions)
importData.attempts.forEach { backupAttempt ->
try {
attemptDao.insertAttempt(backupAttempt.toAttempt())
} catch (e: Exception) {
throw Exception("Failed to import attempt '${backupAttempt.id}': ${e.message}")
}
}
} catch (e: Exception) {
throw Exception("Import failed: ${e.message}")
}
}
private fun validateDataIntegrity(
gyms: List<Gym>,
problems: List<Problem>,
sessions: List<ClimbSession>,
attempts: List<Attempt>
) {
// Validate that all problems reference valid gyms
val gymIds = gyms.map { it.id }.toSet()
val invalidProblems = problems.filter { it.gymId !in gymIds }
if (invalidProblems.isNotEmpty()) {
throw Exception(
"Data integrity error: ${invalidProblems.size} problems reference non-existent gyms"
)
}
// Validate that all sessions reference valid gyms
val invalidSessions = sessions.filter { it.gymId !in gymIds }
if (invalidSessions.isNotEmpty()) {
throw Exception(
"Data integrity error: ${invalidSessions.size} sessions reference non-existent gyms"
)
}
// Validate that all attempts reference valid problems and sessions
val problemIds = problems.map { it.id }.toSet()
val sessionIds = sessions.map { it.id }.toSet()
val invalidAttempts =
attempts.filter { it.problemId !in problemIds || it.sessionId !in sessionIds }
if (invalidAttempts.isNotEmpty()) {
throw Exception(
"Data integrity error: ${invalidAttempts.size} attempts reference non-existent problems or sessions"
)
}
}
private fun validateImportData(importData: ClimbDataBackup) {
if (importData.gyms.isEmpty()) {
throw Exception("Import data is invalid: no gyms found")
}
if (importData.version.isBlank()) {
throw Exception("Import data is invalid: no version information")
}
// Check for reasonable data sizes to prevent malicious imports
if (importData.gyms.size > 1000 ||
importData.problems.size > 10000 ||
importData.sessions.size > 10000 ||
importData.attempts.size > 100000
) {
throw Exception("Import data is too large: possible corruption or malicious file")
}
}
suspend fun resetAllData() {
try {
// Clear all data from database
attemptDao.deleteAllAttempts()
sessionDao.deleteAllSessions()
problemDao.deleteAllProblems()
gymDao.deleteAllGyms()
// Clear all images from storage
clearAllImages()
} catch (e: Exception) {
throw Exception("Reset failed: ${e.message}")
}
}
private fun clearAllImages() {
try {
// Get the images directory
val imagesDir = File(context.filesDir, "images")
if (imagesDir.exists() && imagesDir.isDirectory) {
val deletedCount = imagesDir.listFiles()?.size ?: 0
imagesDir.deleteRecursively()
android.util.Log.i("ClimbRepository", "Cleared $deletedCount image files")
}
} catch (e: Exception) {
android.util.Log.w("ClimbRepository", "Failed to clear some images: ${e.message}")
}
}
}

View File

@@ -20,7 +20,7 @@ struct ClimbingActivityWidget: Widget {
DynamicIsland {
// Expanded UI goes here
DynamicIslandExpandedRegion(.leading) {
Text("🧗‍♂️")
Text("CLIMB")
.font(.title2)
}
DynamicIslandExpandedRegion(.trailing) {
@@ -39,12 +39,12 @@ struct ClimbingActivityWidget: Widget {
.font(.caption)
}
} compactLeading: {
Text("🧗‍♂️")
Text("CLIMB")
} compactTrailing: {
Text("\(context.state.totalAttempts)")
.monospacedDigit()
} minimal: {
Text("🧗‍♂️")
Text("CLIMB")
}
}
}
@@ -56,7 +56,7 @@ struct LiveActivityView: View {
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("🧗‍♂️ \(context.attributes.gymName)")
Text("CLIMBING: \(context.attributes.gymName)")
.font(.headline)
.lineLimit(1)
Spacer()

View File

@@ -15,6 +15,13 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D2F32FB12E90B26500B1BC56 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D24C19602E75002A0045894C /* Project object */;
proxyType = 1;
remoteGlobalIDString = D24C19672E75002A0045894C;
remoteInfo = OpenClimb;
};
D2FE949E2E78FEE1008CDB25 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D24C19602E75002A0045894C /* Project object */;
@@ -41,6 +48,7 @@
/* Begin PBXFileReference section */
D24C19682E75002A0045894C /* OpenClimb.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = OpenClimb.app; sourceTree = BUILT_PRODUCTS_DIR; };
D268B79E2E83894A003AA641 /* SessionStatusLiveExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = SessionStatusLiveExtension.entitlements; sourceTree = "<group>"; };
D2F32FAD2E90B26500B1BC56 /* OpenClimbTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = OpenClimbTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
D2FE94802E78E958008CDB25 /* ActivityKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ActivityKit.framework; path = System/Library/Frameworks/ActivityKit.framework; sourceTree = SDKROOT; };
D2FE948B2E78FEE0008CDB25 /* SessionStatusLiveExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = SessionStatusLiveExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
D2FE948C2E78FEE0008CDB25 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };
@@ -73,6 +81,11 @@
path = OpenClimb;
sourceTree = "<group>";
};
D2F32FAE2E90B26500B1BC56 /* OpenClimbTests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = OpenClimbTests;
sourceTree = "<group>";
};
D2FE94902E78FEE0008CDB25 /* SessionStatusLive */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
@@ -92,6 +105,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F32FAA2E90B26500B1BC56 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2FE94882E78FEE0008CDB25 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -111,6 +131,7 @@
D268B79E2E83894A003AA641 /* SessionStatusLiveExtension.entitlements */,
D24C196A2E75002A0045894C /* OpenClimb */,
D2FE94902E78FEE0008CDB25 /* SessionStatusLive */,
D2F32FAE2E90B26500B1BC56 /* OpenClimbTests */,
D2FE947F2E78E958008CDB25 /* Frameworks */,
D24C19692E75002A0045894C /* Products */,
);
@@ -121,6 +142,7 @@
children = (
D24C19682E75002A0045894C /* OpenClimb.app */,
D2FE948B2E78FEE0008CDB25 /* SessionStatusLiveExtension.appex */,
D2F32FAD2E90B26500B1BC56 /* OpenClimbTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -162,6 +184,29 @@
productReference = D24C19682E75002A0045894C /* OpenClimb.app */;
productType = "com.apple.product-type.application";
};
D2F32FAC2E90B26500B1BC56 /* OpenClimbTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D2F32FB52E90B26500B1BC56 /* Build configuration list for PBXNativeTarget "OpenClimbTests" */;
buildPhases = (
D2F32FA92E90B26500B1BC56 /* Sources */,
D2F32FAA2E90B26500B1BC56 /* Frameworks */,
D2F32FAB2E90B26500B1BC56 /* Resources */,
);
buildRules = (
);
dependencies = (
D2F32FB22E90B26500B1BC56 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
D2F32FAE2E90B26500B1BC56 /* OpenClimbTests */,
);
name = OpenClimbTests;
packageProductDependencies = (
);
productName = OpenClimbTests;
productReference = D2F32FAD2E90B26500B1BC56 /* OpenClimbTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
D2FE948A2E78FEE0008CDB25 /* SessionStatusLiveExtension */ = {
isa = PBXNativeTarget;
buildConfigurationList = D2FE94A12E78FEE1008CDB25 /* Build configuration list for PBXNativeTarget "SessionStatusLiveExtension" */;
@@ -197,6 +242,10 @@
D24C19672E75002A0045894C = {
CreatedOnToolsVersion = 26.0;
};
D2F32FAC2E90B26500B1BC56 = {
CreatedOnToolsVersion = 26.0.1;
TestTargetID = D24C19672E75002A0045894C;
};
D2FE948A2E78FEE0008CDB25 = {
CreatedOnToolsVersion = 26.0;
};
@@ -218,6 +267,7 @@
targets = (
D24C19672E75002A0045894C /* OpenClimb */,
D2FE948A2E78FEE0008CDB25 /* SessionStatusLiveExtension */,
D2F32FAC2E90B26500B1BC56 /* OpenClimbTests */,
);
};
/* End PBXProject section */
@@ -230,6 +280,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F32FAB2E90B26500B1BC56 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2FE94892E78FEE0008CDB25 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@@ -247,6 +304,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F32FA92E90B26500B1BC56 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2FE94872E78FEE0008CDB25 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -257,6 +321,11 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D2F32FB22E90B26500B1BC56 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D24C19672E75002A0045894C /* OpenClimb */;
targetProxy = D2F32FB12E90B26500B1BC56 /* PBXContainerItemProxy */;
};
D2FE949F2E78FEE1008CDB25 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D2FE948A2E78FEE0008CDB25 /* SessionStatusLiveExtension */;
@@ -324,6 +393,7 @@
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
@@ -381,6 +451,7 @@
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
VALIDATE_PRODUCT = YES;
};
@@ -394,7 +465,7 @@
CODE_SIGN_ENTITLEMENTS = OpenClimb/OpenClimb.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 10;
CURRENT_PROJECT_VERSION = 13;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
@@ -414,7 +485,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.1.0;
MARKETING_VERSION = 1.2.2;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -437,7 +508,7 @@
CODE_SIGN_ENTITLEMENTS = OpenClimb/OpenClimb.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 10;
CURRENT_PROJECT_VERSION = 13;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
@@ -457,7 +528,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.1.0;
MARKETING_VERSION = 1.2.2;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -472,6 +543,48 @@
};
name = Release;
};
D2F32FB32E90B26500B1BC56 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atri.dad.OpenClimb.Watch.OpenClimbTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/OpenClimb.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/OpenClimb";
};
name = Debug;
};
D2F32FB42E90B26500B1BC56 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atri.dad.OpenClimb.Watch.OpenClimbTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/OpenClimb.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/OpenClimb";
};
name = Release;
};
D2FE94A22E78FEE1008CDB25 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -479,7 +592,7 @@
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 10;
CURRENT_PROJECT_VERSION = 13;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = SessionStatusLive/Info.plist;
@@ -490,7 +603,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.1.0;
MARKETING_VERSION = 1.2.2;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb.SessionStatusLive;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
@@ -509,7 +622,7 @@
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 10;
CURRENT_PROJECT_VERSION = 13;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = SessionStatusLive/Info.plist;
@@ -520,7 +633,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.1.0;
MARKETING_VERSION = 1.2.2;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb.SessionStatusLive;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
@@ -553,6 +666,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D2F32FB52E90B26500B1BC56 /* Build configuration list for PBXNativeTarget "OpenClimbTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D2F32FB32E90B26500B1BC56 /* Debug */,
D2F32FB42E90B26500B1BC56 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D2FE94A12E78FEE1008CDB25 /* Build configuration list for PBXNativeTarget "SessionStatusLiveExtension" */ = {
isa = XCConfigurationList;
buildConfigurations = (

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D24C19672E75002A0045894C"
BuildableName = "OpenClimb.app"
BlueprintName = "OpenClimb"
ReferencedContainer = "container:OpenClimb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D2F32FAC2E90B26500B1BC56"
BuildableName = "OpenClimbTests.xctest"
BlueprintName = "OpenClimbTests"
ReferencedContainer = "container:OpenClimb.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D24C19672E75002A0045894C"
BuildableName = "OpenClimb.app"
BlueprintName = "OpenClimb"
ReferencedContainer = "container:OpenClimb.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D24C19672E75002A0045894C"
BuildableName = "OpenClimb.app"
BlueprintName = "OpenClimb"
ReferencedContainer = "container:OpenClimb.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -44,6 +44,19 @@
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D2F32FAC2E90B26500B1BC56"
BuildableName = "OpenClimbTests.xctest"
BlueprintName = "OpenClimbTests"
ReferencedContainer = "container:OpenClimb.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"

View File

@@ -57,6 +57,8 @@ struct ContentView: View {
}
.onAppear {
setupNotificationObservers()
// Trigger auto-sync on app launch
dataManager.syncService.triggerAutoSync(dataManager: dataManager)
}
.onDisappear {
removeNotificationObservers()
@@ -83,7 +85,7 @@ struct ContentView: View {
object: nil,
queue: .main
) { _ in
print("📱 App will enter foreground - preparing Live Activity check")
print("App will enter foreground - preparing Live Activity check")
Task {
// Small delay to ensure app is fully active
try? await Task.sleep(nanoseconds: 800_000_000) // 0.8 seconds
@@ -97,10 +99,12 @@ struct ContentView: View {
object: nil,
queue: .main
) { _ in
print("📱 App did become active - checking Live Activity status")
print("App did become active - checking Live Activity status")
Task {
try? await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds
await dataManager.onAppBecomeActive()
// Trigger auto-sync when app becomes active
await dataManager.syncService.triggerAutoSync(dataManager: dataManager)
}
}

View File

@@ -1,17 +1,9 @@
//
// BackupFormat.swift
// OpenClimb
//
// Created by OpenClimb Team on 2024-12-19.
// Copyright © 2024 OpenClimb. All rights reserved.
//
import Foundation
// MARK: - Backup Format Specification v2.0
// Platform-neutral backup format for cross-platform compatibility
// This format ensures portability between iOS and Android while maintaining
// platform-specific implementations
/// Root structure for OpenClimb backup data
struct ClimbDataBackup: Codable {
@@ -42,7 +34,7 @@ struct ClimbDataBackup: Codable {
}
}
/// Platform-neutral gym representation for backup/restore
// Platform-neutral gym representation for backup/restore
struct BackupGym: Codable {
let id: String
let name: String
@@ -51,8 +43,8 @@ struct BackupGym: Codable {
let difficultySystems: [DifficultySystem]
let customDifficultyGrades: [String]
let notes: String?
let createdAt: String // ISO 8601 format
let updatedAt: String // ISO 8601 format
let createdAt: String
let updatedAt: String
/// Initialize from native iOS Gym model
init(from gym: Gym) {
@@ -119,7 +111,7 @@ struct BackupGym: Codable {
}
}
/// Platform-neutral problem representation for backup/restore
// Platform-neutral problem representation for backup/restore
struct BackupProblem: Codable {
let id: String
let gymId: String
@@ -133,8 +125,8 @@ struct BackupProblem: Codable {
let isActive: Bool
let dateSet: String? // ISO 8601 format
let notes: String?
let createdAt: String // ISO 8601 format
let updatedAt: String // ISO 8601 format
let createdAt: String
let updatedAt: String
/// Initialize from native iOS Problem model
init(from problem: Problem) {
@@ -244,7 +236,7 @@ struct BackupProblem: Codable {
}
}
/// Platform-neutral climb session representation for backup/restore
// Platform-neutral climb session representation for backup/restore
struct BackupClimbSession: Codable {
let id: String
let gymId: String
@@ -254,8 +246,8 @@ struct BackupClimbSession: Codable {
let duration: Int64? // Duration in seconds
let status: SessionStatus
let notes: String?
let createdAt: String // ISO 8601 format
let updatedAt: String // ISO 8601 format
let createdAt: String
let updatedAt: String
/// Initialize from native iOS ClimbSession model
init(from session: ClimbSession) {
@@ -332,7 +324,7 @@ struct BackupClimbSession: Codable {
}
}
/// Platform-neutral attempt representation for backup/restore
// Platform-neutral attempt representation for backup/restore
struct BackupAttempt: Codable {
let id: String
let sessionId: String
@@ -342,8 +334,8 @@ struct BackupAttempt: Codable {
let notes: String?
let duration: Int64? // Duration in seconds
let restTime: Int64? // Rest time in seconds
let timestamp: String // ISO 8601 format
let createdAt: String // ISO 8601 format
let timestamp: String
let createdAt: String
/// Initialize from native iOS Attempt model
init(from attempt: Attempt) {

View File

@@ -0,0 +1,824 @@
import Combine
import Foundation
@MainActor
class SyncService: ObservableObject {
@Published var isSyncing = false
@Published var lastSyncTime: Date?
@Published var syncError: String?
@Published var isConnected = false
@Published var isTesting = false
private let userDefaults = UserDefaults.standard
private enum Keys {
static let serverURL = "sync_server_url"
static let authToken = "sync_auth_token"
static let lastSyncTime = "last_sync_time"
static let isConnected = "sync_is_connected"
static let autoSyncEnabled = "auto_sync_enabled"
}
var serverURL: String {
get { userDefaults.string(forKey: Keys.serverURL) ?? "" }
set { userDefaults.set(newValue, forKey: Keys.serverURL) }
}
var authToken: String {
get { userDefaults.string(forKey: Keys.authToken) ?? "" }
set { userDefaults.set(newValue, forKey: Keys.authToken) }
}
var isConfigured: Bool {
return !serverURL.isEmpty && !authToken.isEmpty
}
var isAutoSyncEnabled: Bool {
get { userDefaults.bool(forKey: Keys.autoSyncEnabled) }
set { userDefaults.set(newValue, forKey: Keys.autoSyncEnabled) }
}
init() {
if let lastSync = userDefaults.object(forKey: Keys.lastSyncTime) as? Date {
self.lastSyncTime = lastSync
}
self.isConnected = userDefaults.bool(forKey: Keys.isConnected)
}
func downloadData() async throws -> ClimbDataBackup {
guard isConfigured else {
throw SyncError.notConfigured
}
guard let url = URL(string: "\(serverURL)/sync") else {
throw SyncError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw SyncError.invalidResponse
}
switch httpResponse.statusCode {
case 200:
break
case 401:
throw SyncError.unauthorized
default:
throw SyncError.serverError(httpResponse.statusCode)
}
do {
let backup = try JSONDecoder().decode(ClimbDataBackup.self, from: data)
return backup
} catch {
throw SyncError.decodingError(error)
}
}
func uploadData(_ backup: ClimbDataBackup) async throws -> ClimbDataBackup {
guard isConfigured else {
throw SyncError.notConfigured
}
guard let url = URL(string: "\(serverURL)/sync") else {
throw SyncError.invalidURL
}
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let jsonData = try encoder.encode(backup)
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw SyncError.invalidResponse
}
switch httpResponse.statusCode {
case 200:
break
case 401:
throw SyncError.unauthorized
case 400:
throw SyncError.badRequest
default:
throw SyncError.serverError(httpResponse.statusCode)
}
do {
let responseBackup = try JSONDecoder().decode(ClimbDataBackup.self, from: data)
return responseBackup
} catch {
throw SyncError.decodingError(error)
}
}
func uploadImage(filename: String, imageData: Data) async throws {
guard isConfigured else {
throw SyncError.notConfigured
}
guard let url = URL(string: "\(serverURL)/images/upload?filename=\(filename)") else {
throw SyncError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.httpBody = imageData
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw SyncError.invalidResponse
}
switch httpResponse.statusCode {
case 200:
break
case 401:
throw SyncError.unauthorized
default:
throw SyncError.serverError(httpResponse.statusCode)
}
}
func downloadImage(filename: String) async throws -> Data {
guard isConfigured else {
throw SyncError.notConfigured
}
guard let url = URL(string: "\(serverURL)/images/download?filename=\(filename)") else {
throw SyncError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw SyncError.invalidResponse
}
switch httpResponse.statusCode {
case 200:
return data
case 401:
throw SyncError.unauthorized
case 404:
throw SyncError.imageNotFound
default:
throw SyncError.serverError(httpResponse.statusCode)
}
}
func syncWithServer(dataManager: ClimbingDataManager) async throws {
guard isConfigured else {
throw SyncError.notConfigured
}
guard isConnected else {
throw SyncError.notConnected
}
isSyncing = true
syncError = nil
defer {
isSyncing = false
}
do {
// Get local backup data
let localBackup = createBackupFromDataManager(dataManager)
// Download server data
let serverBackup = try await downloadData()
// Check if we have any local data
let hasLocalData =
!dataManager.gyms.isEmpty || !dataManager.problems.isEmpty
|| !dataManager.sessions.isEmpty || !dataManager.attempts.isEmpty
let hasServerData =
!serverBackup.gyms.isEmpty || !serverBackup.problems.isEmpty
|| !serverBackup.sessions.isEmpty || !serverBackup.attempts.isEmpty
if !hasLocalData && hasServerData {
// Case 1: No local data - do full restore from server
print("iOS SYNC: Case 1 - No local data, performing full restore from server")
print("Syncing images from server first...")
let imagePathMapping = try await syncImagesFromServer(
backup: serverBackup, dataManager: dataManager)
print("Importing data after images...")
try importBackupToDataManager(
serverBackup, dataManager: dataManager, imagePathMapping: imagePathMapping)
print("Full restore completed")
} else if hasLocalData && !hasServerData {
// Case 2: No server data - upload local data to server
print("iOS SYNC: Case 2 - No server data, uploading local data to server")
let currentBackup = createBackupFromDataManager(dataManager)
_ = try await uploadData(currentBackup)
print("Uploading local images to server...")
try await syncImagesToServer(dataManager: dataManager)
print("Initial upload completed")
} else if hasLocalData && hasServerData {
// Case 3: Both have data - compare timestamps (last writer wins)
let localTimestamp = parseISO8601ToMillis(timestamp: localBackup.exportedAt)
let serverTimestamp = parseISO8601ToMillis(timestamp: serverBackup.exportedAt)
print("DEBUG iOS Timestamp Comparison:")
print(" Local exportedAt: '\(localBackup.exportedAt)' -> \(localTimestamp)")
print(" Server exportedAt: '\(serverBackup.exportedAt)' -> \(serverTimestamp)")
print(
" DataStateManager last modified: '\(DataStateManager.shared.getLastModified())'"
)
print(" Comparison result: local=\(localTimestamp), server=\(serverTimestamp)")
if localTimestamp > serverTimestamp {
// Local is newer - replace server with local data
print("iOS SYNC: Case 3a - Local data is newer, replacing server content")
let currentBackup = createBackupFromDataManager(dataManager)
_ = try await uploadData(currentBackup)
try await syncImagesToServer(dataManager: dataManager)
print("Server replaced with local data")
} else if serverTimestamp > localTimestamp {
// Server is newer - replace local with server data
print("iOS SYNC: Case 3b - Server data is newer, replacing local content")
let imagePathMapping = try await syncImagesFromServer(
backup: serverBackup, dataManager: dataManager)
try importBackupToDataManager(
serverBackup, dataManager: dataManager, imagePathMapping: imagePathMapping)
print("Local data replaced with server data")
} else {
// Timestamps are equal - no sync needed
print(
"iOS SYNC: Case 3c - Data is in sync (timestamps equal), no action needed"
)
}
} else {
print("No data to sync")
}
// Update last sync time
lastSyncTime = Date()
userDefaults.set(lastSyncTime, forKey: Keys.lastSyncTime)
} catch {
syncError = error.localizedDescription
throw error
}
}
/// Parses ISO8601 timestamp to milliseconds for comparison
private func parseISO8601ToMillis(timestamp: String) -> Int64 {
let formatter = ISO8601DateFormatter()
if let date = formatter.date(from: timestamp) {
return Int64(date.timeIntervalSince1970 * 1000)
}
print("Failed to parse timestamp: \(timestamp), using 0")
return 0
}
private func syncImagesFromServer(backup: ClimbDataBackup, dataManager: ClimbingDataManager)
async throws -> [String: String]
{
var imagePathMapping: [String: String] = [:]
// Process images by problem to maintain consistent naming
for problem in backup.problems {
guard let imagePaths = problem.imagePaths, !imagePaths.isEmpty else { continue }
for (index, imagePath) in imagePaths.enumerated() {
let serverFilename = URL(fileURLWithPath: imagePath).lastPathComponent
do {
let imageData = try await downloadImage(filename: serverFilename)
// Generate consistent filename if needed
let consistentFilename =
ImageNamingUtils.isValidImageFilename(serverFilename)
? serverFilename
: ImageNamingUtils.generateImageFilename(
problemId: problem.id, imageIndex: index)
// Save image with consistent filename
let imageManager = ImageManager.shared
_ = try imageManager.saveImportedImage(
imageData, filename: consistentFilename)
// Map server filename to consistent local filename
imagePathMapping[serverFilename] = consistentFilename
print("Downloaded and mapped image: \(serverFilename) -> \(consistentFilename)")
} catch SyncError.imageNotFound {
print("Image not found on server: \(serverFilename)")
continue
} catch {
print("Failed to download image \(serverFilename): \(error)")
continue
}
}
}
return imagePathMapping
}
private func syncImagesToServer(dataManager: ClimbingDataManager) async throws {
// Process images by problem to ensure consistent naming
for problem in dataManager.problems {
guard !problem.imagePaths.isEmpty else { continue }
for (index, imagePath) in problem.imagePaths.enumerated() {
let filename = URL(fileURLWithPath: imagePath).lastPathComponent
// Ensure filename follows consistent naming convention
let consistentFilename =
ImageNamingUtils.isValidImageFilename(filename)
? filename
: ImageNamingUtils.generateImageFilename(
problemId: problem.id.uuidString, imageIndex: index)
// Load image data
let imageManager = ImageManager.shared
let fullPath = imageManager.imagesDirectory.appendingPathComponent(filename).path
if let imageData = imageManager.loadImageData(fromPath: fullPath) {
do {
// If filename changed, rename local file
if filename != consistentFilename {
let newPath = imageManager.imagesDirectory.appendingPathComponent(
consistentFilename
).path
do {
try FileManager.default.moveItem(atPath: fullPath, toPath: newPath)
print("Renamed local image: \(filename) -> \(consistentFilename)")
// Update problem's image path in memory for consistency
// Note: This would require updating the problem in the data manager
} catch {
print("Failed to rename local image, using original: \(error)")
}
}
try await uploadImage(filename: consistentFilename, imageData: imageData)
print("Successfully uploaded image: \(consistentFilename)")
} catch {
print("Failed to upload image \(consistentFilename): \(error)")
// Continue with other images even if one fails
}
}
}
}
}
private func createBackupFromDataManager(_ dataManager: ClimbingDataManager) -> ClimbDataBackup
{
return ClimbDataBackup(
exportedAt: DataStateManager.shared.getLastModified(),
gyms: dataManager.gyms.map { BackupGym(from: $0) },
problems: dataManager.problems.map { BackupProblem(from: $0) },
sessions: dataManager.sessions.map { BackupClimbSession(from: $0) },
attempts: dataManager.attempts.map { BackupAttempt(from: $0) }
)
}
private func importBackupToDataManager(
_ backup: ClimbDataBackup, dataManager: ClimbingDataManager,
imagePathMapping: [String: String] = [:]
) throws {
do {
// Update problem image paths to point to downloaded images
let updatedBackup: ClimbDataBackup
if !imagePathMapping.isEmpty {
let updatedProblems = backup.problems.map { problem in
let updatedImagePaths = problem.imagePaths?.compactMap { oldPath in
imagePathMapping[oldPath] ?? oldPath
}
return BackupProblem(
id: problem.id,
gymId: problem.gymId,
name: problem.name,
description: problem.description,
climbType: problem.climbType,
difficulty: problem.difficulty,
tags: problem.tags,
location: problem.location,
imagePaths: updatedImagePaths,
isActive: problem.isActive,
dateSet: problem.dateSet,
notes: problem.notes,
createdAt: problem.createdAt,
updatedAt: problem.updatedAt
)
}
updatedBackup = ClimbDataBackup(
exportedAt: backup.exportedAt,
version: backup.version,
formatVersion: backup.formatVersion,
gyms: backup.gyms,
problems: updatedProblems,
sessions: backup.sessions,
attempts: backup.attempts
)
} else {
updatedBackup = backup
}
// Create a minimal ZIP with just the JSON data for existing import mechanism
let zipData = try createMinimalZipFromBackup(updatedBackup)
// Use existing import method which properly handles data restoration
try dataManager.importData(from: zipData, showSuccessMessage: false)
// Update local data state to match imported data timestamp
DataStateManager.shared.setLastModified(backup.exportedAt)
print("Data state synchronized to imported timestamp: \(backup.exportedAt)")
} catch {
throw SyncError.importFailed(error)
}
}
private func createMinimalZipFromBackup(_ backup: ClimbDataBackup) throws -> Data {
// Create JSON data
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
encoder.dateEncodingStrategy = .custom { date, encoder in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
var container = encoder.singleValueContainer()
try container.encode(formatter.string(from: date))
}
let jsonData = try encoder.encode(backup)
// Collect all downloaded images from ImageManager
let imageManager = ImageManager.shared
var imageFiles: [(filename: String, data: Data)] = []
let imagePaths = Set(backup.problems.flatMap { $0.imagePaths ?? [] })
for imagePath in imagePaths {
let filename = URL(fileURLWithPath: imagePath).lastPathComponent
let fullPath = imageManager.imagesDirectory.appendingPathComponent(filename).path
if let imageData = imageManager.loadImageData(fromPath: fullPath) {
imageFiles.append((filename: filename, data: imageData))
}
}
// Create ZIP with data.json, metadata, and images
var zipData = Data()
var fileEntries: [(name: String, data: Data, offset: UInt32)] = []
var currentOffset: UInt32 = 0
// Add data.json to ZIP
try addFileToMinimalZip(
filename: "data.json",
fileData: jsonData,
zipData: &zipData,
fileEntries: &fileEntries,
currentOffset: &currentOffset
)
// Add metadata with correct image count
let metadata = "export_version=2.0\nformat_version=2.0\nimage_count=\(imageFiles.count)"
let metadataData = metadata.data(using: .utf8) ?? Data()
try addFileToMinimalZip(
filename: "metadata.txt",
fileData: metadataData,
zipData: &zipData,
fileEntries: &fileEntries,
currentOffset: &currentOffset
)
// Add images to ZIP in images/ directory
for imageFile in imageFiles {
try addFileToMinimalZip(
filename: "images/\(imageFile.filename)",
fileData: imageFile.data,
zipData: &zipData,
fileEntries: &fileEntries,
currentOffset: &currentOffset
)
}
// Add central directory
var centralDirectory = Data()
for entry in fileEntries {
centralDirectory.append(createCentralDirectoryHeader(entry: entry))
}
// Add end of central directory record
let endOfCentralDir = createEndOfCentralDirectoryRecord(
fileCount: UInt16(fileEntries.count),
centralDirSize: UInt32(centralDirectory.count),
centralDirOffset: currentOffset
)
zipData.append(centralDirectory)
zipData.append(endOfCentralDir)
return zipData
}
private func addFileToMinimalZip(
filename: String,
fileData: Data,
zipData: inout Data,
fileEntries: inout [(name: String, data: Data, offset: UInt32)],
currentOffset: inout UInt32
) throws {
let localFileHeader = createLocalFileHeader(
filename: filename, fileSize: UInt32(fileData.count))
fileEntries.append((name: filename, data: fileData, offset: currentOffset))
zipData.append(localFileHeader)
zipData.append(fileData)
currentOffset += UInt32(localFileHeader.count + fileData.count)
}
private func createLocalFileHeader(filename: String, fileSize: UInt32) -> Data {
var header = Data()
// Local file header signature
header.append(Data([0x50, 0x4b, 0x03, 0x04]))
// Version needed to extract (2.0)
header.append(Data([0x14, 0x00]))
// General purpose bit flag
header.append(Data([0x00, 0x00]))
// Compression method (no compression)
header.append(Data([0x00, 0x00]))
// Last mod file time & date (dummy values)
header.append(Data([0x00, 0x00, 0x00, 0x00]))
// CRC-32 (dummy - we're not compressing)
header.append(Data([0x00, 0x00, 0x00, 0x00]))
// Compressed size
withUnsafeBytes(of: fileSize.littleEndian) { header.append(Data($0)) }
// Uncompressed size
withUnsafeBytes(of: fileSize.littleEndian) { header.append(Data($0)) }
// File name length
let filenameData = filename.data(using: .utf8) ?? Data()
let filenameLength = UInt16(filenameData.count)
withUnsafeBytes(of: filenameLength.littleEndian) { header.append(Data($0)) }
// Extra field length
header.append(Data([0x00, 0x00]))
// File name
header.append(filenameData)
return header
}
private func createCentralDirectoryHeader(entry: (name: String, data: Data, offset: UInt32))
-> Data
{
var header = Data()
// Central directory signature
header.append(Data([0x50, 0x4b, 0x01, 0x02]))
// Version made by
header.append(Data([0x14, 0x00]))
// Version needed to extract
header.append(Data([0x14, 0x00]))
// General purpose bit flag
header.append(Data([0x00, 0x00]))
// Compression method
header.append(Data([0x00, 0x00]))
// Last mod file time & date
header.append(Data([0x00, 0x00, 0x00, 0x00]))
// CRC-32
header.append(Data([0x00, 0x00, 0x00, 0x00]))
// Compressed size
let compressedSize = UInt32(entry.data.count)
withUnsafeBytes(of: compressedSize.littleEndian) { header.append(Data($0)) }
// Uncompressed size
withUnsafeBytes(of: compressedSize.littleEndian) { header.append(Data($0)) }
// File name length
let filenameData = entry.name.data(using: .utf8) ?? Data()
let filenameLength = UInt16(filenameData.count)
withUnsafeBytes(of: filenameLength.littleEndian) { header.append(Data($0)) }
// Extra field length
header.append(Data([0x00, 0x00]))
// File comment length
header.append(Data([0x00, 0x00]))
// Disk number start
header.append(Data([0x00, 0x00]))
// Internal file attributes
header.append(Data([0x00, 0x00]))
// External file attributes
header.append(Data([0x00, 0x00, 0x00, 0x00]))
// Relative offset of local header
withUnsafeBytes(of: entry.offset.littleEndian) { header.append(Data($0)) }
// File name
header.append(filenameData)
return header
}
private func createEndOfCentralDirectoryRecord(
fileCount: UInt16, centralDirSize: UInt32, centralDirOffset: UInt32
) -> Data {
var record = Data()
// End of central dir signature
record.append(Data([0x50, 0x4b, 0x05, 0x06]))
// Number of this disk
record.append(Data([0x00, 0x00]))
// Number of the disk with the start of the central directory
record.append(Data([0x00, 0x00]))
// Total number of entries in the central directory on this disk
withUnsafeBytes(of: fileCount.littleEndian) { record.append(Data($0)) }
// Total number of entries in the central directory
withUnsafeBytes(of: fileCount.littleEndian) { record.append(Data($0)) }
// Size of the central directory
withUnsafeBytes(of: centralDirSize.littleEndian) { record.append(Data($0)) }
// Offset of start of central directory
withUnsafeBytes(of: centralDirOffset.littleEndian) { record.append(Data($0)) }
// ZIP file comment length
record.append(Data([0x00, 0x00]))
return record
}
func testConnection() async throws {
guard isConfigured else {
throw SyncError.notConfigured
}
isTesting = true
defer { isTesting = false }
guard let url = URL(string: "\(serverURL)/health") else {
throw SyncError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.timeoutInterval = 10
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw SyncError.invalidResponse
}
guard httpResponse.statusCode == 200 else {
throw SyncError.serverError(httpResponse.statusCode)
}
// Connection successful, mark as connected
isConnected = true
userDefaults.set(true, forKey: Keys.isConnected)
}
func triggerAutoSync(dataManager: ClimbingDataManager) {
// Early exit if sync cannot proceed - don't set isSyncing
guard isConnected && isConfigured && isAutoSyncEnabled else {
// Ensure isSyncing is false when sync is not possible
if isSyncing {
isSyncing = false
}
return
}
// Prevent multiple simultaneous syncs
guard !isSyncing else {
return
}
Task {
do {
try await syncWithServer(dataManager: dataManager)
} catch {
await MainActor.run {
self.isSyncing = false
}
}
}
}
func disconnect() {
isConnected = false
lastSyncTime = nil
syncError = nil
userDefaults.set(false, forKey: Keys.isConnected)
userDefaults.removeObject(forKey: Keys.lastSyncTime)
}
func clearConfiguration() {
serverURL = ""
authToken = ""
lastSyncTime = nil
isConnected = false
isAutoSyncEnabled = true
userDefaults.removeObject(forKey: Keys.lastSyncTime)
userDefaults.removeObject(forKey: Keys.isConnected)
userDefaults.removeObject(forKey: Keys.autoSyncEnabled)
}
}
enum SyncError: LocalizedError {
case notConfigured
case notConnected
case invalidURL
case invalidResponse
case unauthorized
case badRequest
case serverError(Int)
case decodingError(Error)
case exportFailed
case importFailed(Error)
case imageNotFound
case imageUploadFailed
var errorDescription: String? {
switch self {
case .notConfigured:
return "Sync server not configured. Please set server URL and auth token."
case .notConnected:
return "Not connected to sync server. Please test connection first."
case .invalidURL:
return "Invalid server URL."
case .invalidResponse:
return "Invalid response from server."
case .unauthorized:
return "Authentication failed. Check your auth token."
case .badRequest:
return "Bad request. Check your data format."
case .serverError(let code):
return "Server error (code \(code))."
case .decodingError(let error):
return "Failed to decode response: \(error.localizedDescription)"
case .exportFailed:
return "Failed to export local data."
case .importFailed(let error):
return "Failed to import data: \(error.localizedDescription)"
case .imageNotFound:
return "Image not found on server."
case .imageUploadFailed:
return "Failed to upload image to server."
}
}
}

View File

@@ -0,0 +1,83 @@
//
// DataStateManager.swift
import Foundation
/// Manages the overall data state timestamp for sync purposes
class DataStateManager {
private let userDefaults = UserDefaults.standard
private enum Keys {
static let lastModified = "openclimb_data_last_modified"
static let initialized = "openclimb_data_state_initialized"
}
static let shared = DataStateManager()
private init() {
// Initialize with current timestamp if this is the first time
if !isInitialized() {
print("DataStateManager: First time initialization")
// Set initial timestamp to a very old date so server data will be considered newer
let epochTime = "1970-01-01T00:00:00.000Z"
userDefaults.set(epochTime, forKey: Keys.lastModified)
markAsInitialized()
print("DataStateManager initialized with epoch timestamp: \(epochTime)")
} else {
print("DataStateManager: Already initialized, current timestamp: \(getLastModified())")
}
}
/// Updates the data state timestamp to the current time. Call this whenever any data is modified
/// (create, update, delete).
func updateDataState() {
let now = ISO8601DateFormatter().string(from: Date())
userDefaults.set(now, forKey: Keys.lastModified)
print("iOS Data state updated to: \(now)")
}
/// Gets the current data state timestamp. This represents when any data was last modified
/// locally.
func getLastModified() -> String {
if let storedTimestamp = userDefaults.string(forKey: Keys.lastModified) {
print("iOS DataStateManager returning stored timestamp: \(storedTimestamp)")
return storedTimestamp
}
// If no timestamp is stored, return epoch time to indicate very old data
// This ensures server data will be considered newer than uninitialized local data
let epochTime = "1970-01-01T00:00:00.000Z"
print("WARNING: No data state timestamp found - returning epoch time: \(epochTime)")
return epochTime
}
/// Sets the data state timestamp to a specific value. Used when importing data from server to
/// sync the state.
func setLastModified(_ timestamp: String) {
userDefaults.set(timestamp, forKey: Keys.lastModified)
print("Data state set to: \(timestamp)")
}
/// Resets the data state (for testing or complete data wipe).
func reset() {
userDefaults.removeObject(forKey: Keys.lastModified)
userDefaults.removeObject(forKey: Keys.initialized)
print("Data state reset")
}
/// Checks if the data state has been initialized.
private func isInitialized() -> Bool {
return userDefaults.bool(forKey: Keys.initialized)
}
/// Marks the data state as initialized.
private func markAsInitialized() {
userDefaults.set(true, forKey: Keys.initialized)
}
/// Gets debug information about the current state.
func getDebugInfo() -> String {
return "DataState(lastModified=\(getLastModified()), initialized=\(isInitialized()))"
}
}

View File

@@ -1,4 +1,3 @@
import Combine
import SwiftUI
@@ -11,7 +10,7 @@ import SwiftUI
@State private var testResults: [String] = []
var body: some View {
NavigationView {
NavigationStack {
List {
StatusSection()
@@ -263,10 +262,10 @@ import SwiftUI
ForEach(testResults.indices, id: \.self) { index in
HStack {
Image(
systemName: testResults[index].contains("")
systemName: testResults[index].contains("PASS")
? "checkmark.circle.fill" : "exclamationmark.triangle.fill"
)
.foregroundColor(testResults[index].contains("") ? .green : .orange)
.foregroundColor(testResults[index].contains("PASS") ? .green : .orange)
Text(testResults[index])
.font(.caption)
@@ -286,24 +285,24 @@ import SwiftUI
// Test 1: Check iOS version compatibility
if iconHelper.supportsModernIconFeatures {
testResults.append(" iOS 17+ features supported")
testResults.append("PASS: iOS 17+ features supported")
} else {
testResults.append(
"⚠️ Running on iOS version that doesn't support modern icon features")
"WARNING: Running on iOS version that doesn't support modern icon features")
}
// Test 2: Check dark mode detection
let detectedDarkMode = iconHelper.isInDarkMode(for: colorScheme)
let systemDarkMode = colorScheme == .dark
if detectedDarkMode == systemDarkMode {
testResults.append(" Dark mode detection matches system setting")
testResults.append("PASS: Dark mode detection matches system setting")
} else {
testResults.append("⚠️ Dark mode detection mismatch")
testResults.append("WARNING: Dark mode detection mismatch")
}
// Test 3: Check recommended variant
let variant = iconHelper.getRecommendedIconVariant(for: colorScheme)
testResults.append(" Recommended icon variant: \(variant.description)")
testResults.append("PASS: Recommended icon variant: \(variant.description)")
// Test 4: Test asset availability
validateAssetConfiguration()
@@ -316,7 +315,7 @@ import SwiftUI
iconHelper.updateDarkModeStatus(for: colorScheme)
let variant = iconHelper.getRecommendedIconVariant(for: colorScheme)
testResults.append(
" Icon appearance test completed - Current variant: \(variant.description)")
"PASS: Icon appearance test completed - Current variant: \(variant.description)")
}
private func validateAssetConfiguration() {
@@ -327,20 +326,20 @@ import SwiftUI
]
for asset in expectedAssets {
testResults.append(" Asset '\(asset)' configuration found")
testResults.append("PASS: Asset '\(asset)' configuration found")
}
}
private func checkBundleResources() {
// Check bundle identifier
let bundleId = Bundle.main.bundleIdentifier ?? "Unknown"
testResults.append(" Bundle ID: \(bundleId)")
testResults.append("PASS: Bundle ID: \(bundleId)")
// Check app version
let version =
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unknown"
testResults.append(" App version: \(version) (\(build))")
testResults.append("PASS: App version: \(version) (\(build))")
}
}
@@ -364,7 +363,7 @@ import SwiftUI
@Environment(\.colorScheme) private var colorScheme
var body: some View {
NavigationView {
NavigationStack {
VStack(spacing: 30) {
Text("Icon Appearance Comparison")
.font(.title2)

View File

@@ -23,7 +23,7 @@ class ImageManager {
// Final integrity check
if !validateStorageIntegrity() {
print("🚨 CRITICAL: Storage integrity compromised - attempting emergency recovery")
print("CRITICAL: Storage integrity compromised - attempting emergency recovery")
emergencyImageRestore()
}
@@ -69,9 +69,9 @@ class ImageManager {
attributes: [
.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication
])
print("Created directory: \(directory.path)")
print("Created directory: \(directory.path)")
} catch {
print(" Failed to create directory \(directory.path): \(error)")
print("ERROR: Failed to create directory \(directory.path): \(error)")
}
}
}
@@ -88,9 +88,9 @@ class ImageManager {
var backupURL = backupDirectory
try imagesURL.setResourceValues(resourceValues)
try backupURL.setResourceValues(resourceValues)
print("Excluded image directories from iCloud backup")
print("Excluded image directories from iCloud backup")
} catch {
print("⚠️ Failed to exclude from iCloud backup: \(error)")
print("WARNING: Failed to exclude from iCloud backup: \(error)")
}
}
@@ -114,11 +114,11 @@ class ImageManager {
}
private func performRobustMigration() {
print("🔄 Starting robust image migration system...")
print("Starting robust image migration system...")
// Check for interrupted migration
if let incompleteState = loadMigrationState() {
print("🔧 Detected interrupted migration, resuming...")
print("Detected interrupted migration, resuming...")
resumeMigration(from: incompleteState)
} else {
// Start fresh migration
@@ -135,7 +135,7 @@ class ImageManager {
private func startNewMigration() {
// First check for images in previous Application Support directories
if let previousAppSupportImages = findPreviousAppSupportImages() {
print("📁 Found images in previous Application Support directory")
print("Found images in previous Application Support directory")
migratePreviousAppSupportImages(from: previousAppSupportImages)
return
}
@@ -145,7 +145,7 @@ class ImageManager {
let hasLegacyImportImages = fileManager.fileExists(atPath: legacyImportImagesDirectory.path)
guard hasLegacyImages || hasLegacyImportImages else {
print("No legacy images to migrate")
print("No legacy images to migrate")
return
}
@@ -160,7 +160,7 @@ class ImageManager {
let legacyFiles = try fileManager.contentsOfDirectory(
atPath: legacyImagesDirectory.path)
allLegacyFiles.append(contentsOf: legacyFiles)
print("📦 Found \(legacyFiles.count) images in OpenClimbImages")
print("Found \(legacyFiles.count) images in OpenClimbImages")
}
// Collect files from Documents/images directory
@@ -168,10 +168,10 @@ class ImageManager {
let importFiles = try fileManager.contentsOfDirectory(
atPath: legacyImportImagesDirectory.path)
allLegacyFiles.append(contentsOf: importFiles)
print("📦 Found \(importFiles.count) images in Documents/images")
print("Found \(importFiles.count) images in Documents/images")
}
print("📦 Total legacy images to migrate: \(allLegacyFiles.count)")
print("Total legacy images to migrate: \(allLegacyFiles.count)")
let initialState = MigrationState(
version: MigrationState.currentVersion,
@@ -186,24 +186,24 @@ class ImageManager {
performMigrationWithCheckpoints(files: allLegacyFiles, currentState: initialState)
} catch {
print(" Failed to start migration: \(error)")
print("ERROR: Failed to start migration: \(error)")
}
}
private func resumeMigration(from state: MigrationState) {
print("🔄 Resuming migration from checkpoint...")
print("📊 Progress: \(state.completedFiles.count)/\(state.totalFiles)")
print("Resuming migration from checkpoint...")
print("Progress: \(state.completedFiles.count)/\(state.totalFiles)")
do {
let legacyFiles = try fileManager.contentsOfDirectory(
atPath: legacyImagesDirectory.path)
let remainingFiles = legacyFiles.filter { !state.completedFiles.contains($0) }
print("📦 Resuming with \(remainingFiles.count) remaining files")
print("Resuming with \(remainingFiles.count) remaining files")
performMigrationWithCheckpoints(files: remainingFiles, currentState: state)
} catch {
print(" Failed to resume migration: \(error)")
print("ERROR: Failed to resume migration: \(error)")
// Fallback: start fresh
removeMigrationState()
startNewMigration()
@@ -270,11 +270,11 @@ class ImageManager {
completedFiles.append(fileName)
migratedCount += 1
print("Migrated: \(fileName) (\(migratedCount)/\(currentState.totalFiles))")
print("Migrated: \(fileName) (\(migratedCount)/\(currentState.totalFiles))")
} catch {
failedCount += 1
print(" Failed to migrate \(fileName): \(error)")
print("ERROR: Failed to migrate \(fileName): \(error)")
}
// Save checkpoint every 5 files or if interrupted
@@ -288,7 +288,7 @@ class ImageManager {
lastCheckpoint: Date()
)
saveMigrationState(checkpointState)
print("💾 Checkpoint saved: \(completedFiles.count)/\(currentState.totalFiles)")
print("Checkpoint saved: \(completedFiles.count)/\(currentState.totalFiles)")
}
}
}
@@ -304,7 +304,7 @@ class ImageManager {
)
saveMigrationState(finalState)
print("🏁 Migration complete: \(migratedCount) migrated, \(failedCount) failed")
print("Migration complete: \(migratedCount) migrated, \(failedCount) failed")
// Clean up legacy directory if no failures
if failedCount == 0 {
@@ -313,7 +313,7 @@ class ImageManager {
}
private func verifyMigrationIntegrity() {
print("🔍 Verifying migration integrity...")
print("Verifying migration integrity...")
var allLegacyFiles = Set<String>()
@@ -331,12 +331,12 @@ class ImageManager {
allLegacyFiles.formUnion(importFiles)
}
} catch {
print(" Failed to read legacy directories: \(error)")
print("ERROR: Failed to read legacy directories: \(error)")
return
}
guard !allLegacyFiles.isEmpty else {
print("No legacy directories to verify against")
print("No legacy directories to verify against")
return
}
@@ -347,10 +347,10 @@ class ImageManager {
let missingFiles = allLegacyFiles.subtracting(migratedFiles)
if missingFiles.isEmpty {
print("Migration integrity verified - all files present")
print("Migration integrity verified - all files present")
cleanupLegacyDirectory()
} else {
print("⚠️ Missing \(missingFiles.count) files, re-triggering migration")
print("WARNING: Missing \(missingFiles.count) files, re-triggering migration")
// Re-trigger migration for missing files
performMigrationWithCheckpoints(
files: Array(missingFiles),
@@ -364,16 +364,16 @@ class ImageManager {
))
}
} catch {
print(" Failed to verify migration integrity: \(error)")
print("ERROR: Failed to verify migration integrity: \(error)")
}
}
private func cleanupLegacyDirectory() {
do {
try fileManager.removeItem(at: legacyImagesDirectory)
print("🗑️ Cleaned up legacy directory")
print("Cleaned up legacy directory")
} catch {
print("⚠️ Failed to clean up legacy directory: \(error)")
print("WARNING: Failed to clean up legacy directory: \(error)")
}
}
@@ -395,14 +395,14 @@ class ImageManager {
// Check if state is too old (more than 1 hour)
if Date().timeIntervalSince(state.lastCheckpoint) > 3600 {
print("⚠️ Migration state is stale, starting fresh")
print("WARNING: Migration state is stale, starting fresh")
removeMigrationState()
return nil
}
return state.isComplete ? nil : state
} catch {
print(" Failed to load migration state: \(error)")
print("ERROR: Failed to load migration state: \(error)")
removeMigrationState()
return nil
}
@@ -413,7 +413,7 @@ class ImageManager {
let data = try JSONEncoder().encode(state)
try data.write(to: migrationStateURL)
} catch {
print(" Failed to save migration state: \(error)")
print("ERROR: Failed to save migration state: \(error)")
}
}
@@ -429,7 +429,7 @@ class ImageManager {
private func cleanupMigrationState() {
try? fileManager.removeItem(at: migrationStateURL)
try? fileManager.removeItem(at: migrationLockURL)
print("🧹 Cleaned up migration state files")
print("Cleaned up migration state files")
}
func saveImageData(_ data: Data, withName name: String? = nil) -> String? {
@@ -444,10 +444,10 @@ class ImageManager {
// Create backup copy
try data.write(to: backupPath)
print("Saved image with backup: \(fileName)")
print("Saved image with backup: \(fileName)")
return fileName
} catch {
print(" Failed to save image \(fileName): \(error)")
print("ERROR: Failed to save image \(fileName): \(error)")
return nil
}
}
@@ -467,7 +467,7 @@ class ImageManager {
if fileManager.fileExists(atPath: backupPath.path),
let data = try? Data(contentsOf: backupPath)
{
print("📦 Restored image from backup: \(path)")
print("Restored image from backup: \(path)")
// Restore to primary location
try? data.write(to: URL(fileURLWithPath: primaryPath))
@@ -497,7 +497,7 @@ class ImageManager {
do {
try fileManager.removeItem(atPath: primaryPath)
} catch {
print(" Failed to delete primary image at \(primaryPath): \(error)")
print("ERROR: Failed to delete primary image at \(primaryPath): \(error)")
success = false
}
}
@@ -507,7 +507,7 @@ class ImageManager {
do {
try fileManager.removeItem(at: backupPath)
} catch {
print(" Failed to delete backup image at \(backupPath.path): \(error)")
print("ERROR: Failed to delete backup image at \(backupPath.path): \(error)")
success = false
}
}
@@ -544,7 +544,7 @@ class ImageManager {
}
func performMaintenance() {
print("🔧 Starting image maintenance...")
print("Starting image maintenance...")
syncBackups()
validateImageIntegrity()
@@ -562,11 +562,11 @@ class ImageManager {
let backupPath = backupDirectory.appendingPathComponent(fileName)
try? fileManager.copyItem(at: primaryPath, to: backupPath)
print("🔄 Created missing backup for: \(fileName)")
print("Created missing backup for: \(fileName)")
}
}
} catch {
print(" Failed to sync backups: \(error)")
print("ERROR: Failed to sync backups: \(error)")
}
}
@@ -585,15 +585,15 @@ class ImageManager {
}
}
print("Validated \(validFiles) of \(files.count) image files")
print("Validated \(validFiles) of \(files.count) image files")
} catch {
print(" Failed to validate images: \(error)")
print("ERROR: Failed to validate images: \(error)")
}
}
private func cleanupOrphanedFiles() {
// This would need access to the data manager to check which files are actually referenced
print("🧹 Cleanup would require coordination with data manager")
print("Cleanup would require coordination with data manager")
}
func getStorageInfo() -> (primaryCount: Int, backupCount: Int, totalSize: Int64) {
@@ -623,7 +623,7 @@ class ImageManager {
let previousDir = findPreviousAppSupportImages()
print(
"""
📁 OpenClimb Image Storage:
OpenClimb Image Storage:
- App Support: \(appSupportDirectory.path)
- Images: \(imagesDirectory.path) (\(info.primaryCount) files)
- Backups: \(backupDirectory.path) (\(info.backupCount) files)
@@ -635,7 +635,7 @@ class ImageManager {
}
func forceRecoveryMigration() {
print("🚨 FORCE RECOVERY: Starting manual migration recovery...")
print("FORCE RECOVERY: Starting manual migration recovery...")
// Remove any stale state
removeMigrationState()
@@ -644,7 +644,7 @@ class ImageManager {
// Force fresh migration
startNewMigration()
print("🚨 FORCE RECOVERY: Migration recovery completed")
print("FORCE RECOVERY: Migration recovery completed")
}
func saveImportedImage(_ imageData: Data, filename: String) throws -> String {
@@ -657,12 +657,12 @@ class ImageManager {
// Create backup
try? imageData.write(to: backupPath)
print("📥 Imported image: \(filename)")
print("Imported image: \(filename)")
return filename
}
func emergencyImageRestore() {
print("🆘 EMERGENCY: Attempting image restoration...")
print("EMERGENCY: Attempting image restoration...")
// Try to restore from backup directory
do {
@@ -680,14 +680,14 @@ class ImageManager {
}
}
print("🆘 EMERGENCY: Restored \(restoredCount) images from backup")
print("EMERGENCY: Restored \(restoredCount) images from backup")
} catch {
print("🆘 EMERGENCY: Failed to restore from backup: \(error)")
print("EMERGENCY: Failed to restore from backup: \(error)")
}
// Try previous Application Support directories first
if let previousAppSupportImages = findPreviousAppSupportImages() {
print("🆘 EMERGENCY: Found previous Application Support images, migrating...")
print("EMERGENCY: Found previous Application Support images, migrating...")
migratePreviousAppSupportImages(from: previousAppSupportImages)
return
}
@@ -696,21 +696,21 @@ class ImageManager {
if fileManager.fileExists(atPath: legacyImagesDirectory.path)
|| fileManager.fileExists(atPath: legacyImportImagesDirectory.path)
{
print("🆘 EMERGENCY: Attempting legacy migration as fallback...")
print("EMERGENCY: Attempting legacy migration as fallback...")
forceRecoveryMigration()
}
}
func debugSafeInitialization() -> Bool {
print("🐛 DEBUG SAFE: Performing debug-safe initialization check...")
print("DEBUG SAFE: Performing debug-safe initialization check...")
// Check if we're in a debug environment
#if DEBUG
print("🐛 DEBUG SAFE: Debug environment detected")
print("DEBUG SAFE: Debug environment detected")
// Check for interrupted migration more aggressively
if fileManager.fileExists(atPath: migrationLockURL.path) {
print("🐛 DEBUG SAFE: Found migration lock - likely debug interruption")
print("DEBUG SAFE: Found migration lock - likely debug interruption")
// Give extra time for file system to stabilize
Thread.sleep(forTimeInterval: 1.0)
@@ -732,14 +732,14 @@ class ImageManager {
((try? fileManager.contentsOfDirectory(atPath: backupDirectory.path)) ?? []).count > 0
if primaryEmpty && backupHasFiles {
print("🐛 DEBUG SAFE: Primary empty but backup exists - restoring")
print("DEBUG SAFE: Primary empty but backup exists - restoring")
emergencyImageRestore()
return true
}
// Check if primary storage is empty but previous Application Support images exist
if primaryEmpty, let previousAppSupportImages = findPreviousAppSupportImages() {
print("🐛 DEBUG SAFE: Primary empty but found previous Application Support images")
print("DEBUG SAFE: Primary empty but found previous Application Support images")
migratePreviousAppSupportImages(from: previousAppSupportImages)
return true
}
@@ -755,13 +755,15 @@ class ImageManager {
// Check if we have more backups than primary files (sign of corruption)
if backupFiles.count > primaryFiles.count + 5 {
print("⚠️ INTEGRITY: Backup count significantly exceeds primary - potential corruption")
print(
"WARNING INTEGRITY: Backup count significantly exceeds primary - potential corruption"
)
return false
}
// Check if primary is completely empty but we have data elsewhere
if primaryFiles.isEmpty && !backupFiles.isEmpty {
print("⚠️ INTEGRITY: Primary storage empty but backups exist")
print("WARNING INTEGRITY: Primary storage empty but backups exist")
return false
}
@@ -775,7 +777,7 @@ class ImageManager {
for: .applicationSupportDirectory, in: .userDomainMask
).first
else {
print(" Could not access Application Support directory")
print("ERROR: Could not access Application Support directory")
return nil
}
@@ -808,13 +810,13 @@ class ImageManager {
}
}
} catch {
print(" Error scanning for previous Application Support directories: \(error)")
print("ERROR: Error scanning for previous Application Support directories: \(error)")
}
return nil
}
private func migratePreviousAppSupportImages(from sourceDirectory: URL) {
print("🔄 Migrating images from previous Application Support directory")
print("Migrating images from previous Application Support directory")
do {
let imageFiles = try fileManager.contentsOfDirectory(atPath: sourceDirectory.path)
@@ -837,17 +839,17 @@ class ImageManager {
// Create backup
try? fileManager.copyItem(at: sourcePath, to: backupPath)
print("Migrated: \(fileName)")
print("Migrated: \(fileName)")
} catch {
print(" Failed to migrate \(fileName): \(error)")
print("ERROR: Failed to migrate \(fileName): \(error)")
}
}
}
print("Completed migration from previous Application Support directory")
print("Completed migration from previous Application Support directory")
} catch {
print(" Failed to migrate from previous Application Support: \(error)")
print("ERROR: Failed to migrate from previous Application Support: \(error)")
}
}
}

View File

@@ -0,0 +1,132 @@
//
// ImageNamingUtils.swift
import CryptoKit
import Foundation
/// Utility for creating consistent image filenames across platforms
class ImageNamingUtils {
private static let imageExtension = ".jpg"
private static let hashLength = 12
/// Generates a deterministic filename for a problem image
static func generateImageFilename(problemId: String, timestamp: String, imageIndex: Int)
-> String
{
let input = "\(problemId)_\(timestamp)_\(imageIndex)"
let hash = createHash(from: input)
return "problem_\(hash)_\(imageIndex)\(imageExtension)"
}
/// Generates a deterministic filename using current timestamp
static func generateImageFilename(problemId: String, imageIndex: Int) -> String {
let timestamp = ISO8601DateFormatter().string(from: Date())
return generateImageFilename(
problemId: problemId, timestamp: timestamp, imageIndex: imageIndex)
}
/// Extracts problem ID from an image filename
static func extractProblemIdFromFilename(_ filename: String) -> String? {
guard filename.hasPrefix("problem_") && filename.hasSuffix(imageExtension) else {
return nil
}
let nameWithoutExtension = String(filename.dropLast(imageExtension.count))
let parts = nameWithoutExtension.components(separatedBy: "_")
guard parts.count == 3 && parts[0] == "problem" else {
return nil
}
return parts[1]
}
/// Validates if a filename follows our naming convention
static func isValidImageFilename(_ filename: String) -> Bool {
guard filename.hasPrefix("problem_") && filename.hasSuffix(imageExtension) else {
return false
}
let nameWithoutExtension = String(filename.dropLast(imageExtension.count))
let parts = nameWithoutExtension.components(separatedBy: "_")
return parts.count == 3 && parts[0] == "problem" && parts[1].count == hashLength
&& Int(parts[2]) != nil
}
/// Migrates an existing filename to our naming convention
static func migrateFilename(oldFilename: String, problemId: String, imageIndex: Int) -> String {
if isValidImageFilename(oldFilename) {
return oldFilename
}
let timestamp = ISO8601DateFormatter().string(from: Date())
return generateImageFilename(
problemId: problemId, timestamp: timestamp, imageIndex: imageIndex)
}
/// Creates a deterministic hash from input string
private static func createHash(from input: String) -> String {
let inputData = Data(input.utf8)
let hashed = SHA256.hash(data: inputData)
let hashString = hashed.compactMap { String(format: "%02x", $0) }.joined()
return String(hashString.prefix(hashLength))
}
/// Batch renames images for a problem to use our naming convention
static func batchRenameForProblem(problemId: String, existingFilenames: [String]) -> [String:
String]
{
var renameMap: [String: String] = [:]
for (index, oldFilename) in existingFilenames.enumerated() {
let newFilename = migrateFilename(
oldFilename: oldFilename, problemId: problemId, imageIndex: index)
if newFilename != oldFilename {
renameMap[oldFilename] = newFilename
}
}
return renameMap
}
/// Validates that a collection of filenames follow our naming convention
static func validateFilenames(_ filenames: [String]) -> ImageValidationResult {
var validImages: [String] = []
var invalidImages: [String] = []
for filename in filenames {
if isValidImageFilename(filename) {
validImages.append(filename)
} else {
invalidImages.append(filename)
}
}
return ImageValidationResult(
totalImages: filenames.count,
validImages: validImages,
invalidImages: invalidImages
)
}
}
// Result of image filename validation
struct ImageValidationResult {
let totalImages: Int
let validImages: [String]
let invalidImages: [String]
var isAllValid: Bool {
return invalidImages.isEmpty
}
var validPercentage: Double {
guard totalImages > 0 else { return 100.0 }
return (Double(validImages.count) / Double(totalImages)) * 100.0
}
}

View File

@@ -29,6 +29,12 @@ class ClimbingDataManager: ObservableObject {
private let decoder = JSONDecoder()
private var liveActivityObserver: NSObjectProtocol?
// Sync service for automatic syncing
let syncService = SyncService()
// Published property to propagate sync state changes
@Published var isSyncing = false
private enum Keys {
static let gyms = "openclimb_gyms"
static let problems = "openclimb_problems"
@@ -64,6 +70,10 @@ class ClimbingDataManager: ObservableObject {
migrateImagePaths()
setupLiveActivityNotifications()
// Keep our published isSyncing in sync with syncService.isSyncing
syncService.$isSyncing
.assign(to: &$isSyncing)
Task {
try? await Task.sleep(nanoseconds: 2_000_000_000)
await performImageMaintenance()
@@ -200,16 +210,24 @@ class ClimbingDataManager: ObservableObject {
func addGym(_ gym: Gym) {
gyms.append(gym)
saveGyms()
DataStateManager.shared.updateDataState()
successMessage = "Gym added successfully"
clearMessageAfterDelay()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
func updateGym(_ gym: Gym) {
if let index = gyms.firstIndex(where: { $0.id == gym.id }) {
gyms[index] = gym
saveGyms()
DataStateManager.shared.updateDataState()
successMessage = "Gym updated successfully"
clearMessageAfterDelay()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
}
@@ -229,8 +247,12 @@ class ClimbingDataManager: ObservableObject {
// Delete the gym
gyms.removeAll { $0.id == gym.id }
saveGyms()
DataStateManager.shared.updateDataState()
successMessage = "Gym deleted successfully"
clearMessageAfterDelay()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
func gym(withId id: UUID) -> Gym? {
@@ -240,16 +262,24 @@ class ClimbingDataManager: ObservableObject {
func addProblem(_ problem: Problem) {
problems.append(problem)
saveProblems()
DataStateManager.shared.updateDataState()
successMessage = "Problem added successfully"
clearMessageAfterDelay()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
func updateProblem(_ problem: Problem) {
if let index = problems.firstIndex(where: { $0.id == problem.id }) {
problems[index] = problem
saveProblems()
DataStateManager.shared.updateDataState()
successMessage = "Problem updated successfully"
clearMessageAfterDelay()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
}
@@ -264,6 +294,10 @@ class ClimbingDataManager: ObservableObject {
// Delete the problem
problems.removeAll { $0.id == problem.id }
saveProblems()
DataStateManager.shared.updateDataState()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
func problem(withId id: UUID) -> Problem? {
@@ -279,7 +313,7 @@ class ClimbingDataManager: ObservableObject {
}
func startSession(gymId: UUID, notes: String? = nil) {
// End any currently active session
if let currentActive = activeSession {
endSession(currentActive.id)
}
@@ -290,6 +324,7 @@ class ClimbingDataManager: ObservableObject {
saveActiveSession()
saveSessions()
DataStateManager.shared.updateDataState()
successMessage = "Session started successfully"
clearMessageAfterDelay()
@@ -301,6 +336,9 @@ class ClimbingDataManager: ObservableObject {
for: newSession, gymName: gym.name)
}
}
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
func endSession(_ sessionId: UUID) {
@@ -317,9 +355,13 @@ class ClimbingDataManager: ObservableObject {
saveActiveSession()
saveSessions()
DataStateManager.shared.updateDataState()
successMessage = "Session completed successfully"
clearMessageAfterDelay()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
// MARK: - End Live Activity after session ends
Task {
await LiveActivityManager.shared.endLiveActivity()
@@ -337,11 +379,15 @@ class ClimbingDataManager: ObservableObject {
}
saveSessions()
DataStateManager.shared.updateDataState()
successMessage = "Session updated successfully"
clearMessageAfterDelay()
// Update Live Activity when session updates
// Update Live Activity when session is updated
updateLiveActivityForActiveSession()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
}
@@ -350,7 +396,7 @@ class ClimbingDataManager: ObservableObject {
attempts.removeAll { $0.sessionId == session.id }
saveAttempts()
// Remove from active session if it's the current one
// If this is the active session, clear it
if activeSession?.id == session.id {
activeSession = nil
saveActiveSession()
@@ -359,8 +405,15 @@ class ClimbingDataManager: ObservableObject {
// Delete the session
sessions.removeAll { $0.id == session.id }
saveSessions()
DataStateManager.shared.updateDataState()
successMessage = "Session deleted successfully"
clearMessageAfterDelay()
// Update Live Activity when session is deleted
updateLiveActivityForActiveSession()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
func session(withId id: UUID) -> ClimbSession? {
@@ -380,8 +433,12 @@ class ClimbingDataManager: ObservableObject {
func addAttempt(_ attempt: Attempt) {
attempts.append(attempt)
saveAttempts()
DataStateManager.shared.updateDataState()
successMessage = "Attempt logged successfully"
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
clearMessageAfterDelay()
// Update Live Activity when new attempt is added
@@ -392,22 +449,30 @@ class ClimbingDataManager: ObservableObject {
if let index = attempts.firstIndex(where: { $0.id == attempt.id }) {
attempts[index] = attempt
saveAttempts()
DataStateManager.shared.updateDataState()
successMessage = "Attempt updated successfully"
clearMessageAfterDelay()
// Update Live Activity when attempt is updated
updateLiveActivityForActiveSession()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
}
func deleteAttempt(_ attempt: Attempt) {
attempts.removeAll { $0.id == attempt.id }
saveAttempts()
DataStateManager.shared.updateDataState()
successMessage = "Attempt deleted successfully"
clearMessageAfterDelay()
// Update Live Activity when attempt is deleted
updateLiveActivityForActiveSession()
// Trigger auto-sync if enabled
syncService.triggerAutoSync(dataManager: self)
}
func attempts(forSession sessionId: UUID) -> [Attempt] {
@@ -451,7 +516,7 @@ class ClimbingDataManager: ObservableObject {
return gym(withId: mostUsedGymId)
}
func resetAllData() {
func resetAllData(showSuccessMessage: Bool = true) {
gyms.removeAll()
problems.removeAll()
sessions.removeAll()
@@ -464,8 +529,12 @@ class ClimbingDataManager: ObservableObject {
userDefaults.removeObject(forKey: Keys.attempts)
userDefaults.removeObject(forKey: Keys.activeSession)
successMessage = "All data has been reset"
clearMessageAfterDelay()
DataStateManager.shared.reset()
if showSuccessMessage {
successMessage = "All data has been reset"
clearMessageAfterDelay()
}
}
func exportData() -> Data? {
@@ -485,26 +554,26 @@ class ClimbingDataManager: ObservableObject {
// Collect referenced image paths
let referencedImagePaths = collectReferencedImagePaths()
print("🎯 Starting export with \(referencedImagePaths.count) images")
print("Starting export with \(referencedImagePaths.count) images")
let zipData = try ZipUtils.createExportZip(
exportData: exportData,
referencedImagePaths: referencedImagePaths
)
print("Export completed successfully")
print("Export completed successfully")
successMessage = "Export completed with \(referencedImagePaths.count) images"
clearMessageAfterDelay()
return zipData
} catch {
let errorMessage = "Export failed: \(error.localizedDescription)"
print(" \(errorMessage)")
print("ERROR: \(errorMessage)")
setError(errorMessage)
return nil
}
}
func importData(from data: Data) throws {
func importData(from data: Data, showSuccessMessage: Bool = true) throws {
do {
let importResult = try ZipUtils.extractImportZip(data: data)
@@ -540,7 +609,7 @@ class ClimbingDataManager: ObservableObject {
try validateImportData(importData)
resetAllData()
resetAllData(showSuccessMessage: showSuccessMessage)
let updatedProblems = updateProblemImagePaths(
problems: importData.problems,
@@ -557,9 +626,14 @@ class ClimbingDataManager: ObservableObject {
saveSessions()
saveAttempts()
successMessage =
"Data imported successfully with \(importResult.imagePathMapping.count) images"
clearMessageAfterDelay()
// Update data state to current time since we just imported new data
DataStateManager.shared.updateDataState()
if showSuccessMessage {
successMessage =
"Data imported successfully with \(importResult.imagePathMapping.count) images"
clearMessageAfterDelay()
}
} catch {
setError("Import failed: \(error.localizedDescription)")
throw error
@@ -588,13 +662,13 @@ class ClimbingDataManager: ObservableObject {
extension ClimbingDataManager {
private func collectReferencedImagePaths() -> Set<String> {
var imagePaths = Set<String>()
print("🖼️ Starting image path collection...")
print("📊 Total problems: \(problems.count)")
print("Starting image path collection...")
print("Total problems: \(problems.count)")
for problem in problems {
if !problem.imagePaths.isEmpty {
print(
"📸 Problem '\(problem.name ?? "Unnamed")' has \(problem.imagePaths.count) images"
"Problem '\(problem.name ?? "Unnamed")' has \(problem.imagePaths.count) images"
)
for imagePath in problem.imagePaths {
print(" - Relative path: \(imagePath)")
@@ -603,10 +677,10 @@ extension ClimbingDataManager {
// Check if file exists
if FileManager.default.fileExists(atPath: fullPath) {
print(" File exists")
print(" File exists")
imagePaths.insert(fullPath)
} else {
print(" File does NOT exist")
print(" File does NOT exist")
// Still add it to let ZipUtils handle the error logging
imagePaths.insert(fullPath)
}
@@ -614,7 +688,7 @@ extension ClimbingDataManager {
}
}
print("🖼️ Collected \(imagePaths.count) total image paths for export")
print("Collected \(imagePaths.count) total image paths for export")
return imagePaths
}
@@ -674,7 +748,7 @@ extension ClimbingDataManager {
// Log storage information for debugging
let info = await ImageManager.shared.getStorageInfo()
print(
"📊 Image Storage: \(info.primaryCount) primary, \(info.backupCount) backup, \(info.totalSize / 1024)KB total"
"Image Storage: \(info.primaryCount) primary, \(info.backupCount) backup, \(info.totalSize / 1024)KB total"
)
}.value
}
@@ -712,7 +786,7 @@ extension ClimbingDataManager {
}
if !orphanedFiles.isEmpty {
print("🗑️ Cleaned up \(orphanedFiles.count) orphaned image files")
print("Cleaned up \(orphanedFiles.count) orphaned image files")
}
}
}
@@ -729,7 +803,7 @@ extension ClimbingDataManager {
}
func forceImageRecovery() {
print("🚨 User initiated force image recovery")
print("User initiated force image recovery")
ImageManager.shared.forceRecoveryMigration()
// Refresh the UI after recovery
@@ -737,7 +811,7 @@ extension ClimbingDataManager {
}
func emergencyImageRestore() {
print("🆘 User initiated emergency image restore")
print("User initiated emergency image restore")
ImageManager.shared.emergencyImageRestore()
// Refresh the UI after restore
@@ -753,7 +827,7 @@ extension ClimbingDataManager {
let info = ImageManager.shared.getStorageInfo()
return """
Image Storage Health: \(isValid ? "Good" : "Needs Recovery")
Image Storage Health: \(isValid ? "Good" : "Needs Recovery")
Primary Files: \(info.primaryCount)
Backup Files: \(info.backupCount)
Total Size: \(formatBytes(info.totalSize))
@@ -771,7 +845,7 @@ extension ClimbingDataManager {
// Test with dummy data if we have a gym
guard let testGym = gyms.first else {
print(" No gyms available for testing")
print("ERROR: No gyms available for testing")
return
}
@@ -803,14 +877,14 @@ extension ClimbingDataManager {
// Only restart if session is actually active
guard activeSession.status == .active else {
print(
"⚠️ Session exists but is not active (status: \(activeSession.status)), ending Live Activity"
"WARNING: Session exists but is not active (status: \(activeSession.status)), ending Live Activity"
)
await LiveActivityManager.shared.endLiveActivity()
return
}
if let gym = gym(withId: activeSession.gymId) {
print("🔍 Checking Live Activity for active session at \(gym.name)")
print("Checking Live Activity for active session at \(gym.name)")
// First cleanup any dismissed activities
await LiveActivityManager.shared.cleanupDismissedActivities()
@@ -820,15 +894,12 @@ extension ClimbingDataManager {
activeSession: activeSession,
gymName: gym.name
)
// Update with current session data
await updateLiveActivityData()
}
}
/// Call this when app becomes active to check for Live Activity restart
func onAppBecomeActive() {
print("📱 App became active - checking Live Activity status")
print("App became active - checking Live Activity status")
Task {
await checkAndRestartLiveActivity()
}
@@ -836,7 +907,7 @@ extension ClimbingDataManager {
/// Call this when app enters background to update Live Activity
func onAppEnterBackground() {
print("📱 App entering background - updating Live Activity if needed")
print("App entering background - updating Live Activity if needed")
Task {
await updateLiveActivityData()
}
@@ -865,7 +936,7 @@ extension ClimbingDataManager {
return
}
print("🔄 Attempting to restart dismissed Live Activity for \(gym.name)")
print("Attempting to restart dismissed Live Activity for \(gym.name)")
// Wait a bit before restarting to avoid frequency limits
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
@@ -905,7 +976,7 @@ extension ClimbingDataManager {
activeSession.status == .active,
let gym = gym(withId: activeSession.gymId)
else {
print("⚠️ Live Activity update skipped - no active session or gym")
print("WARNING: Live Activity update skipped - no active session or gym")
if let session = activeSession {
print(" Session ID: \(session.id)")
print(" Session Status: \(session.status)")
@@ -929,7 +1000,7 @@ extension ClimbingDataManager {
elapsedInterval = 0
}
print("🔄 Live Activity Update Debug:")
print("Live Activity Update Debug:")
print(" Session ID: \(activeSession.id)")
print(" Gym: \(gym.name)")
print(" Total attempts in session: \(totalAttempts)")

View File

@@ -34,11 +34,11 @@ final class LiveActivityManager {
let isStillActive = activities.contains { $0.id == currentActivity.id }
if isStillActive {
print(" Live Activity still running: \(currentActivity.id)")
print("Live Activity still running: \(currentActivity.id)")
return
} else {
print(
"⚠️ Tracked Live Activity \(currentActivity.id) was dismissed, clearing reference"
"WARNING: Tracked Live Activity \(currentActivity.id) was dismissed, clearing reference"
)
self.currentActivity = nil
}
@@ -47,18 +47,18 @@ final class LiveActivityManager {
// Check if there are ANY active Live Activities for this session
let existingActivities = Activity<SessionActivityAttributes>.activities
if let existingActivity = existingActivities.first {
print(" Found existing Live Activity: \(existingActivity.id), using it")
print("Found existing Live Activity: \(existingActivity.id), using it")
self.currentActivity = existingActivity
return
}
print("🔄 No Live Activity found, restarting for existing session")
print("No Live Activity found, restarting for existing session")
await startLiveActivity(for: activeSession, gymName: gymName)
}
/// Call this when a ClimbSession starts to begin a Live Activity
func startLiveActivity(for session: ClimbSession, gymName: String) async {
print("🔴 Starting Live Activity for gym: \(gymName)")
print("Starting Live Activity for gym: \(gymName)")
await endLiveActivity()
@@ -84,9 +84,9 @@ final class LiveActivityManager {
pushType: nil
)
self.currentActivity = activity
print("Live Activity started successfully: \(activity.id)")
print("Live Activity started successfully: \(activity.id)")
} catch {
print(" Failed to start live activity: \(error)")
print("ERROR: Failed to start live activity: \(error)")
print("Error details: \(error.localizedDescription)")
// Check specific error types
@@ -104,7 +104,7 @@ final class LiveActivityManager {
func updateLiveActivity(elapsed: TimeInterval, totalAttempts: Int, completedProblems: Int) async
{
guard let currentActivity = currentActivity else {
print("⚠️ No current activity to update")
print("WARNING: No current activity to update")
return
}
@@ -114,14 +114,14 @@ final class LiveActivityManager {
if !isStillActive {
print(
"⚠️ Tracked Live Activity \(currentActivity.id) is no longer active, clearing reference"
"WARNING: Tracked Live Activity \(currentActivity.id) is no longer active, clearing reference"
)
self.currentActivity = nil
return
}
print(
"🔄 Updating Live Activity - Attempts: \(totalAttempts), Completed: \(completedProblems)"
"Updating Live Activity - Attempts: \(totalAttempts), Completed: \(completedProblems)"
)
let updatedContentState = SessionActivityAttributes.ContentState(
@@ -131,7 +131,7 @@ final class LiveActivityManager {
)
await currentActivity.update(.init(state: updatedContentState, staleDate: nil))
print("Live Activity updated successfully")
print("Live Activity updated successfully")
}
/// Call this when a ClimbSession ends to end the Live Activity
@@ -141,25 +141,25 @@ final class LiveActivityManager {
// First end the tracked activity if it exists
if let currentActivity {
print("🔴 Ending tracked Live Activity: \(currentActivity.id)")
print("Ending tracked Live Activity: \(currentActivity.id)")
await currentActivity.end(nil, dismissalPolicy: .immediate)
self.currentActivity = nil
print("Tracked Live Activity ended successfully")
print("Tracked Live Activity ended successfully")
}
// Force end ALL active activities of our type to ensure cleanup
print("🔍 Checking for any remaining active activities...")
print("Checking for any remaining active activities...")
let activities = Activity<SessionActivityAttributes>.activities
if activities.isEmpty {
print(" No additional activities found")
print("No additional activities found")
} else {
print("🔴 Found \(activities.count) additional active activities, ending them...")
print("Found \(activities.count) additional active activities, ending them...")
for activity in activities {
print("🔴 Force ending activity: \(activity.id)")
print("Force ending activity: \(activity.id)")
await activity.end(nil, dismissalPolicy: .immediate)
}
print("All Live Activities ended successfully")
print("All Live Activities ended successfully")
}
}
@@ -188,7 +188,7 @@ final class LiveActivityManager {
if let currentActivity = currentActivity {
let isStillActive = activities.contains { $0.id == currentActivity.id }
if !isStillActive {
print("🧹 Cleaning up dismissed Live Activity: \(currentActivity.id)")
print("Cleaning up dismissed Live Activity: \(currentActivity.id)")
self.currentActivity = nil
}
}
@@ -211,7 +211,7 @@ final class LiveActivityManager {
func stopHealthChecks() {
healthCheckTimer?.invalidate()
healthCheckTimer = nil
print("🛑 Stopped Live Activity health checks")
print("Stopped Live Activity health checks")
}
/// Perform a health check on the current Live Activity
@@ -231,7 +231,7 @@ final class LiveActivityManager {
let isStillActive = activities.contains { $0.id == currentActivity.id }
if !isStillActive {
print("💔 Health check failed - Live Activity was dismissed")
print("Health check failed - Live Activity was dismissed")
self.currentActivity = nil
// Notify that we need to restart
@@ -240,7 +240,7 @@ final class LiveActivityManager {
object: nil
)
} else {
print("Live Activity health check passed")
print("Live Activity health check passed")
}
}

View File

@@ -42,7 +42,7 @@ struct AddAttemptView: View {
}
var body: some View {
NavigationView {
NavigationStack {
Form {
if !showingCreateProblem {
ProblemSelectionSection()
@@ -597,7 +597,7 @@ struct ProblemExpandedView: View {
@State private var selectedImageIndex = 0
var body: some View {
NavigationView {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
// Images
@@ -735,7 +735,7 @@ struct EditAttemptView: View {
}
var body: some View {
NavigationView {
NavigationStack {
Form {
if !showingCreateProblem {
ProblemSelectionSection()

View File

@@ -1,4 +1,3 @@
import SwiftUI
struct AddEditGymView: View {
@@ -34,7 +33,7 @@ struct AddEditGymView: View {
}
var body: some View {
NavigationView {
NavigationStack {
Form {
BasicInfoSection()
ClimbTypesSection()

View File

@@ -55,7 +55,7 @@ struct AddEditProblemView: View {
}
var body: some View {
NavigationView {
NavigationStack {
Form {
GymSelectionSection()
BasicInfoSection()

View File

@@ -1,4 +1,3 @@
import SwiftUI
struct AddEditSessionView: View {
@@ -21,7 +20,7 @@ struct AddEditSessionView: View {
}
var body: some View {
NavigationView {
NavigationStack {
Form {
GymSelectionSection()
SessionDetailsSection()

View File

@@ -4,7 +4,7 @@ struct AnalyticsView: View {
@EnvironmentObject var dataManager: ClimbingDataManager
var body: some View {
NavigationView {
NavigationStack {
ScrollView {
LazyVStack(spacing: 20) {
OverallStatsSection()
@@ -20,6 +20,27 @@ struct AnalyticsView: View {
.padding()
}
.navigationTitle("Analytics")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
if dataManager.isSyncing {
HStack(spacing: 2) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .blue))
.scaleEffect(0.6)
}
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(
Circle()
.fill(.regularMaterial)
)
.transition(.scale.combined(with: .opacity))
.animation(
.easeInOut(duration: 0.2), value: dataManager.isSyncing
)
}
}
}
}
}
}

View File

@@ -420,7 +420,7 @@ struct ImageViewerView: View {
}
var body: some View {
NavigationView {
NavigationStack {
TabView(selection: $currentIndex) {
ForEach(imagePaths.indices, id: \.self) { index in
ProblemDetailImageFullView(imagePath: imagePaths[index])

View File

@@ -9,24 +9,11 @@ struct SessionDetailView: View {
@State private var showingAddAttempt = false
@State private var editingAttempt: Attempt?
@State private var attemptToDelete: Attempt?
@State private var currentTime = Date()
private var session: ClimbSession? {
dataManager.session(withId: sessionId)
}
private func startTimer() {
// Update every 5 seconds instead of 1 second for better performance
timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in
currentTime = Date()
}
}
private func stopTimer() {
timer?.invalidate()
timer = nil
}
private var gym: Gym? {
guard let session = session else { return nil }
return dataManager.gym(withId: session.gymId)
@@ -47,14 +34,12 @@ struct SessionDetailView: View {
calculateSessionStats()
}
@State private var timer: Timer?
var body: some View {
ScrollView {
LazyVStack(spacing: 20) {
if let session = session, let gym = gym {
SessionHeaderCard(
session: session, gym: gym, stats: sessionStats, currentTime: currentTime)
session: session, gym: gym, stats: sessionStats)
SessionStatsCard(stats: sessionStats)
@@ -69,12 +54,7 @@ struct SessionDetailView: View {
}
.padding()
}
.onAppear {
startTimer()
}
.onDisappear {
stopTimer()
}
.navigationTitle("Session Details")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
@@ -182,7 +162,6 @@ struct SessionHeaderCard: View {
let session: ClimbSession
let gym: Gym
let stats: SessionStats
let currentTime: Date
var body: some View {
VStack(alignment: .leading, spacing: 16) {
@@ -197,9 +176,13 @@ struct SessionHeaderCard: View {
if session.status == .active {
if let startTime = session.startTime {
Text("Duration: \(formatDuration(from: startTime, to: currentTime))")
Text("Duration: ")
.font(.subheadline)
.foregroundColor(.secondary)
+ Text(timerInterval: startTime...Date.distantFuture, countsDown: false)
.font(.subheadline)
.foregroundColor(.secondary)
.monospacedDigit()
}
} else if let duration = session.duration {
Text("Duration: \(duration) minutes")
@@ -246,20 +229,6 @@ struct SessionHeaderCard: View {
return formatter.string(from: date)
}
private func formatDuration(from start: Date, to end: Date) -> String {
let interval = end.timeIntervalSince(start)
let hours = Int(interval) / 3600
let minutes = Int(interval) % 3600 / 60
let seconds = Int(interval) % 60
if hours > 0 {
return String(format: "%dh %dm %ds", hours, minutes, seconds)
} else if minutes > 0 {
return String(format: "%dm %ds", minutes, seconds)
} else {
return String(format: "%ds", seconds)
}
}
}
struct SessionStatsCard: View {

View File

@@ -5,7 +5,7 @@ struct GymsView: View {
@State private var showingAddGym = false
var body: some View {
NavigationView {
NavigationStack {
VStack {
if dataManager.gyms.isEmpty {
EmptyGymsView()
@@ -15,7 +15,25 @@ struct GymsView: View {
}
.navigationTitle("Gyms")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if dataManager.isSyncing {
HStack(spacing: 2) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .blue))
.scaleEffect(0.6)
}
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(
Circle()
.fill(.regularMaterial)
)
.transition(.scale.combined(with: .opacity))
.animation(
.easeInOut(duration: 0.2), value: dataManager.isSyncing
)
}
Button("Add") {
showingAddGym = true
}

View File

@@ -1,9 +1,5 @@
//
// LiveActivityDebugView.swift
// OpenClimb
//
// Created by Assistant on 2025-09-15.
//
import SwiftUI
@@ -13,7 +9,7 @@ struct LiveActivityDebugView: View {
@State private var isTestRunning = false
var body: some View {
NavigationView {
NavigationStack {
VStack(alignment: .leading, spacing: 20) {
// Header
@@ -91,7 +87,7 @@ struct LiveActivityDebugView: View {
.disabled(dataManager.activeSession == nil)
if dataManager.gyms.isEmpty {
Text("⚠️ Add at least one gym to test Live Activities")
Text("WARNING: Add at least one gym to test Live Activities")
.font(.caption)
.foregroundColor(.orange)
}
@@ -171,29 +167,31 @@ struct LiveActivityDebugView: View {
}
private func checkStatus() {
appendDebugOutput("🔍 Checking Live Activity status...")
appendDebugOutput("Checking Live Activity status...")
let status = LiveActivityManager.shared.checkLiveActivityAvailability()
appendDebugOutput("Status: \(status)")
// Check iOS version
if #available(iOS 16.1, *) {
appendDebugOutput("iOS version supports Live Activities")
appendDebugOutput("iOS version supports Live Activities")
} else {
appendDebugOutput("❌ iOS version does not support Live Activities (requires 16.1+)")
appendDebugOutput(
"ERROR: iOS version does not support Live Activities (requires 16.1+)")
}
// Check if we're on simulator
#if targetEnvironment(simulator)
appendDebugOutput("⚠️ Running on Simulator - Live Activities have limited functionality")
appendDebugOutput(
"WARNING: Running on Simulator - Live Activities have limited functionality")
#else
appendDebugOutput("Running on device - Live Activities should work fully")
appendDebugOutput("Running on device - Live Activities should work fully")
#endif
}
private func testLiveActivity() {
guard !dataManager.gyms.isEmpty else {
appendDebugOutput(" No gyms available for testing")
appendDebugOutput("ERROR: No gyms available for testing")
return
}
@@ -244,25 +242,25 @@ struct LiveActivityDebugView: View {
appendDebugOutput("Ending Live Activity...")
await LiveActivityManager.shared.endLiveActivity()
appendDebugOutput("🏁 Live Activity test completed!")
appendDebugOutput("Live Activity test completed!")
}
}
private func endCurrentSession() {
guard let activeSession = dataManager.activeSession else {
appendDebugOutput(" No active session to end")
appendDebugOutput("ERROR: No active session to end")
return
}
appendDebugOutput("🛑 Ending current session: \(activeSession.id)")
appendDebugOutput("Ending current session: \(activeSession.id)")
dataManager.endSession(activeSession.id)
appendDebugOutput("Session ended")
appendDebugOutput("Session ended")
}
private func forceLiveActivityUpdate() {
appendDebugOutput("🔄 Forcing Live Activity update...")
appendDebugOutput("Forcing Live Activity update...")
dataManager.forceLiveActivityUpdate()
appendDebugOutput("Live Activity update sent")
appendDebugOutput("Live Activity update sent")
}
}

View File

@@ -6,6 +6,8 @@ struct ProblemsView: View {
@State private var selectedClimbType: ClimbType?
@State private var selectedGym: Gym?
@State private var searchText = ""
@State private var showingSearch = false
@FocusState private var isSearchFocused: Bool
private var filteredProblems: [Problem] {
var filtered = dataManager.problems
@@ -38,31 +40,103 @@ struct ProblemsView: View {
}
var body: some View {
NavigationView {
VStack(spacing: 0) {
if !dataManager.problems.isEmpty {
FilterSection(
selectedClimbType: $selectedClimbType,
selectedGym: $selectedGym,
filteredProblems: filteredProblems
)
.padding()
.background(.regularMaterial)
}
NavigationStack {
Group {
VStack(spacing: 0) {
if showingSearch {
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
.foregroundColor(.secondary)
.font(.system(size: 16, weight: .medium))
if filteredProblems.isEmpty {
EmptyProblemsView(
isEmpty: dataManager.problems.isEmpty,
isFiltered: !dataManager.problems.isEmpty
)
} else {
ProblemsList(problems: filteredProblems)
TextField("Search problems...", text: $searchText)
.textFieldStyle(.plain)
.font(.system(size: 16))
.focused($isSearchFocused)
.submitLabel(.search)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background {
if #available(iOS 18.0, *) {
RoundedRectangle(cornerRadius: 12)
.fill(.regularMaterial)
.overlay {
RoundedRectangle(cornerRadius: 12)
.stroke(.quaternary, lineWidth: 0.5)
}
} else {
RoundedRectangle(cornerRadius: 10)
.fill(Color(.systemGray6))
.overlay {
RoundedRectangle(cornerRadius: 10)
.stroke(Color(.systemGray4), lineWidth: 0.5)
}
}
}
.padding(.horizontal)
.padding(.top, 8)
.animation(.easeInOut(duration: 0.3), value: showingSearch)
}
if !dataManager.problems.isEmpty && !showingSearch {
FilterSection(
selectedClimbType: $selectedClimbType,
selectedGym: $selectedGym,
filteredProblems: filteredProblems
)
.padding()
.background(.regularMaterial)
}
if filteredProblems.isEmpty {
EmptyProblemsView(
isEmpty: dataManager.problems.isEmpty,
isFiltered: !dataManager.problems.isEmpty
)
} else {
ProblemsList(problems: filteredProblems)
}
}
}
.navigationTitle("Problems")
.searchable(text: $searchText, prompt: "Search problems...")
.navigationBarTitleDisplayMode(.automatic)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if dataManager.isSyncing {
HStack(spacing: 2) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .blue))
.scaleEffect(0.6)
}
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(
Circle()
.fill(.regularMaterial)
)
.transition(.scale.combined(with: .opacity))
.animation(
.easeInOut(duration: 0.2), value: dataManager.isSyncing
)
}
Button(action: {
withAnimation(.easeInOut(duration: 0.3)) {
showingSearch.toggle()
if showingSearch {
isSearchFocused = true
} else {
searchText = ""
isSearchFocused = false
}
}
}) {
Image(systemName: showingSearch ? "xmark.circle.fill" : "magnifyingglass")
.font(.system(size: 16, weight: .medium))
.foregroundColor(showingSearch ? .secondary : .blue)
}
if !dataManager.gyms.isEmpty {
Button("Add") {
showingAddProblem = true

View File

@@ -6,7 +6,7 @@ struct SessionsView: View {
@State private var showingAddSession = false
var body: some View {
NavigationView {
NavigationStack {
Group {
if dataManager.sessions.isEmpty && dataManager.activeSession == nil {
EmptySessionsView()
@@ -17,7 +17,25 @@ struct SessionsView: View {
.navigationTitle("Sessions")
.navigationBarTitleDisplayMode(.automatic)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if dataManager.isSyncing {
HStack(spacing: 2) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .blue))
.scaleEffect(0.6)
}
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(
Circle()
.fill(.regularMaterial)
)
.transition(.scale.combined(with: .opacity))
.animation(
.easeInOut(duration: 0.2), value: dataManager.isSyncing
)
}
if dataManager.gyms.isEmpty {
EmptyView()
} else if dataManager.activeSession == nil {
@@ -35,7 +53,6 @@ struct SessionsView: View {
AddEditSessionView()
}
}
.navigationViewStyle(.stack)
}
}
@@ -111,11 +128,8 @@ struct ActiveSessionBanner: View {
let session: ClimbSession
let gym: Gym
@EnvironmentObject var dataManager: ClimbingDataManager
@State private var currentTime = Date()
@State private var navigateToDetail = false
@State private var timer: Timer?
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
@@ -133,9 +147,10 @@ struct ActiveSessionBanner: View {
.foregroundColor(.secondary)
if let startTime = session.startTime {
Text(formatDuration(from: startTime, to: currentTime))
Text(timerInterval: startTime...Date.distantFuture, countsDown: false)
.font(.caption)
.foregroundColor(.secondary)
.monospacedDigit()
}
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -162,42 +177,12 @@ struct ActiveSessionBanner: View {
.fill(.green.opacity(0.1))
.stroke(.green.opacity(0.3), lineWidth: 1)
)
.onAppear {
startTimer()
}
.onDisappear {
stopTimer()
}
.navigationDestination(isPresented: $navigateToDetail) {
SessionDetailView(sessionId: session.id)
}
}
private func formatDuration(from start: Date, to end: Date) -> String {
let interval = end.timeIntervalSince(start)
let hours = Int(interval) / 3600
let minutes = Int(interval) % 3600 / 60
let seconds = Int(interval) % 60
if hours > 0 {
return String(format: "%dh %dm %ds", hours, minutes, seconds)
} else if minutes > 0 {
return String(format: "%dm %ds", minutes, seconds)
} else {
return String(format: "%ds", seconds)
}
}
private func startTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in
currentTime = Date()
}
}
private func stopTimer() {
timer?.invalidate()
timer = nil
}
}
struct SessionRow: View {

View File

@@ -11,25 +11,52 @@ struct SettingsView: View {
@State private var activeSheet: SheetType?
var body: some View {
List {
DataManagementSection(
activeSheet: $activeSheet
)
NavigationStack {
List {
SyncSection()
.environmentObject(dataManager.syncService)
AppInfoSection()
}
.navigationTitle("Settings")
.sheet(
item: Binding<SheetType?>(
get: { activeSheet },
set: { activeSheet = $0 }
)
) { sheetType in
switch sheetType {
case .export(let data):
ExportDataView(data: data)
case .importData:
ImportDataView()
DataManagementSection(
activeSheet: $activeSheet
)
AppInfoSection()
}
.navigationTitle("Settings")
.navigationBarTitleDisplayMode(.automatic)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
if dataManager.isSyncing {
HStack(spacing: 2) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .blue))
.scaleEffect(0.6)
}
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(
Circle()
.fill(.regularMaterial)
)
.transition(.scale.combined(with: .opacity))
.animation(
.easeInOut(duration: 0.2), value: dataManager.isSyncing
)
}
}
}
.sheet(
item: Binding<SheetType?>(
get: { activeSheet },
set: { activeSheet = $0 }
)
) { sheetType in
switch sheetType {
case .export(let data):
ExportDataView(data: data)
case .importData:
ImportDataView()
}
}
}
}
@@ -167,7 +194,7 @@ struct ExportDataView: View {
@State private var isCreatingFile = true
var body: some View {
NavigationView {
NavigationStack {
VStack(spacing: 30) {
if isCreatingFile {
// Loading state - more prominent
@@ -303,6 +330,362 @@ struct ExportDataView: View {
}
}
struct SyncSection: View {
@EnvironmentObject var syncService: SyncService
@EnvironmentObject var dataManager: ClimbingDataManager
@State private var showingSyncSettings = false
@State private var showingDisconnectAlert = false
var body: some View {
Section("Sync") {
// Sync Status
HStack {
Image(
systemName: syncService.isConnected
? "checkmark.circle.fill"
: syncService.isConfigured
? "exclamationmark.triangle.fill"
: "exclamationmark.circle.fill"
)
.foregroundColor(
syncService.isConnected
? .green
: syncService.isConfigured
? .orange
: .red
)
VStack(alignment: .leading) {
Text("Sync Server")
.font(.headline)
Text(
syncService.isConnected
? "Connected"
: syncService.isConfigured
? "Configured - Not tested"
: "Not configured"
)
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
}
// Configure Server
Button(action: {
showingSyncSettings = true
}) {
HStack {
Image(systemName: "gear")
.foregroundColor(.blue)
Text("Configure Server")
Spacer()
Image(systemName: "chevron.right")
.font(.caption)
.foregroundColor(.secondary)
}
}
.foregroundColor(.primary)
if syncService.isConfigured {
// Sync Now - only show if connected
if syncService.isConnected {
Button(action: {
performSync()
}) {
HStack {
if syncService.isSyncing {
ProgressView()
.scaleEffect(0.8)
Text("Syncing...")
.foregroundColor(.secondary)
} else {
Image(systemName: "arrow.triangle.2.circlepath")
.foregroundColor(.green)
Text("Sync Now")
Spacer()
if let lastSync = syncService.lastSyncTime {
Text(
RelativeDateTimeFormatter().localizedString(
for: lastSync, relativeTo: Date())
)
.font(.caption)
.foregroundColor(.secondary)
}
}
}
}
.disabled(syncService.isSyncing)
.foregroundColor(.primary)
}
// Auto-sync configuration - always visible for testing
HStack {
VStack(alignment: .leading) {
Text("Auto-sync")
Text("Sync automatically on app launch and data changes")
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
Toggle(
"",
isOn: Binding(
get: { syncService.isAutoSyncEnabled },
set: { syncService.isAutoSyncEnabled = $0 }
)
)
.disabled(!syncService.isConnected)
}
.foregroundColor(.primary)
// Disconnect option - only show if connected
if syncService.isConnected {
Button(action: {
showingDisconnectAlert = true
}) {
HStack {
Image(systemName: "power")
.foregroundColor(.orange)
Text("Disconnect")
Spacer()
}
}
.foregroundColor(.primary)
}
if let error = syncService.syncError {
Text(error)
.font(.caption)
.foregroundColor(.red)
.padding(.leading, 24)
}
}
}
.sheet(isPresented: $showingSyncSettings) {
SyncSettingsView()
.environmentObject(syncService)
}
.alert("Disconnect from Server", isPresented: $showingDisconnectAlert) {
Button("Cancel", role: .cancel) {}
Button("Disconnect", role: .destructive) {
syncService.disconnect()
}
} message: {
Text(
"This will sign you out but keep your server settings. You'll need to test the connection again to sync."
)
}
}
private func performSync() {
Task {
do {
try await syncService.syncWithServer(dataManager: dataManager)
} catch {
print("Sync failed: \(error)")
}
}
}
}
struct SyncSettingsView: View {
@EnvironmentObject var syncService: SyncService
@Environment(\.dismiss) private var dismiss
@State private var serverURL: String = ""
@State private var authToken: String = ""
@State private var showingDisconnectAlert = false
@State private var isTesting = false
@State private var showingTestResult = false
@State private var testResultMessage = ""
var body: some View {
NavigationStack {
Form {
Section {
TextField("Server URL", text: $serverURL)
.textFieldStyle(.roundedBorder)
.keyboardType(.URL)
.autocapitalization(.none)
.disableAutocorrection(true)
.placeholder(when: serverURL.isEmpty) {
Text("http://your-server:8080")
.foregroundColor(.secondary)
}
TextField("Auth Token", text: $authToken)
.textFieldStyle(.roundedBorder)
.autocapitalization(.none)
.disableAutocorrection(true)
.placeholder(when: authToken.isEmpty) {
Text("your-secret-token")
.foregroundColor(.secondary)
}
} header: {
Text("Server Configuration")
} footer: {
Text(
"Enter your sync server URL and authentication token. You must test the connection before syncing is available."
)
}
Section {
Button(action: {
testConnection()
}) {
HStack {
if isTesting {
ProgressView()
.scaleEffect(0.8)
Text("Testing...")
.foregroundColor(.secondary)
} else {
Image(systemName: "network")
.foregroundColor(.blue)
Text("Test Connection")
Spacer()
if syncService.isConnected {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
}
}
}
}
.disabled(
isTesting
|| serverURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|| authToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
)
.foregroundColor(.primary)
} header: {
Text("Connection")
} footer: {
Text("Test the connection to verify your server settings before saving.")
}
Section {
Button("Disconnect from Server") {
showingDisconnectAlert = true
}
.foregroundColor(.orange)
Button("Clear Configuration") {
syncService.clearConfiguration()
serverURL = ""
authToken = ""
}
.foregroundColor(.red)
} footer: {
Text(
"Disconnect will sign you out but keep settings. Clear Configuration removes all sync settings."
)
}
}
.navigationTitle("Sync Settings")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") {
dismiss()
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
let newURL = serverURL.trimmingCharacters(in: .whitespacesAndNewlines)
let newToken = authToken.trimmingCharacters(in: .whitespacesAndNewlines)
// Mark as disconnected if settings changed
if newURL != syncService.serverURL || newToken != syncService.authToken {
syncService.isConnected = false
UserDefaults.standard.set(false, forKey: "sync_is_connected")
}
syncService.serverURL = newURL
syncService.authToken = newToken
dismiss()
}
.fontWeight(.semibold)
}
}
}
.onAppear {
serverURL = syncService.serverURL
authToken = syncService.authToken
}
.alert("Disconnect from Server", isPresented: $showingDisconnectAlert) {
Button("Cancel", role: .cancel) {}
Button("Disconnect", role: .destructive) {
syncService.disconnect()
dismiss()
}
} message: {
Text(
"This will sign you out but keep your server settings. You'll need to test the connection again to sync."
)
}
.alert("Connection Test", isPresented: $showingTestResult) {
Button("OK") {}
} message: {
Text(testResultMessage)
}
}
private func testConnection() {
isTesting = true
let testURL = serverURL.trimmingCharacters(in: .whitespacesAndNewlines)
let testToken = authToken.trimmingCharacters(in: .whitespacesAndNewlines)
// Store original values in case test fails
let originalURL = syncService.serverURL
let originalToken = syncService.authToken
Task {
do {
// Temporarily set the values for testing
syncService.serverURL = testURL
syncService.authToken = testToken
try await syncService.testConnection()
await MainActor.run {
isTesting = false
testResultMessage =
"Connection successful! You can now save and sync your data."
showingTestResult = true
}
} catch {
// Restore original values if test failed
syncService.serverURL = originalURL
syncService.authToken = originalToken
await MainActor.run {
isTesting = false
testResultMessage = "Connection failed: \(error.localizedDescription)"
showingTestResult = true
}
}
}
}
}
// Removed AutoSyncSettingsView - now using simple toggle in main settings
extension View {
func placeholder<Content: View>(
when shouldShow: Bool,
alignment: Alignment = .leading,
@ViewBuilder placeholder: () -> Content
) -> some View {
ZStack(alignment: alignment) {
placeholder().opacity(shouldShow ? 1 : 0)
self
}
}
}
struct ImportDataView: View {
@EnvironmentObject var dataManager: ClimbingDataManager
@Environment(\.dismiss) private var dismiss
@@ -311,7 +694,7 @@ struct ImportDataView: View {
@State private var showingDocumentPicker = false
var body: some View {
NavigationView {
NavigationStack {
VStack(spacing: 20) {
Image(systemName: "square.and.arrow.down")
.font(.system(size: 60))
@@ -325,7 +708,7 @@ struct ImportDataView: View {
Text("Import climbing data from a previously exported ZIP file.")
.multilineTextAlignment(.center)
Text("⚠️ Warning: This will replace all current data!")
Text("WARNING: This will replace all current data!")
.font(.subheadline)
.foregroundColor(.red)
.multilineTextAlignment(.center)

View File

@@ -0,0 +1,255 @@
import XCTest
final class OpenClimbTests: XCTestCase {
override func setUpWithError() throws {
}
override func tearDownWithError() throws {
}
// MARK: - Data Validation Tests
func testDifficultyGradeComparison() throws {
// Test basic difficulty grade string comparison
let grade1 = "V5"
let grade2 = "V3"
let grade3 = "V5"
XCTAssertEqual(grade1, grade3)
XCTAssertNotEqual(grade1, grade2)
XCTAssertFalse(grade1.isEmpty)
}
func testClimbTypeValidation() throws {
// Test climb type validation
let validClimbTypes = ["ROPE", "BOULDER"]
for climbType in validClimbTypes {
XCTAssertTrue(validClimbTypes.contains(climbType))
XCTAssertFalse(climbType.isEmpty)
}
let invalidTypes = ["", "unknown", "invalid", "sport", "trad", "toprope"]
for invalidType in invalidTypes {
if !invalidType.isEmpty {
XCTAssertFalse(validClimbTypes.contains(invalidType))
}
}
}
func testDateFormatting() throws {
// Test ISO 8601 date formatting
let formatter = ISO8601DateFormatter()
let date = Date()
let formattedDate = formatter.string(from: date)
XCTAssertFalse(formattedDate.isEmpty)
XCTAssertTrue(formattedDate.contains("T"))
XCTAssertTrue(formattedDate.hasSuffix("Z"))
// Test parsing back
let parsedDate = formatter.date(from: formattedDate)
XCTAssertNotNil(parsedDate)
}
func testSessionDurationCalculation() throws {
// Test session duration calculation
let startTime = Date()
let endTime = Date(timeInterval: 3600, since: startTime) // 1 hour later
let duration = endTime.timeIntervalSince(startTime)
XCTAssertEqual(duration, 3600, accuracy: 1.0)
XCTAssertGreaterThan(duration, 0)
}
func testAttemptResultValidation() throws {
// Test attempt result validation
let validResults = ["completed", "failed", "flash", "project"]
for result in validResults {
XCTAssertTrue(validResults.contains(result))
XCTAssertFalse(result.isEmpty)
}
}
func testGymCreation() throws {
// Test gym model creation with basic validation
let gymName = "Test Climbing Gym"
let location = "Test City"
let supportedTypes = ["BOULDER", "ROPE"]
XCTAssertFalse(gymName.isEmpty)
XCTAssertFalse(location.isEmpty)
XCTAssertFalse(supportedTypes.isEmpty)
XCTAssertEqual(supportedTypes.count, 2)
XCTAssertTrue(supportedTypes.contains("BOULDER"))
XCTAssertTrue(supportedTypes.contains("ROPE"))
}
func testProblemValidation() throws {
// Test problem model validation
let problemName = "Test Problem"
let climbType = "BOULDER"
let difficulty = "V5"
let tags = ["overhang", "crimpy"]
XCTAssertFalse(problemName.isEmpty)
XCTAssertTrue(["BOULDER", "ROPE"].contains(climbType))
XCTAssertFalse(difficulty.isEmpty)
XCTAssertEqual(tags.count, 2)
XCTAssertTrue(tags.allSatisfy { !$0.isEmpty })
}
func testSessionStatusTransitions() throws {
// Test session status transitions
let validStatuses = ["planned", "active", "completed", "cancelled"]
for status in validStatuses {
XCTAssertTrue(validStatuses.contains(status))
XCTAssertFalse(status.isEmpty)
}
// Test status transitions logic
let initialStatus = "planned"
let activeStatus = "active"
let completedStatus = "completed"
XCTAssertNotEqual(initialStatus, activeStatus)
XCTAssertNotEqual(activeStatus, completedStatus)
}
func testUniqueIDGeneration() throws {
// Test unique ID generation using UUID
let id1 = UUID().uuidString
let id2 = UUID().uuidString
XCTAssertNotEqual(id1, id2)
XCTAssertFalse(id1.isEmpty)
XCTAssertFalse(id2.isEmpty)
XCTAssertEqual(id1.count, 36) // UUID string length
XCTAssertTrue(id1.contains("-"))
}
func testDataValidation() throws {
// Test basic data validation patterns
let emptyString = ""
let validString = "test"
let negativeNumber = -1
let positiveNumber = 5
let zeroNumber = 0
XCTAssertTrue(emptyString.isEmpty)
XCTAssertFalse(validString.isEmpty)
XCTAssertLessThan(negativeNumber, 0)
XCTAssertGreaterThan(positiveNumber, 0)
XCTAssertEqual(zeroNumber, 0)
}
// MARK: - Collection Tests
func testArrayOperations() throws {
// Test array operations for climb data
var problems: [String] = []
XCTAssertTrue(problems.isEmpty)
XCTAssertEqual(problems.count, 0)
problems.append("Problem 1")
problems.append("Problem 2")
XCTAssertFalse(problems.isEmpty)
XCTAssertEqual(problems.count, 2)
XCTAssertTrue(problems.contains("Problem 1"))
let filteredProblems = problems.filter { $0.contains("1") }
XCTAssertEqual(filteredProblems.count, 1)
}
func testDictionaryOperations() throws {
// Test dictionary operations for data storage
var gymData: [String: Any] = [:]
XCTAssertTrue(gymData.isEmpty)
gymData["name"] = "Test Gym"
gymData["location"] = "Test City"
gymData["types"] = ["BOULDER", "ROPE"]
XCTAssertFalse(gymData.isEmpty)
XCTAssertEqual(gymData.count, 3)
XCTAssertNotNil(gymData["name"])
if let name = gymData["name"] as? String {
XCTAssertEqual(name, "Test Gym")
} else {
XCTFail("Failed to cast gym name to String")
}
}
// MARK: - String and Numeric Tests
func testStringManipulation() throws {
// Test string operations common in climb data
let problemName = " Test Problem V5 "
let trimmedName = problemName.trimmingCharacters(in: .whitespacesAndNewlines)
let uppercaseName = trimmedName.uppercased()
let lowercaseName = trimmedName.lowercased()
XCTAssertEqual(trimmedName, "Test Problem V5")
XCTAssertEqual(uppercaseName, "TEST PROBLEM V5")
XCTAssertEqual(lowercaseName, "test problem v5")
let components = trimmedName.components(separatedBy: " ")
XCTAssertEqual(components.count, 3)
XCTAssertEqual(components.last, "V5")
}
func testNumericOperations() throws {
// Test numeric operations for climb ratings and statistics
let grades = [3, 5, 7, 4, 6]
let sum = grades.reduce(0, +)
let average = Double(sum) / Double(grades.count)
let maxGrade = grades.max() ?? 0
let minGrade = grades.min() ?? 0
XCTAssertEqual(sum, 25)
XCTAssertEqual(average, 5.0, accuracy: 0.01)
XCTAssertEqual(maxGrade, 7)
XCTAssertEqual(minGrade, 3)
}
// MARK: - JSON and Data Format Tests
func testJSONSerialization() throws {
// Test JSON serialization for basic data structures
let testData: [String: Any] = [
"id": "test123",
"name": "Test Gym",
"active": true,
"rating": 4.5,
"types": ["BOULDER", "ROPE"],
]
XCTAssertNoThrow({
let jsonData = try JSONSerialization.data(withJSONObject: testData)
XCTAssertFalse(jsonData.isEmpty)
let deserializedData =
try JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
XCTAssertNotNil(deserializedData)
XCTAssertEqual(deserializedData?["name"] as? String, "Test Gym")
})
}
func testDateSerialization() throws {
// Test date serialization for API compatibility
let date = Date()
let formatter = ISO8601DateFormatter()
let dateString = formatter.string(from: date)
let parsedDate = formatter.date(from: dateString)
XCTAssertNotNil(parsedDate)
XCTAssertEqual(date.timeIntervalSince1970, parsedDate!.timeIntervalSince1970, accuracy: 1.0)
}
}

View File

@@ -1,12 +1,8 @@
//
// AppIntent.swift
// SessionStatusLive
//
// Created by Atridad Lahiji on 2025-09-15.
//
import WidgetKit
import AppIntents
import WidgetKit
struct ConfigurationAppIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource { "Configuration" }

View File

@@ -1,9 +1,5 @@
//
// SessionStatusLive.swift
// SessionStatusLive
//
// Created by Atridad Lahiji on 2025-09-15.
//
import SwiftUI
import WidgetKit

View File

@@ -1,12 +1,8 @@
//
// SessionStatusLiveBundle.swift
// SessionStatusLive
//
// Created by Atridad Lahiji on 2025-09-15.
//
import WidgetKit
import SwiftUI
import WidgetKit
@main
struct SessionStatusLiveBundle: WidgetBundle {

View File

@@ -1,9 +1,5 @@
//
// SessionStatusLiveControl.swift
// SessionStatusLive
//
// Created by Atridad Lahiji on 2025-09-15.
//
import AppIntents
import SwiftUI
@@ -42,8 +38,9 @@ extension SessionStatusLiveControl {
}
func currentValue(configuration: TimerConfiguration) async throws -> Value {
let isRunning = true // Check if the timer is running
return SessionStatusLiveControl.Value(isRunning: isRunning, name: configuration.timerName)
let isRunning = true // Check if the timer is running
return SessionStatusLiveControl.Value(
isRunning: isRunning, name: configuration.timerName)
}
}
}

View File

@@ -1,9 +1,5 @@
//
// SessionStatusLiveLiveActivity.swift
// SessionStatusLive
//
// Created by Atridad Lahiji on 2025-09-15.
//
import ActivityKit
import SwiftUI

9
sync/.env.example Normal file
View File

@@ -0,0 +1,9 @@
# Required
AUTH_TOKEN=your-secure-secret-token-here
IMAGE="git.atri.dad/atridad/openclimb-sync:latest"
APP_PORT=1337
ROOT_DIR="./data"
# Optional
DATA_FILE=/data/data.json
IMAGES_DIR=/data/images

16
sync/.gitignore vendored Normal file
View File

@@ -0,0 +1,16 @@
# Binaries
sync-server
openclimb-sync
# Go workspace file
go.work
# Data directory
data/
# Environment files
.env
.env.local
# OS generated files
.DS_Store

14
sync/Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
FROM golang:1.25-alpine AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o sync-server .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/sync-server .
EXPOSE 8080
CMD ["./sync-server"]

13
sync/docker-compose.yml Normal file
View File

@@ -0,0 +1,13 @@
services:
openclimb-sync:
image: ${IMAGE}
ports:
- ${APP_PORT}:8080
environment:
- AUTH_TOKEN=${AUTH_TOKEN}
- DATA_FILE=${DATA_FILE}
- IMAGES_DIR=${IMAGES_DIR}
volumes:
- ${ROOT_DIR}:/data
restart: unless-stopped
networks: {}

479
sync/format_test.go Normal file
View File

@@ -0,0 +1,479 @@
package main
import (
"encoding/json"
"strings"
"testing"
)
func TestDataFormatCompatibility(t *testing.T) {
t.Run("JSON Marshaling and Unmarshaling", func(t *testing.T) {
originalBackup := ClimbDataBackup{
ExportedAt: "2024-01-01T10:00:00Z",
Version: "2.0",
FormatVersion: "2.0",
Gyms: []BackupGym{
{
ID: "gym1",
Name: "Test Gym",
Location: stringPtr("Test Location"),
SupportedClimbTypes: []string{"BOULDER", "ROPE"},
DifficultySystems: []string{"V", "YDS"},
CustomDifficultyGrades: []string{"V0+", "V1+"},
Notes: stringPtr("Test notes"),
CreatedAt: "2024-01-01T10:00:00Z",
UpdatedAt: "2024-01-01T10:00:00Z",
},
},
Problems: []BackupProblem{
{
ID: "problem1",
GymID: "gym1",
Name: stringPtr("Test Problem"),
Description: stringPtr("A challenging problem"),
ClimbType: "BOULDER",
Difficulty: DifficultyGrade{
System: "V",
Grade: "V5",
NumericValue: 5,
},
Tags: []string{"overhang", "crimpy"},
Location: stringPtr("Wall A"),
ImagePaths: []string{"image1.jpg", "image2.jpg"},
IsActive: true,
DateSet: stringPtr("2024-01-01"),
Notes: stringPtr("Watch the start"),
CreatedAt: "2024-01-01T10:00:00Z",
UpdatedAt: "2024-01-01T10:00:00Z",
},
},
Sessions: []BackupClimbSession{
{
ID: "session1",
GymID: "gym1",
Date: "2024-01-01",
StartTime: stringPtr("2024-01-01T10:00:00Z"),
EndTime: stringPtr("2024-01-01T12:00:00Z"),
Duration: int64Ptr(7200),
Status: "completed",
Notes: stringPtr("Great session"),
CreatedAt: "2024-01-01T10:00:00Z",
UpdatedAt: "2024-01-01T12:00:00Z",
},
},
Attempts: []BackupAttempt{
{
ID: "attempt1",
SessionID: "session1",
ProblemID: "problem1",
Result: "completed",
HighestHold: stringPtr("Top"),
Notes: stringPtr("Clean send"),
Duration: int64Ptr(300),
RestTime: int64Ptr(120),
Timestamp: "2024-01-01T10:30:00Z",
CreatedAt: "2024-01-01T10:30:00Z",
},
},
}
jsonData, err := json.Marshal(originalBackup)
if err != nil {
t.Fatalf("Failed to marshal backup: %v", err)
}
var unmarshaledBackup ClimbDataBackup
if err := json.Unmarshal(jsonData, &unmarshaledBackup); err != nil {
t.Fatalf("Failed to unmarshal backup: %v", err)
}
if originalBackup.Version != unmarshaledBackup.Version {
t.Errorf("Version mismatch: expected %s, got %s", originalBackup.Version, unmarshaledBackup.Version)
}
if len(originalBackup.Gyms) != len(unmarshaledBackup.Gyms) {
t.Errorf("Gyms count mismatch: expected %d, got %d", len(originalBackup.Gyms), len(unmarshaledBackup.Gyms))
}
if len(originalBackup.Problems) != len(unmarshaledBackup.Problems) {
t.Errorf("Problems count mismatch: expected %d, got %d", len(originalBackup.Problems), len(unmarshaledBackup.Problems))
}
if len(originalBackup.Sessions) != len(unmarshaledBackup.Sessions) {
t.Errorf("Sessions count mismatch: expected %d, got %d", len(originalBackup.Sessions), len(unmarshaledBackup.Sessions))
}
if len(originalBackup.Attempts) != len(unmarshaledBackup.Attempts) {
t.Errorf("Attempts count mismatch: expected %d, got %d", len(originalBackup.Attempts), len(unmarshaledBackup.Attempts))
}
})
t.Run("Required Fields Validation", func(t *testing.T) {
testCases := []struct {
name string
jsonInput string
shouldError bool
}{
{
name: "Valid minimal backup",
jsonInput: `{
"exportedAt": "2024-01-01T10:00:00Z",
"version": "2.0",
"formatVersion": "2.0",
"gyms": [],
"problems": [],
"sessions": [],
"attempts": []
}`,
shouldError: false,
},
{
name: "Missing version field",
jsonInput: `{
"exportedAt": "2024-01-01T10:00:00Z",
"formatVersion": "2.0",
"gyms": [],
"problems": [],
"sessions": [],
"attempts": []
}`,
shouldError: false,
},
{
name: "Invalid JSON structure",
jsonInput: `{
"exportedAt": "2024-01-01T10:00:00Z",
"version": "2.0",
"formatVersion": "2.0",
"gyms": "not an array"
}`,
shouldError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
var backup ClimbDataBackup
err := json.Unmarshal([]byte(tc.jsonInput), &backup)
if tc.shouldError && err == nil {
t.Error("Expected error but got none")
}
if !tc.shouldError && err != nil {
t.Errorf("Unexpected error: %v", err)
}
})
}
})
t.Run("Difficulty Grade Format", func(t *testing.T) {
testGrades := []DifficultyGrade{
{System: "V", Grade: "V0", NumericValue: 0},
{System: "V", Grade: "V5", NumericValue: 5},
{System: "V", Grade: "V10", NumericValue: 10},
{System: "YDS", Grade: "5.10a", NumericValue: 100},
{System: "YDS", Grade: "5.12d", NumericValue: 124},
{System: "Font", Grade: "6A", NumericValue: 60},
{System: "Custom", Grade: "Beginner", NumericValue: 1},
}
for _, grade := range testGrades {
jsonData, err := json.Marshal(grade)
if err != nil {
t.Errorf("Failed to marshal grade %+v: %v", grade, err)
continue
}
var unmarshaledGrade DifficultyGrade
if err := json.Unmarshal(jsonData, &unmarshaledGrade); err != nil {
t.Errorf("Failed to unmarshal grade %s: %v", string(jsonData), err)
continue
}
if grade.System != unmarshaledGrade.System {
t.Errorf("System mismatch for grade %+v: expected %s, got %s", grade, grade.System, unmarshaledGrade.System)
}
if grade.Grade != unmarshaledGrade.Grade {
t.Errorf("Grade mismatch for grade %+v: expected %s, got %s", grade, grade.Grade, unmarshaledGrade.Grade)
}
if grade.NumericValue != unmarshaledGrade.NumericValue {
t.Errorf("NumericValue mismatch for grade %+v: expected %d, got %d", grade, grade.NumericValue, unmarshaledGrade.NumericValue)
}
}
})
t.Run("Null and Optional Fields", func(t *testing.T) {
jsonWithNulls := `{
"exportedAt": "2024-01-01T10:00:00Z",
"version": "2.0",
"formatVersion": "2.0",
"gyms": [{
"id": "gym1",
"name": "Test Gym",
"location": null,
"supportedClimbTypes": ["boulder"],
"difficultySystems": ["V"],
"customDifficultyGrades": [],
"notes": null,
"createdAt": "2024-01-01T10:00:00Z",
"updatedAt": "2024-01-01T10:00:00Z"
}],
"problems": [{
"id": "problem1",
"gymId": "gym1",
"name": null,
"description": null,
"climbType": "boulder",
"difficulty": {
"system": "V",
"grade": "V5",
"numericValue": 5
},
"tags": [],
"location": null,
"imagePaths": [],
"isActive": true,
"dateSet": null,
"notes": null,
"createdAt": "2024-01-01T10:00:00Z",
"updatedAt": "2024-01-01T10:00:00Z"
}],
"sessions": [],
"attempts": []
}`
var backup ClimbDataBackup
if err := json.Unmarshal([]byte(jsonWithNulls), &backup); err != nil {
t.Fatalf("Failed to unmarshal JSON with nulls: %v", err)
}
if backup.Gyms[0].Location != nil {
t.Error("Expected location to be nil")
}
if backup.Gyms[0].Notes != nil {
t.Error("Expected notes to be nil")
}
if backup.Problems[0].Name != nil {
t.Error("Expected problem name to be nil")
}
})
t.Run("Date Format Validation", func(t *testing.T) {
validDates := []string{
"2024-01-01T10:00:00Z",
"2024-12-31T23:59:59Z",
"2024-06-15T12:30:45Z",
"2024-01-01T00:00:00Z",
}
invalidDates := []string{
"2024-01-01 10:00:00",
"2024/01/01T10:00:00Z",
"2024-1-1T10:00:00Z",
}
for _, date := range validDates {
if !isValidISODate(date) {
t.Errorf("Valid date %s was marked as invalid", date)
}
}
for _, date := range invalidDates {
if isValidISODate(date) {
t.Errorf("Invalid date %s was marked as valid", date)
}
}
})
t.Run("Field Length Limits", func(t *testing.T) {
longString := strings.Repeat("a", 10000)
gym := BackupGym{
ID: "gym1",
Name: longString,
Location: &longString,
SupportedClimbTypes: []string{"boulder"},
DifficultySystems: []string{"V"},
CustomDifficultyGrades: []string{},
Notes: &longString,
CreatedAt: "2024-01-01T10:00:00Z",
UpdatedAt: "2024-01-01T10:00:00Z",
}
jsonData, err := json.Marshal(gym)
if err != nil {
t.Errorf("Failed to marshal gym with long strings: %v", err)
}
var unmarshaledGym BackupGym
if err := json.Unmarshal(jsonData, &unmarshaledGym); err != nil {
t.Errorf("Failed to unmarshal gym with long strings: %v", err)
}
if unmarshaledGym.Name != longString {
t.Error("Long name was not preserved")
}
})
t.Run("Array Field Validation", func(t *testing.T) {
backup := ClimbDataBackup{
ExportedAt: "2024-01-01T10:00:00Z",
Version: "2.0",
FormatVersion: "2.0",
Gyms: nil,
Problems: []BackupProblem{},
Sessions: []BackupClimbSession{},
Attempts: []BackupAttempt{},
}
jsonData, err := json.Marshal(backup)
if err != nil {
t.Fatalf("Failed to marshal backup with nil gyms: %v", err)
}
var unmarshaledBackup ClimbDataBackup
if err := json.Unmarshal(jsonData, &unmarshaledBackup); err != nil {
t.Fatalf("Failed to unmarshal backup with nil gyms: %v", err)
}
if len(unmarshaledBackup.Gyms) != 0 {
t.Error("Expected gyms to be empty or nil")
}
})
}
func isValidISODate(date string) bool {
// More robust ISO date validation
if !strings.Contains(date, "T") || !strings.HasSuffix(date, "Z") {
return false
}
// Check basic format: YYYY-MM-DDTHH:MM:SSZ
parts := strings.Split(date, "T")
if len(parts) != 2 {
return false
}
datePart := parts[0]
timePart := strings.TrimSuffix(parts[1], "Z")
// Date part should be YYYY-MM-DD
dateComponents := strings.Split(datePart, "-")
if len(dateComponents) != 3 || len(dateComponents[0]) != 4 || len(dateComponents[1]) != 2 || len(dateComponents[2]) != 2 {
return false
}
// Time part should be HH:MM:SS
timeComponents := strings.Split(timePart, ":")
if len(timeComponents) != 3 || len(timeComponents[0]) != 2 || len(timeComponents[1]) != 2 || len(timeComponents[2]) != 2 {
return false
}
return true
}
func TestVersionCompatibility(t *testing.T) {
testCases := []struct {
version string
formatVersion string
shouldSupport bool
}{
{"2.0", "2.0", true},
{"1.0", "1.0", true},
{"2.1", "2.0", false},
{"3.0", "2.0", false},
{"1.0", "2.0", false},
}
for _, tc := range testCases {
t.Run(tc.version+"/"+tc.formatVersion, func(t *testing.T) {
backup := ClimbDataBackup{
Version: tc.version,
FormatVersion: tc.formatVersion,
}
// Only exact version matches are supported for now
isSupported := backup.Version == "2.0" && backup.FormatVersion == "2.0"
if backup.Version == "1.0" && backup.FormatVersion == "1.0" {
isSupported = true
}
if isSupported != tc.shouldSupport {
t.Errorf("Version %s support expectation mismatch: expected %v, got %v",
tc.version, tc.shouldSupport, isSupported)
}
})
}
}
func TestClimbTypeValidation(t *testing.T) {
validClimbTypes := []string{"boulder", "sport", "trad", "toprope", "aid", "ice", "mixed"}
invalidClimbTypes := []string{"", "invalid", "BOULDER", "Sport", "unknown"}
for _, climbType := range validClimbTypes {
if !isValidClimbType(climbType) {
t.Errorf("Valid climb type %s was marked as invalid", climbType)
}
}
for _, climbType := range invalidClimbTypes {
if isValidClimbType(climbType) {
t.Errorf("Invalid climb type %s was marked as valid", climbType)
}
}
}
func isValidClimbType(climbType string) bool {
validTypes := map[string]bool{
"boulder": true,
"sport": true,
"trad": true,
"toprope": true,
"aid": true,
"ice": true,
"mixed": true,
}
return validTypes[climbType]
}
func TestAttemptResultValidation(t *testing.T) {
validResults := []string{"completed", "failed", "flash", "project", "attempt"}
invalidResults := []string{"", "invalid", "COMPLETED", "Failed", "unknown"}
for _, result := range validResults {
if !isValidAttemptResult(result) {
t.Errorf("Valid attempt result %s was marked as invalid", result)
}
}
for _, result := range invalidResults {
if isValidAttemptResult(result) {
t.Errorf("Invalid attempt result %s was marked as valid", result)
}
}
}
// Helper functions for creating pointers
func stringPtr(s string) *string {
return &s
}
func int64Ptr(i int64) *int64 {
return &i
}
func isValidAttemptResult(result string) bool {
validResults := map[string]bool{
"completed": true,
"failed": true,
"flash": true,
"project": true,
"attempt": true,
}
return validResults[result]
}

3
sync/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module openclimb-sync
go 1.21

358
sync/main.go Normal file
View File

@@ -0,0 +1,358 @@
package main
import (
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
func min(a, b int) int {
if a < b {
return a
}
return b
}
type ClimbDataBackup struct {
ExportedAt string `json:"exportedAt"`
Version string `json:"version"`
FormatVersion string `json:"formatVersion"`
Gyms []BackupGym `json:"gyms"`
Problems []BackupProblem `json:"problems"`
Sessions []BackupClimbSession `json:"sessions"`
Attempts []BackupAttempt `json:"attempts"`
}
type BackupGym struct {
ID string `json:"id"`
Name string `json:"name"`
Location *string `json:"location,omitempty"`
SupportedClimbTypes []string `json:"supportedClimbTypes"`
DifficultySystems []string `json:"difficultySystems"`
CustomDifficultyGrades []string `json:"customDifficultyGrades"`
Notes *string `json:"notes,omitempty"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}
type BackupProblem struct {
ID string `json:"id"`
GymID string `json:"gymId"`
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
ClimbType string `json:"climbType"`
Difficulty DifficultyGrade `json:"difficulty"`
Tags []string `json:"tags"`
Location *string `json:"location,omitempty"`
ImagePaths []string `json:"imagePaths,omitempty"`
IsActive bool `json:"isActive"`
DateSet *string `json:"dateSet,omitempty"`
Notes *string `json:"notes,omitempty"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}
type DifficultyGrade struct {
System string `json:"system"`
Grade string `json:"grade"`
NumericValue int `json:"numericValue"`
}
type BackupClimbSession struct {
ID string `json:"id"`
GymID string `json:"gymId"`
Date string `json:"date"`
StartTime *string `json:"startTime,omitempty"`
EndTime *string `json:"endTime,omitempty"`
Duration *int64 `json:"duration,omitempty"`
Status string `json:"status"`
Notes *string `json:"notes,omitempty"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}
type BackupAttempt struct {
ID string `json:"id"`
SessionID string `json:"sessionId"`
ProblemID string `json:"problemId"`
Result string `json:"result"`
HighestHold *string `json:"highestHold,omitempty"`
Notes *string `json:"notes,omitempty"`
Duration *int64 `json:"duration,omitempty"`
RestTime *int64 `json:"restTime,omitempty"`
Timestamp string `json:"timestamp"`
CreatedAt string `json:"createdAt"`
}
type SyncServer struct {
authToken string
dataFile string
imagesDir string
}
func (s *SyncServer) authenticate(r *http.Request) bool {
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
return false
}
token := strings.TrimPrefix(authHeader, "Bearer ")
return subtle.ConstantTimeCompare([]byte(token), []byte(s.authToken)) == 1
}
func (s *SyncServer) loadData() (*ClimbDataBackup, error) {
log.Printf("Loading data from: %s", s.dataFile)
if _, err := os.Stat(s.dataFile); os.IsNotExist(err) {
log.Printf("Data file does not exist, creating empty backup")
return &ClimbDataBackup{
ExportedAt: time.Now().UTC().Format(time.RFC3339),
Version: "2.0",
FormatVersion: "2.0",
Gyms: []BackupGym{},
Problems: []BackupProblem{},
Sessions: []BackupClimbSession{},
Attempts: []BackupAttempt{},
}, nil
}
data, err := os.ReadFile(s.dataFile)
if err != nil {
log.Printf("Failed to read data file: %v", err)
return nil, err
}
log.Printf("Read %d bytes from data file", len(data))
log.Printf("File content preview: %s", string(data[:min(200, len(data))]))
var backup ClimbDataBackup
if err := json.Unmarshal(data, &backup); err != nil {
log.Printf("Failed to unmarshal JSON: %v", err)
return nil, err
}
log.Printf("Loaded backup: gyms=%d, problems=%d, sessions=%d, attempts=%d",
len(backup.Gyms), len(backup.Problems), len(backup.Sessions), len(backup.Attempts))
return &backup, nil
}
func (s *SyncServer) saveData(backup *ClimbDataBackup) error {
backup.ExportedAt = time.Now().UTC().Format(time.RFC3339)
data, err := json.MarshalIndent(backup, "", " ")
if err != nil {
return err
}
dir := filepath.Dir(s.dataFile)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
// Ensure images directory exists
if err := os.MkdirAll(s.imagesDir, 0755); err != nil {
return err
}
return os.WriteFile(s.dataFile, data, 0644)
}
func (s *SyncServer) handleGet(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
log.Printf("Unauthorized access attempt from %s", r.RemoteAddr)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
log.Printf("GET /sync request from %s", r.RemoteAddr)
backup, err := s.loadData()
if err != nil {
log.Printf("Failed to load data: %v", err)
http.Error(w, "Failed to load data", http.StatusInternalServerError)
return
}
log.Printf("Sending data to %s: gyms=%d, problems=%d, sessions=%d, attempts=%d",
r.RemoteAddr, len(backup.Gyms), len(backup.Problems), len(backup.Sessions), len(backup.Attempts))
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(backup)
}
func (s *SyncServer) handlePut(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
log.Printf("Unauthorized sync attempt from %s", r.RemoteAddr)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var backup ClimbDataBackup
if err := json.NewDecoder(r.Body).Decode(&backup); err != nil {
log.Printf("Invalid JSON from %s: %v", r.RemoteAddr, err)
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if err := s.saveData(&backup); err != nil {
log.Printf("Failed to save data: %v", err)
http.Error(w, "Failed to save data", http.StatusInternalServerError)
return
}
log.Printf("Data synced by %s", r.RemoteAddr)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(backup)
}
func (s *SyncServer) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
"status": "healthy",
"time": time.Now().UTC().Format(time.RFC3339),
})
}
func (s *SyncServer) handleImageUpload(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
log.Printf("Unauthorized image upload attempt from %s", r.RemoteAddr)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
filename := r.URL.Query().Get("filename")
if filename == "" {
http.Error(w, "Missing filename parameter", http.StatusBadRequest)
return
}
imageData, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read image data", http.StatusBadRequest)
return
}
imagePath := filepath.Join(s.imagesDir, filename)
if err := os.WriteFile(imagePath, imageData, 0644); err != nil {
log.Printf("Failed to save image %s: %v", filename, err)
http.Error(w, "Failed to save image", http.StatusInternalServerError)
return
}
log.Printf("Image uploaded: %s (%d bytes) by %s", filename, len(imageData), r.RemoteAddr)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "uploaded"})
}
func (s *SyncServer) handleImageDownload(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
log.Printf("Unauthorized image download attempt from %s", r.RemoteAddr)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
filename := r.URL.Query().Get("filename")
if filename == "" {
http.Error(w, "Missing filename parameter", http.StatusBadRequest)
return
}
imagePath := filepath.Join(s.imagesDir, filename)
imageData, err := os.ReadFile(imagePath)
if err != nil {
if os.IsNotExist(err) {
http.Error(w, "Image not found", http.StatusNotFound)
} else {
http.Error(w, "Failed to read image", http.StatusInternalServerError)
}
return
}
// Set appropriate content type based on file extension
ext := filepath.Ext(filename)
switch ext {
case ".jpg", ".jpeg":
w.Header().Set("Content-Type", "image/jpeg")
case ".png":
w.Header().Set("Content-Type", "image/png")
case ".gif":
w.Header().Set("Content-Type", "image/gif")
case ".webp":
w.Header().Set("Content-Type", "image/webp")
default:
w.Header().Set("Content-Type", "application/octet-stream")
}
w.WriteHeader(http.StatusOK)
w.Write(imageData)
}
func (s *SyncServer) handleSync(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
s.handleGet(w, r)
case http.MethodPut:
s.handlePut(w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func main() {
authToken := os.Getenv("AUTH_TOKEN")
if authToken == "" {
log.Fatal("AUTH_TOKEN environment variable is required")
}
dataFile := os.Getenv("DATA_FILE")
if dataFile == "" {
dataFile = "./data/climb_data.json"
}
imagesDir := os.Getenv("IMAGES_DIR")
if imagesDir == "" {
imagesDir = "./data/images"
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
server := &SyncServer{
authToken: authToken,
dataFile: dataFile,
imagesDir: imagesDir,
}
http.HandleFunc("/sync", server.handleSync)
http.HandleFunc("/health", server.handleHealth)
http.HandleFunc("/images/upload", server.handleImageUpload)
http.HandleFunc("/images/download", server.handleImageDownload)
fmt.Printf("OpenClimb sync server starting on port %s\n", port)
fmt.Printf("Data file: %s\n", dataFile)
fmt.Printf("Images directory: %s\n", imagesDir)
fmt.Printf("Health check available at /health\n")
fmt.Printf("Image upload: POST /images/upload?filename=<name>\n")
fmt.Printf("Image download: GET /images/download?filename=<name>\n")
log.Fatal(http.ListenAndServe(":"+port, nil))
}

361
sync/main_test.go Normal file
View File

@@ -0,0 +1,361 @@
package main
import (
"encoding/json"
"path/filepath"
"strings"
"testing"
"time"
)
func TestSyncServerAuthentication(t *testing.T) {
server := &SyncServer{authToken: "test-token"}
tests := []struct {
name string
token string
expected bool
}{
{"Valid token", "test-token", true},
{"Invalid token", "wrong-token", false},
{"Empty token", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test the authentication logic directly without HTTP
result := strings.Compare(tt.token, server.authToken) == 0
if result != tt.expected {
t.Errorf("authenticate() = %v, want %v", result, tt.expected)
}
})
}
}
func TestLoadDataNonExistentFile(t *testing.T) {
tempDir := t.TempDir()
server := &SyncServer{
dataFile: filepath.Join(tempDir, "nonexistent.json"),
}
backup, err := server.loadData()
if err != nil {
t.Errorf("loadData() error = %v, want nil", err)
}
if backup == nil {
t.Error("Expected backup to be non-nil")
}
if len(backup.Gyms) != 0 || len(backup.Problems) != 0 || len(backup.Sessions) != 0 || len(backup.Attempts) != 0 {
t.Error("Expected empty backup data")
}
if backup.Version != "2.0" || backup.FormatVersion != "2.0" {
t.Error("Expected version and format version to be 2.0")
}
}
func TestSaveAndLoadData(t *testing.T) {
tempDir := t.TempDir()
server := &SyncServer{
dataFile: filepath.Join(tempDir, "test.json"),
imagesDir: filepath.Join(tempDir, "images"),
}
testData := &ClimbDataBackup{
Version: "2.0",
FormatVersion: "2.0",
Gyms: []BackupGym{
{
ID: "gym1",
Name: "Test Gym",
},
},
Problems: []BackupProblem{
{
ID: "problem1",
GymID: "gym1",
ClimbType: "BOULDER",
Difficulty: DifficultyGrade{
System: "V",
Grade: "V5",
NumericValue: 5,
},
IsActive: true,
},
},
Sessions: []BackupClimbSession{},
Attempts: []BackupAttempt{},
}
err := server.saveData(testData)
if err != nil {
t.Errorf("saveData() error = %v", err)
}
loadedData, err := server.loadData()
if err != nil {
t.Errorf("loadData() error = %v", err)
}
if len(loadedData.Gyms) != 1 || loadedData.Gyms[0].ID != "gym1" {
t.Error("Loaded gym data doesn't match saved data")
}
if len(loadedData.Problems) != 1 || loadedData.Problems[0].ID != "problem1" {
t.Error("Loaded problem data doesn't match saved data")
}
}
func TestMinFunction(t *testing.T) {
tests := []struct {
a, b, expected int
}{
{5, 3, 3},
{2, 8, 2},
{4, 4, 4},
{0, 1, 0},
{-1, 2, -1},
}
for _, tt := range tests {
result := min(tt.a, tt.b)
if result != tt.expected {
t.Errorf("min(%d, %d) = %d, want %d", tt.a, tt.b, result, tt.expected)
}
}
}
func TestClimbDataBackupValidation(t *testing.T) {
tests := []struct {
name string
backup ClimbDataBackup
isValid bool
}{
{
name: "Valid backup",
backup: ClimbDataBackup{
Version: "2.0",
FormatVersion: "2.0",
Gyms: []BackupGym{},
Problems: []BackupProblem{},
Sessions: []BackupClimbSession{},
Attempts: []BackupAttempt{},
},
isValid: true,
},
{
name: "Missing version",
backup: ClimbDataBackup{
FormatVersion: "2.0",
Gyms: []BackupGym{},
Problems: []BackupProblem{},
Sessions: []BackupClimbSession{},
Attempts: []BackupAttempt{},
},
isValid: false,
},
{
name: "Missing format version",
backup: ClimbDataBackup{
Version: "2.0",
Gyms: []BackupGym{},
Problems: []BackupProblem{},
Sessions: []BackupClimbSession{},
Attempts: []BackupAttempt{},
},
isValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test basic validation logic
hasVersion := tt.backup.Version != ""
hasFormatVersion := tt.backup.FormatVersion != ""
isValid := hasVersion && hasFormatVersion
if isValid != tt.isValid {
t.Errorf("validation = %v, want %v", isValid, tt.isValid)
}
})
}
}
func TestBackupDataStructures(t *testing.T) {
t.Run("BackupGym", func(t *testing.T) {
gym := BackupGym{
ID: "gym1",
Name: "Test Gym",
SupportedClimbTypes: []string{"BOULDER", "ROPE"},
DifficultySystems: []string{"V", "YDS"},
CustomDifficultyGrades: []string{},
CreatedAt: "2024-01-01T10:00:00Z",
UpdatedAt: "2024-01-01T10:00:00Z",
}
if gym.ID != "gym1" {
t.Errorf("Expected gym ID 'gym1', got %s", gym.ID)
}
if len(gym.SupportedClimbTypes) != 2 {
t.Errorf("Expected 2 climb types, got %d", len(gym.SupportedClimbTypes))
}
})
t.Run("BackupProblem", func(t *testing.T) {
problem := BackupProblem{
ID: "problem1",
GymID: "gym1",
ClimbType: "BOULDER",
Difficulty: DifficultyGrade{
System: "V",
Grade: "V5",
NumericValue: 5,
},
IsActive: true,
CreatedAt: "2024-01-01T10:00:00Z",
UpdatedAt: "2024-01-01T10:00:00Z",
}
if problem.ClimbType != "BOULDER" {
t.Errorf("Expected climb type 'BOULDER', got %s", problem.ClimbType)
}
if problem.Difficulty.Grade != "V5" {
t.Errorf("Expected difficulty 'V5', got %s", problem.Difficulty.Grade)
}
})
}
func TestDifficultyGrade(t *testing.T) {
tests := []struct {
name string
grade DifficultyGrade
expectedGrade string
expectedValue int
}{
{
name: "V-Scale grade",
grade: DifficultyGrade{
System: "V",
Grade: "V5",
NumericValue: 5,
},
expectedGrade: "V5",
expectedValue: 5,
},
{
name: "YDS grade",
grade: DifficultyGrade{
System: "YDS",
Grade: "5.10a",
NumericValue: 10,
},
expectedGrade: "5.10a",
expectedValue: 10,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.grade.Grade != tt.expectedGrade {
t.Errorf("Expected grade %s, got %s", tt.expectedGrade, tt.grade.Grade)
}
if tt.grade.NumericValue != tt.expectedValue {
t.Errorf("Expected numeric value %d, got %d", tt.expectedValue, tt.grade.NumericValue)
}
})
}
}
func TestJSONSerialization(t *testing.T) {
backup := ClimbDataBackup{
Version: "2.0",
FormatVersion: "2.0",
Gyms: []BackupGym{
{
ID: "gym1",
Name: "Test Gym",
},
},
Problems: []BackupProblem{
{
ID: "problem1",
GymID: "gym1",
ClimbType: "BOULDER",
Difficulty: DifficultyGrade{
System: "V",
Grade: "V5",
NumericValue: 5,
},
IsActive: true,
},
},
Sessions: []BackupClimbSession{},
Attempts: []BackupAttempt{},
}
// Test JSON marshaling
jsonData, err := json.Marshal(backup)
if err != nil {
t.Errorf("Failed to marshal JSON: %v", err)
}
// Test JSON unmarshaling
var unmarshaledBackup ClimbDataBackup
err = json.Unmarshal(jsonData, &unmarshaledBackup)
if err != nil {
t.Errorf("Failed to unmarshal JSON: %v", err)
}
if unmarshaledBackup.Version != backup.Version {
t.Errorf("Version mismatch after JSON round-trip")
}
if len(unmarshaledBackup.Gyms) != len(backup.Gyms) {
t.Errorf("Gyms count mismatch after JSON round-trip")
}
}
func TestTimestampHandling(t *testing.T) {
now := time.Now().UTC()
timestamp := now.Format(time.RFC3339)
// Test that timestamp is in correct format
parsedTime, err := time.Parse(time.RFC3339, timestamp)
if err != nil {
t.Errorf("Failed to parse timestamp: %v", err)
}
if parsedTime.Year() != now.Year() {
t.Errorf("Year mismatch in timestamp")
}
}
func TestFilePathHandling(t *testing.T) {
tempDir := t.TempDir()
tests := []struct {
name string
filename string
isValid bool
}{
{"Valid filename", "test.json", true},
{"Valid path", filepath.Join(tempDir, "data.json"), true},
{"Empty filename", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
isEmpty := tt.filename == ""
isValid := !isEmpty
if isValid != tt.isValid {
t.Errorf("File path validation = %v, want %v", isValid, tt.isValid)
}
})
}
}

1
sync/version.md Normal file
View File

@@ -0,0 +1 @@
1.0.0