Compare commits
87 Commits
ANDROID_1.
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
77f7092287
|
|||
|
ed25cf7ecd
|
|||
|
255f85c2df
|
|||
|
a3d47d29c5
|
|||
|
b94b823986
|
|||
|
58d84af29b
|
|||
|
12f9463e8c
|
|||
|
aa3ddfc7cb
|
|||
|
25688b0615
|
|||
|
3874703fcb
|
|||
| aa08892e75 | |||
|
4da10912fc
|
|||
|
94d2f9d951
|
|||
|
6e679236c8
|
|||
|
06fe659478
|
|||
|
390b4bf499
|
|||
|
394789d609
|
|||
|
94566eabf6
|
|||
|
c020287d1f
|
|||
|
98589645e6
|
|||
|
33610a5959
|
|||
|
20058e9ac0
|
|||
|
e4d6e6fb7e
|
|||
|
d97a5f36ea
|
|||
| 1a85dab6ae | |||
|
2d5382ba28
|
|||
|
05c0430b40
|
|||
|
f4f4968431
|
|||
|
d002c703d5
|
|||
|
afb0456692
|
|||
|
74db155d93
|
|||
|
ec63d7c58f
|
|||
|
1c47dd93b0
|
|||
|
ef05727cde
|
|||
|
452fd96372
|
|||
|
d263c6c87e
|
|||
|
aa6ee4ecd4
|
|||
|
c0d9702e54
|
|||
|
0cc576bb12
|
|||
|
abb76e454b
|
|||
|
8154cd24bb
|
|||
| 06bfb02ccc | |||
| f82560bb1d | |||
|
a6508da413
|
|||
|
50b30442e8
|
|||
|
b365b967b2
|
|||
|
cacd178817
|
|||
|
922412c2c2
|
|||
|
acb1b1f532
|
|||
|
c8694eacab
|
|||
|
57855b8332
|
|||
|
6342bfed5c
|
|||
| 869ca0fc0d | |||
| 33562e9d16 | |||
|
a212f3f3b5
|
|||
|
a99196b9ca
|
|||
|
93fb7a41fb
|
|||
|
6d67ae6d81
|
|||
| 071e47f95e | |||
| c6c3e6084b | |||
|
c2f95f2793
|
|||
|
b7a3c98b2c
|
|||
|
fed9bab2ea
|
|||
|
862622b07b
|
|||
|
eba503eb5e
|
|||
|
8c4a78ad50
|
|||
|
3b16475dc6
|
|||
|
105d39689d
|
|||
|
d4023133b7
|
|||
|
602b5f8938
|
|||
| 8529f76c22 | |||
|
879aae0721
|
|||
|
6fc86558b2
|
|||
|
23de8a6fc6
|
|||
|
01d85a4add
|
|||
|
ef1cf3583a
|
|||
|
3c7290f7e7
|
|||
|
5a49b9f0b2
|
|||
| 7601e7bb03 | |||
| 082cb79630 | |||
| 79b87a088d | |||
| 1a8f41ecde | |||
|
175dad8342
|
|||
|
4559d5e2f2
|
|||
|
d57149d29c
|
|||
|
d5cf14d466
|
|||
|
09b4055985
|
18
.editorconfig
Normal file
18
.editorconfig
Normal file
@@ -0,0 +1,18 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.{json,yml,yaml}]
|
||||
indent_size = 2
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
79
.gitattributes
vendored
Normal file
79
.gitattributes
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
|
||||
# Source code files
|
||||
*.swift text eol=lf
|
||||
*.kt text eol=lf
|
||||
*.kts text eol=lf
|
||||
*.java text eol=lf
|
||||
*.go text eol=lf
|
||||
*.py text eol=lf
|
||||
*.ts text eol=lf
|
||||
*.tsx text eol=lf
|
||||
*.js text eol=lf
|
||||
*.jsx text eol=lf
|
||||
*.mjs text eol=lf
|
||||
*.cjs text eol=lf
|
||||
|
||||
# Configuration files
|
||||
*.json text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.yaml text eol=lf
|
||||
*.toml text eol=lf
|
||||
*.xml text eol=lf
|
||||
*.plist text eol=lf
|
||||
*.properties text eol=lf
|
||||
*.gradle text eol=lf
|
||||
*.md text eol=lf
|
||||
|
||||
# Shell scripts
|
||||
*.sh text eol=lf
|
||||
*.bash text eol=lf
|
||||
*.zsh text eol=lf
|
||||
|
||||
# Windows batch files
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
|
||||
# Binary files
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.webp binary
|
||||
*.pdf binary
|
||||
*.zip binary
|
||||
*.tar binary
|
||||
*.gz binary
|
||||
*.jar binary
|
||||
*.aar binary
|
||||
*.apk binary
|
||||
*.ipa binary
|
||||
*.xcassets binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.eot binary
|
||||
|
||||
# Xcode files
|
||||
*.pbxproj merge=union
|
||||
*.xcworkspacedata text eol=lf
|
||||
*.xcscheme text eol=lf
|
||||
|
||||
# Gradle wrapper
|
||||
gradlew text eol=lf
|
||||
gradlew.bat text eol=crlf
|
||||
gradle-wrapper.jar binary
|
||||
|
||||
# Lock files
|
||||
*.lock text -diff
|
||||
package-lock.json text -diff
|
||||
pnpm-lock.yaml text -diff
|
||||
|
||||
# Documentation
|
||||
LICENSE text eol=lf
|
||||
README.md text eol=lf
|
||||
|
||||
*.pxd linguist-vendored
|
||||
38
.github/workflows/deploy_docs.yml
vendored
Normal file
38
.github/workflows/deploy_docs.yml
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
name: Ascently - Docs Deploy
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["docs/**"]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ["docs/**"]
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ secrets.REPO_HOST }}
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.DEPLOY_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./docs
|
||||
platforms: linux/amd64
|
||||
push: true
|
||||
tags: |
|
||||
${{ secrets.REPO_HOST }}/${{ github.repository_owner }}/ascently-docs:${{ github.sha }}
|
||||
${{ secrets.REPO_HOST }}/${{ github.repository_owner }}/ascently-docs:latest
|
||||
@@ -1,4 +1,4 @@
|
||||
name: OpenClimb Docker Deploy
|
||||
name: Ascently - Sync Deploy
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
@@ -27,12 +27,12 @@ jobs:
|
||||
password: ${{ secrets.DEPLOY_TOKEN }}
|
||||
|
||||
- name: Build and push sync-server
|
||||
uses: docker/build-push-action@v4
|
||||
uses: docker/build-push-action@v6
|
||||
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
|
||||
${{ secrets.REPO_HOST }}/${{ github.repository_owner }}/ascently-sync:${{ github.sha }}
|
||||
${{ secrets.REPO_HOST }}/${{ github.repository_owner }}/ascently-sync:latest
|
||||
46
.gitignore
vendored
46
.gitignore
vendored
@@ -9,6 +9,11 @@ local.properties
|
||||
# Log/OS Files
|
||||
*.log
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
Thumbs.db
|
||||
|
||||
# Android Studio generated files and folders
|
||||
captures/
|
||||
@@ -34,3 +39,44 @@ google-services.json
|
||||
|
||||
# Android Profiling
|
||||
*.hprof
|
||||
|
||||
# iOS/Xcode
|
||||
ios/build/
|
||||
ios/DerivedData/
|
||||
ios/*.xcuserstate
|
||||
ios/**/xcuserdata/
|
||||
ios/**/*.xcuserstate
|
||||
*.xccheckout
|
||||
*.moved-aside
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
*.hmap
|
||||
*.ipa
|
||||
*.dSYM.zip
|
||||
*.dSYM
|
||||
timeline.xctimeline
|
||||
playground.xcworkspace
|
||||
|
||||
# CocoaPods
|
||||
ios/Pods/
|
||||
ios/Podfile.lock
|
||||
|
||||
# Swift Package Manager
|
||||
ios/.swiftpm/
|
||||
ios/Package.resolved
|
||||
.build/
|
||||
|
||||
# fastlane
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots/**/*.png
|
||||
fastlane/test_output
|
||||
|
||||
# Code Injection
|
||||
iOSInjectionProject/
|
||||
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
Ascently is a FOSS app meant to help climbers track their sessions, routes/problems, and overall progress.
|
||||
Copyright (C) 2025 Atridad Lahiji
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
Ascently Copyright (C) 2025 Atridad Lahiji
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
90
Makefile
Normal file
90
Makefile
Normal file
@@ -0,0 +1,90 @@
|
||||
# Ascently Makefile
|
||||
|
||||
.PHONY: help android-lint android-format android-build android-test \
|
||||
ios-lint ios-format ios-build ios-test clean
|
||||
|
||||
# Default target
|
||||
help:
|
||||
@echo "Ascently Dev Commands"
|
||||
@echo "=============================="
|
||||
@echo ""
|
||||
@echo "Android:"
|
||||
@echo " make android-lint: Run Detekt static analysis"
|
||||
@echo " make android-format: Check code formatting with Spotless"
|
||||
@echo " make android-format-fix: Auto-fix code formatting"
|
||||
@echo " make android-build: Build debug APK"
|
||||
@echo " make android-release: Build release APK"
|
||||
@echo " make android-test: Run unit tests"
|
||||
@echo ""
|
||||
@echo "iOS:"
|
||||
@echo " make ios-lint: Run SwiftLint"
|
||||
@echo " make ios-lint-fix: Run SwiftLint with auto-fix"
|
||||
@echo " make ios-format: Run SwiftFormat (dry-run)"
|
||||
@echo " make ios-format-fix: Run SwiftFormat with auto-fix"
|
||||
@echo " make ios-build: Build iOS app"
|
||||
@echo ""
|
||||
@echo "General:"
|
||||
@echo " make lint: Run linters for both platforms"
|
||||
@echo " make format: Check formatting for both platforms"
|
||||
@echo " make clean: Clean build artifacts"
|
||||
|
||||
# Android commands
|
||||
android-lint:
|
||||
cd android && ./gradlew detekt
|
||||
|
||||
android-format:
|
||||
cd android && ./gradlew spotlessCheck
|
||||
|
||||
android-format-fix:
|
||||
cd android && ./gradlew spotlessApply
|
||||
|
||||
android-build:
|
||||
cd android && ./gradlew assembleDebug
|
||||
|
||||
android-release:
|
||||
cd android && ./gradlew assembleRelease
|
||||
|
||||
android-test:
|
||||
cd android && ./gradlew test
|
||||
|
||||
# iOS commands (requires SwiftLint and SwiftFormat!!!)
|
||||
ios-lint:
|
||||
@if command -v swiftlint >/dev/null 2>&1; then \
|
||||
cd ios && swiftlint; \
|
||||
else \
|
||||
echo "SwiftLint not installed. Install with: brew install swiftlint"; \
|
||||
fi
|
||||
|
||||
ios-lint-fix:
|
||||
@if command -v swiftlint >/dev/null 2>&1; then \
|
||||
cd ios && swiftlint --fix; \
|
||||
else \
|
||||
echo "SwiftLint not installed. Install with: brew install swiftlint"; \
|
||||
fi
|
||||
|
||||
ios-format:
|
||||
@if command -v swiftformat >/dev/null 2>&1; then \
|
||||
cd ios && swiftformat . --lint; \
|
||||
else \
|
||||
echo "SwiftFormat not installed. Install with: brew install swiftformat"; \
|
||||
fi
|
||||
|
||||
ios-format-fix:
|
||||
@if command -v swiftformat >/dev/null 2>&1; then \
|
||||
cd ios && swiftformat .; \
|
||||
else \
|
||||
echo "SwiftFormat not installed. Install with: brew install swiftformat"; \
|
||||
fi
|
||||
|
||||
ios-build:
|
||||
cd ios && xcodebuild -project Ascently.xcodeproj -scheme Ascently -configuration Debug build
|
||||
|
||||
# Combined commands
|
||||
lint: android-lint ios-lint
|
||||
|
||||
format: android-format ios-format
|
||||
|
||||
# Clean
|
||||
clean:
|
||||
cd android && ./gradlew clean
|
||||
rm -rf ios/build ios/DerivedData
|
||||
21
PRIVACY.md
21
PRIVACY.md
@@ -1,21 +0,0 @@
|
||||
# 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
|
||||
40
README.md
40
README.md
@@ -1,42 +1,14 @@
|
||||
# OpenClimb
|
||||
# Ascently
|
||||
|
||||
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.
|
||||
<img src="https://git.atri.dad/atridad/Ascently/raw/branch/main/docs/src/assets/logo.png" alt="Ascently Logo" width="250" height="250">
|
||||
|
||||
## Download
|
||||
_Formerly OpenClimb_
|
||||
|
||||
For Android do one of the following:
|
||||
Ascently is an **offline-first FOSS** app designed to help climbers track their sessions, routes/problems, and overall progress. There is an optional self-hosted sync server and integrations with Apple Health and Health Connect. There are no analytics or tracking baked into any part of this project. I am committed to maintaining a transparent and open-source solution for climbers, ensuring that you have full control over your data and privacy.
|
||||
|
||||
1. Download the latest APK from the Releases page
|
||||
2. [<img src="https://github.com/ImranR98/Obtainium/blob/main/assets/graphics/badge_obtainium.png?raw=true" alt="Obtainium" height="41">](https://apps.obtainium.imranr.dev/redirect?r=obtainium://app/%7B%22id%22%3A%22com.atridad.openclimb%22%2C%22url%22%3A%22https%3A%2F%2Fgit.atri.dad%2Fatridad%2FOpenClimb%2Freleases%22%2C%22author%22%3A%22git.atri.dad%22%2C%22name%22%3A%22OpenClimb%22%2C%22preferredApkIndex%22%3A0%2C%22additionalSettings%22%3A%22%7B%5C%22intermediateLink%5C%22%3A%5B%5D%2C%5C%22customLinkFilterRegex%5C%22%3A%5C%22%5C%22%2C%5C%22filterByLinkText%5C%22%3Afalse%2C%5C%22skipSort%5C%22%3Afalse%2C%5C%22reverseSort%5C%22%3Afalse%2C%5C%22sortByLastLinkSegment%5C%22%3Afalse%2C%5C%22versionExtractWholePage%5C%22%3Afalse%2C%5C%22requestHeader%5C%22%3A%5B%7B%5C%22requestHeader%5C%22%3A%5C%22User-Agent%3A%20Mozilla%2F5.0%20(Linux%3B%20Android%2010%3B%20K)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F114.0.0.0%20Mobile%20Safari%2F537.36%5C%22%7D%5D%2C%5C%22defaultPseudoVersioningMethod%5C%22%3A%5C%22partialAPKHash%5C%22%2C%5C%22trackOnly%5C%22%3Afalse%2C%5C%22versionExtractionRegEx%5C%22%3A%5C%22%5C%22%2C%5C%22matchGroupToUse%5C%22%3A%5C%22%5C%22%2C%5C%22versionDetection%5C%22%3Afalse%2C%5C%22useVersionCodeAsOSVersion%5C%22%3Afalse%2C%5C%22apkFilterRegEx%5C%22%3A%5C%22%5C%22%2C%5C%22invertAPKFilter%5C%22%3Afalse%2C%5C%22autoApkFilterByArch%5C%22%3Atrue%2C%5C%22appName%5C%22%3A%5C%22OpenClimb%5C%22%2C%5C%22appAuthor%5C%22%3A%5C%22%5C%22%2C%5C%22shizukuPretendToBeGooglePlay%5C%22%3Afalse%2C%5C%22allowInsecure%5C%22%3Afalse%2C%5C%22exemptFromBackgroundUpdates%5C%22%3Afalse%2C%5C%22skipUpdateNotifications%5C%22%3Afalse%2C%5C%22about%5C%22%3A%5C%22%5C%22%2C%5C%22refreshBeforeDownload%5C%22%3Afalse%7D%22%2C%22overrideSource%22%3Anull%7D)
|
||||
## Documentation
|
||||
|
||||
For iOS:
|
||||
|
||||
Download from the AppStore [here](https://apps.apple.com/ca/app/openclimb/id6752592783)!
|
||||
For development builds, sign up for the TestFlight [here](https://testflight.apple.com/join/88RtxV4J)!
|
||||
|
||||
## 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.
|
||||
Documentation can be found at [https://ascently.atri.dad](https://ascently.atri.dad)!
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
31
android/.editorconfig
Normal file
31
android/.editorconfig
Normal file
@@ -0,0 +1,31 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.{kt,kts}]
|
||||
indent_size = 4
|
||||
max_line_length = 220
|
||||
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
|
||||
ktlint_standard_no-wildcard-imports = disabled
|
||||
ktlint_standard_package-name = disabled
|
||||
|
||||
[*.{xml,gradle}]
|
||||
indent_size = 4
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.properties]
|
||||
indent_size = 2
|
||||
|
||||
[*.toml]
|
||||
indent_size = 4
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
@@ -1,10 +1,9 @@
|
||||
# OpenClimb for Android
|
||||
# Ascently for Android
|
||||
|
||||
This is the native Android app for OpenClimb, built with Kotlin and Jetpack Compose.
|
||||
This is the native Android app for Ascently, built with Kotlin and Jetpack Compose.
|
||||
|
||||
## Project Structure
|
||||
|
||||
This is a standard Android Gradle project. The main code lives in `app/src/main/java/com/atridad/openclimb/`.
|
||||
This is a standard Android Gradle project. The main code lives in `app/src/main/java/com/atridad/ascently/`.
|
||||
|
||||
- `data/`: Handles all the app's data.
|
||||
- `database/`: Room database setup (DAOs, entities).
|
||||
@@ -18,5 +17,3 @@ This is a standard Android Gradle project. The main code lives in `app/src/main/
|
||||
- `navigation/`: Navigation graph and routes using Jetpack Navigation.
|
||||
- `service/`: Background service for tracking climbing sessions.
|
||||
- `utils/`: Helpers for things like date formatting and image handling.
|
||||
|
||||
The app is built to be offline-first. All data is stored locally on your device and works without an internet connection.
|
||||
@@ -6,18 +6,20 @@ plugins {
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
alias(libs.plugins.ksp)
|
||||
alias(libs.plugins.detekt)
|
||||
alias(libs.plugins.spotless)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.atridad.openclimb"
|
||||
namespace = "com.atridad.ascently"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.atridad.openclimb"
|
||||
applicationId = "com.atridad.ascently"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 39
|
||||
versionName = "1.9.2"
|
||||
versionCode = 52
|
||||
versionName = "2.5.2"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
@@ -26,8 +28,8 @@ android {
|
||||
release {
|
||||
isMinifyEnabled = true
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -38,7 +40,10 @@ android {
|
||||
|
||||
java { toolchain { languageVersion.set(JavaLanguageVersion.of(17)) } }
|
||||
|
||||
buildFeatures { compose = true }
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } }
|
||||
@@ -80,7 +85,7 @@ dependencies {
|
||||
implementation(libs.coil.compose)
|
||||
|
||||
// Health Connect
|
||||
implementation("androidx.health.connect:connect-client:1.1.0-alpha07")
|
||||
implementation(libs.health.connect)
|
||||
|
||||
// Testing
|
||||
testImplementation(libs.junit)
|
||||
@@ -96,6 +101,51 @@ 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)
|
||||
}
|
||||
|
||||
// Detekt configuration
|
||||
detekt {
|
||||
config.setFrom(files("$rootDir/detekt.yml"))
|
||||
buildUponDefaultConfig = true
|
||||
allRules = false
|
||||
parallel = true
|
||||
}
|
||||
|
||||
// Spotless configuration for code formatting
|
||||
spotless {
|
||||
kotlin {
|
||||
target("**/*.kt")
|
||||
targetExclude("**/build/**/*.kt")
|
||||
ktlint("1.2.1")
|
||||
.editorConfigOverride(
|
||||
mapOf(
|
||||
"ktlint_standard_no-wildcard-imports" to "disabled",
|
||||
"ktlint_standard_package-name" to "disabled",
|
||||
"ktlint_standard_function-naming" to "disabled",
|
||||
"ktlint_standard_filename" to "disabled",
|
||||
"ktlint_standard_value-parameter-comment" to "disabled",
|
||||
"ktlint_standard_comment-wrapping" to "disabled",
|
||||
"ktlint_standard_multiline-expression-wrapping" to "disabled",
|
||||
"ktlint_standard_string-template-indent" to "disabled",
|
||||
"ktlint_standard_property-naming" to "disabled",
|
||||
"ktlint_standard_class-naming" to "disabled",
|
||||
"ktlint_standard_backing-property-naming" to "disabled",
|
||||
"ktlint_standard_function-signature" to "disabled",
|
||||
"ktlint_standard_parameter-list-wrapping" to "disabled",
|
||||
"ktlint_standard_max-line-length" to "disabled",
|
||||
"max_line_length" to "off",
|
||||
),
|
||||
)
|
||||
}
|
||||
kotlinGradle {
|
||||
target("**/*.kts")
|
||||
targetExclude("**/build/**/*.kts")
|
||||
ktlint("1.2.1")
|
||||
.editorConfigOverride(
|
||||
mapOf(
|
||||
"ktlint_standard_no-wildcard-imports" to "disabled",
|
||||
"max_line_length" to "off",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ plugins {
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.atridad.openclimb"
|
||||
namespace = "com.atridad.ascently"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.atridad.openclimb"
|
||||
applicationId = "com.atridad.ascently"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 27
|
||||
|
||||
62
android/app/proguard-rules.pro
vendored
62
android/app/proguard-rules.pro
vendored
@@ -5,17 +5,61 @@
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# Preserve line number information for debugging stack traces
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# Hide the original source file name
|
||||
-renamesourcefileattribute SourceFile
|
||||
|
||||
# Keep generic signatures for Kotlin
|
||||
-keepattributes Signature
|
||||
|
||||
# Keep annotations
|
||||
-keepattributes *Annotation*
|
||||
|
||||
# Room Database
|
||||
-keep class * extends androidx.room.RoomDatabase
|
||||
-keep @androidx.room.Entity class *
|
||||
-keepclassmembers class * {
|
||||
@androidx.room.* <fields>;
|
||||
@androidx.room.* <methods>;
|
||||
}
|
||||
|
||||
# Kotlinx Serialization
|
||||
-keepattributes *Annotation*, InnerClasses
|
||||
-dontnote kotlinx.serialization.AnnotationsKt
|
||||
|
||||
-keepclassmembers class kotlinx.serialization.json.** {
|
||||
*** Companion;
|
||||
}
|
||||
-keepclasseswithmembers class kotlinx.serialization.json.** {
|
||||
kotlinx.serialization.KSerializer serializer(...);
|
||||
}
|
||||
|
||||
-keep,includedescriptorclasses class com.atridad.ascently.**$$serializer { *; }
|
||||
-keepclassmembers class com.atridad.ascently.** {
|
||||
*** Companion;
|
||||
}
|
||||
-keepclasseswithmembers class com.atridad.ascently.** {
|
||||
kotlinx.serialization.KSerializer serializer(...);
|
||||
}
|
||||
|
||||
# Keep data classes used for serialization
|
||||
-keep class com.atridad.ascently.data.model.** { *; }
|
||||
-keep class com.atridad.ascently.data.format.** { *; }
|
||||
|
||||
# Coroutines
|
||||
-keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {}
|
||||
-keepnames class kotlinx.coroutines.CoroutineExceptionHandler {}
|
||||
-keepclassmembers class kotlinx.coroutines.** {
|
||||
volatile <fields>;
|
||||
}
|
||||
|
||||
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
#}
|
||||
@@ -27,6 +27,7 @@
|
||||
|
||||
<!-- Permissions for notifications and foreground service -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
|
||||
@@ -50,13 +51,13 @@
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.OpenClimb"
|
||||
android:theme="@style/Theme.Ascently"
|
||||
tools:targetApi="31">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.OpenClimb.Splash">
|
||||
android:theme="@style/Theme.Ascently.Splash">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
|
||||
BIN
android/app/src/main/ic_launcher-playstore.png
Normal file
BIN
android/app/src/main/ic_launcher-playstore.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb
|
||||
package com.atridad.ascently
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
@@ -9,8 +9,9 @@ import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.atridad.openclimb.ui.OpenClimbApp
|
||||
import com.atridad.openclimb.ui.theme.OpenClimbTheme
|
||||
import com.atridad.ascently.ui.AscentlyApp
|
||||
import com.atridad.ascently.ui.theme.AscentlyTheme
|
||||
import com.atridad.ascently.utils.MigrationManager
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private var shortcutAction by mutableStateOf<String?>(null)
|
||||
@@ -23,19 +24,22 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setTheme(R.style.Theme_OpenClimb)
|
||||
setTheme(R.style.Theme_Ascently)
|
||||
enableEdgeToEdge()
|
||||
|
||||
// Perform migration from OpenClimb to Ascently if needed
|
||||
MigrationManager(this).migrateIfNeeded()
|
||||
|
||||
shortcutAction = intent?.action
|
||||
lastUsedGymId = intent?.getStringExtra("LAST_USED_GYM_ID")
|
||||
|
||||
setContent {
|
||||
OpenClimbTheme {
|
||||
AscentlyTheme {
|
||||
Surface(modifier = Modifier.fillMaxSize()) {
|
||||
OpenClimbApp(
|
||||
shortcutAction = shortcutAction,
|
||||
lastUsedGymId = lastUsedGymId,
|
||||
onShortcutActionProcessed = { clearShortcutAction() }
|
||||
AscentlyApp(
|
||||
shortcutAction = shortcutAction,
|
||||
lastUsedGymId = lastUsedGymId,
|
||||
onShortcutActionProcessed = { clearShortcutAction() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,80 +1,79 @@
|
||||
package com.atridad.openclimb.data.database
|
||||
package com.atridad.ascently.data.database
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
import com.atridad.openclimb.data.model.*
|
||||
import com.atridad.ascently.data.model.*
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
class Converters {
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun fromClimbTypeList(value: List<ClimbType>): String {
|
||||
return Json.encodeToString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun toClimbTypeList(value: String): List<ClimbType> {
|
||||
return Json.decodeFromString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun fromDifficultySystemList(value: List<DifficultySystem>): String {
|
||||
return Json.encodeToString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun toDifficultySystemList(value: String): List<DifficultySystem> {
|
||||
return Json.decodeFromString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun fromStringList(value: List<String>): String {
|
||||
return Json.encodeToString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun toStringList(value: String): List<String> {
|
||||
return Json.decodeFromString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun fromDifficultyGrade(value: DifficultyGrade): String {
|
||||
return Json.encodeToString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun toDifficultyGrade(value: String): DifficultyGrade {
|
||||
return Json.decodeFromString(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun fromClimbType(value: ClimbType): String {
|
||||
return value.name
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun toClimbType(value: String): ClimbType {
|
||||
return ClimbType.valueOf(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun fromAttemptResult(value: AttemptResult): String {
|
||||
return value.name
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun toAttemptResult(value: String): AttemptResult {
|
||||
return AttemptResult.valueOf(value)
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun fromSessionStatus(value: SessionStatus): String {
|
||||
return value.name
|
||||
}
|
||||
|
||||
|
||||
@TypeConverter
|
||||
fun toSessionStatus(value: String): SessionStatus {
|
||||
return SessionStatus.valueOf(value)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.atridad.ascently.data.database
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.atridad.ascently.data.database.dao.*
|
||||
import com.atridad.ascently.data.model.*
|
||||
|
||||
@Database(
|
||||
entities = [Gym::class, Problem::class, ClimbSession::class, Attempt::class],
|
||||
version = 6,
|
||||
exportSchema = false,
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class AscentlyDatabase : RoomDatabase() {
|
||||
|
||||
abstract fun gymDao(): GymDao
|
||||
abstract fun problemDao(): ProblemDao
|
||||
abstract fun climbSessionDao(): ClimbSessionDao
|
||||
abstract fun attemptDao(): AttemptDao
|
||||
|
||||
companion object {
|
||||
@Volatile private var INSTANCE: AscentlyDatabase? = null
|
||||
|
||||
val MIGRATION_4_5 =
|
||||
object : Migration(4, 5) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
val cursor = db.query("PRAGMA table_info(climb_sessions)")
|
||||
val existingColumns = mutableSetOf<String>()
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
val columnName = cursor.getString(cursor.getColumnIndexOrThrow("name"))
|
||||
existingColumns.add(columnName)
|
||||
}
|
||||
cursor.close()
|
||||
|
||||
if (!existingColumns.contains("startTime")) {
|
||||
db.execSQL("ALTER TABLE climb_sessions ADD COLUMN startTime TEXT")
|
||||
}
|
||||
if (!existingColumns.contains("endTime")) {
|
||||
db.execSQL("ALTER TABLE climb_sessions ADD COLUMN endTime TEXT")
|
||||
}
|
||||
if (!existingColumns.contains("status")) {
|
||||
db.execSQL(
|
||||
"ALTER TABLE climb_sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'COMPLETED'",
|
||||
)
|
||||
}
|
||||
|
||||
db.execSQL(
|
||||
"UPDATE climb_sessions SET startTime = createdAt WHERE startTime IS NULL",
|
||||
)
|
||||
db.execSQL(
|
||||
"UPDATE climb_sessions SET status = 'COMPLETED' WHERE status IS NULL OR status = ''",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val MIGRATION_5_6 =
|
||||
object : Migration(5, 6) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
// Add updatedAt column to attempts table
|
||||
val cursor = db.query("PRAGMA table_info(attempts)")
|
||||
val existingColumns = mutableSetOf<String>()
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
val columnName = cursor.getString(cursor.getColumnIndexOrThrow("name"))
|
||||
existingColumns.add(columnName)
|
||||
}
|
||||
cursor.close()
|
||||
|
||||
if (!existingColumns.contains("updatedAt")) {
|
||||
db.execSQL(
|
||||
"ALTER TABLE attempts ADD COLUMN updatedAt TEXT NOT NULL DEFAULT ''",
|
||||
)
|
||||
// Set updatedAt to createdAt for existing records
|
||||
db.execSQL(
|
||||
"UPDATE attempts SET updatedAt = createdAt WHERE updatedAt = ''",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getDatabase(context: Context): AscentlyDatabase {
|
||||
return INSTANCE
|
||||
?: synchronized(this) {
|
||||
val instance =
|
||||
Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
AscentlyDatabase::class.java,
|
||||
"ascently_database",
|
||||
)
|
||||
.addMigrations(MIGRATION_4_5, MIGRATION_5_6)
|
||||
.enableMultiInstanceInvalidation()
|
||||
.fallbackToDestructiveMigration(false)
|
||||
.build()
|
||||
INSTANCE = instance
|
||||
instance
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +1,76 @@
|
||||
package com.atridad.openclimb.data.database.dao
|
||||
package com.atridad.ascently.data.database.dao
|
||||
|
||||
import androidx.room.*
|
||||
import com.atridad.openclimb.data.model.Attempt
|
||||
import com.atridad.openclimb.data.model.AttemptResult
|
||||
import com.atridad.ascently.data.model.Attempt
|
||||
import com.atridad.ascently.data.model.AttemptResult
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface AttemptDao {
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts ORDER BY timestamp DESC")
|
||||
fun getAllAttempts(): Flow<List<Attempt>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE id = :id")
|
||||
suspend fun getAttemptById(id: String): Attempt?
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE sessionId = :sessionId ORDER BY timestamp ASC")
|
||||
fun getAttemptsBySession(sessionId: String): Flow<List<Attempt>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE problemId = :problemId ORDER BY timestamp DESC")
|
||||
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE sessionId = :sessionId AND problemId = :problemId ORDER BY timestamp ASC")
|
||||
fun getAttemptsBySessionAndProblem(sessionId: String, problemId: String): Flow<List<Attempt>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE result = :result ORDER BY timestamp DESC")
|
||||
fun getAttemptsByResult(result: AttemptResult): Flow<List<Attempt>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE timestamp BETWEEN :startDate AND :endDate ORDER BY timestamp DESC")
|
||||
fun getAttemptsInDateRange(startDate: String, endDate: String): Flow<List<Attempt>>
|
||||
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAttempt(attempt: Attempt)
|
||||
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAttempts(attempts: List<Attempt>)
|
||||
|
||||
|
||||
@Update
|
||||
suspend fun updateAttempt(attempt: Attempt)
|
||||
|
||||
|
||||
@Delete
|
||||
suspend fun deleteAttempt(attempt: Attempt)
|
||||
|
||||
|
||||
@Query("DELETE FROM attempts WHERE id = :id")
|
||||
suspend fun deleteAttemptById(id: String)
|
||||
|
||||
|
||||
@Query("DELETE FROM attempts WHERE sessionId = :sessionId")
|
||||
suspend fun deleteAttemptsBySession(sessionId: String)
|
||||
|
||||
|
||||
@Query("DELETE FROM attempts WHERE problemId = :problemId")
|
||||
suspend fun deleteAttemptsByProblem(problemId: String)
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM attempts")
|
||||
suspend fun getAttemptsCount(): Int
|
||||
|
||||
|
||||
@Query("DELETE FROM attempts")
|
||||
suspend fun deleteAllAttempts()
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM attempts WHERE sessionId = :sessionId")
|
||||
suspend fun getAttemptsCountBySession(sessionId: String): Int
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM attempts WHERE problemId = :problemId")
|
||||
suspend fun getAttemptsCountByProblem(problemId: String): Int
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM attempts WHERE result = :result")
|
||||
suspend fun getAttemptsCountByResult(result: AttemptResult): Int
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM attempts WHERE problemId = :problemId AND result IN ('SUCCESS', 'FLASH', 'REDPOINT', 'ONSIGHT')")
|
||||
suspend fun getSuccessfulAttemptsCountByProblem(problemId: String): Int
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE problemId = :problemId AND result IN ('SUCCESS', 'FLASH', 'REDPOINT', 'ONSIGHT') ORDER BY timestamp ASC LIMIT 1")
|
||||
suspend fun getFirstSuccessfulAttempt(problemId: String): Attempt?
|
||||
|
||||
|
||||
@Query("SELECT * FROM attempts WHERE problemId = :problemId ORDER BY timestamp DESC LIMIT 1")
|
||||
suspend fun getLatestAttemptForProblem(problemId: String): Attempt?
|
||||
}
|
||||
@@ -1,67 +1,67 @@
|
||||
package com.atridad.openclimb.data.database.dao
|
||||
package com.atridad.ascently.data.database.dao
|
||||
|
||||
import androidx.room.*
|
||||
import com.atridad.openclimb.data.model.ClimbSession
|
||||
import com.atridad.openclimb.data.model.SessionStatus
|
||||
import com.atridad.ascently.data.model.ClimbSession
|
||||
import com.atridad.ascently.data.model.SessionStatus
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface ClimbSessionDao {
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions ORDER BY date DESC")
|
||||
fun getAllSessions(): Flow<List<ClimbSession>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions WHERE id = :id")
|
||||
suspend fun getSessionById(id: String): ClimbSession?
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions WHERE gymId = :gymId ORDER BY date DESC")
|
||||
fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions WHERE date = :date ORDER BY createdAt DESC")
|
||||
fun getSessionsByDate(date: String): Flow<List<ClimbSession>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions WHERE date BETWEEN :startDate AND :endDate ORDER BY date DESC")
|
||||
fun getSessionsInDateRange(startDate: String, endDate: String): Flow<List<ClimbSession>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions ORDER BY date DESC LIMIT :limit")
|
||||
fun getRecentSessions(limit: Int = 10): Flow<List<ClimbSession>>
|
||||
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertSession(session: ClimbSession)
|
||||
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertSessions(sessions: List<ClimbSession>)
|
||||
|
||||
|
||||
@Update
|
||||
suspend fun updateSession(session: ClimbSession)
|
||||
|
||||
|
||||
@Delete
|
||||
suspend fun deleteSession(session: ClimbSession)
|
||||
|
||||
|
||||
@Query("DELETE FROM climb_sessions WHERE id = :id")
|
||||
suspend fun deleteSessionById(id: String)
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM climb_sessions")
|
||||
suspend fun getSessionsCount(): Int
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM climb_sessions WHERE gymId = :gymId")
|
||||
suspend fun getSessionsCountByGym(gymId: String): Int
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM climb_sessions WHERE date BETWEEN :startDate AND :endDate")
|
||||
suspend fun getSessionsCountInDateRange(startDate: String, endDate: String): Int
|
||||
|
||||
|
||||
@Query("SELECT DISTINCT date FROM climb_sessions ORDER BY date DESC")
|
||||
suspend fun getUniqueDates(): List<String>
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions WHERE status = :status ORDER BY date DESC")
|
||||
fun getSessionsByStatus(status: SessionStatus): Flow<List<ClimbSession>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions WHERE status = 'ACTIVE' ORDER BY date DESC LIMIT 1")
|
||||
suspend fun getActiveSession(): ClimbSession?
|
||||
|
||||
|
||||
@Query("DELETE FROM climb_sessions")
|
||||
suspend fun deleteAllSessions()
|
||||
|
||||
|
||||
@Query("SELECT * FROM climb_sessions WHERE status = 'ACTIVE' ORDER BY date DESC LIMIT 1")
|
||||
fun getActiveSessionFlow(): Flow<ClimbSession?>
|
||||
}
|
||||
@@ -1,43 +1,43 @@
|
||||
package com.atridad.openclimb.data.database.dao
|
||||
package com.atridad.ascently.data.database.dao
|
||||
|
||||
import androidx.room.*
|
||||
import com.atridad.openclimb.data.model.ClimbType
|
||||
import com.atridad.openclimb.data.model.Gym
|
||||
import com.atridad.ascently.data.model.ClimbType
|
||||
import com.atridad.ascently.data.model.Gym
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface GymDao {
|
||||
|
||||
|
||||
@Query("SELECT * FROM gyms ORDER BY name ASC")
|
||||
fun getAllGyms(): Flow<List<Gym>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM gyms WHERE id = :id")
|
||||
suspend fun getGymById(id: String): Gym?
|
||||
|
||||
|
||||
@Query("SELECT * FROM gyms WHERE :climbType IN (supportedClimbTypes)")
|
||||
fun getGymsByClimbType(climbType: ClimbType): Flow<List<Gym>>
|
||||
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertGym(gym: Gym)
|
||||
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertGyms(gyms: List<Gym>)
|
||||
|
||||
|
||||
@Update
|
||||
suspend fun updateGym(gym: Gym)
|
||||
|
||||
|
||||
@Delete
|
||||
suspend fun deleteGym(gym: Gym)
|
||||
|
||||
|
||||
@Query("DELETE FROM gyms WHERE id = :id")
|
||||
suspend fun deleteGymById(id: String)
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM gyms")
|
||||
suspend fun getGymsCount(): Int
|
||||
|
||||
|
||||
@Query("SELECT * FROM gyms WHERE name LIKE '%' || :searchQuery || '%' OR location LIKE '%' || :searchQuery || '%'")
|
||||
fun searchGyms(searchQuery: String): Flow<List<Gym>>
|
||||
|
||||
|
||||
@Query("DELETE FROM gyms")
|
||||
suspend fun deleteAllGyms()
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.atridad.openclimb.data.database.dao
|
||||
package com.atridad.ascently.data.database.dao
|
||||
|
||||
import androidx.room.*
|
||||
import com.atridad.openclimb.data.model.ClimbType
|
||||
import com.atridad.openclimb.data.model.Problem
|
||||
import com.atridad.ascently.data.model.ClimbType
|
||||
import com.atridad.ascently.data.model.Problem
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
@@ -11,7 +11,8 @@ interface ProblemDao {
|
||||
@Query("SELECT * FROM problems ORDER BY updatedAt DESC")
|
||||
fun getAllProblems(): Flow<List<Problem>>
|
||||
|
||||
@Query("SELECT * FROM problems WHERE id = :id") suspend fun getProblemById(id: String): Problem?
|
||||
@Query("SELECT * FROM problems WHERE id = :id")
|
||||
suspend fun getProblemById(id: String): Problem?
|
||||
|
||||
@Query("SELECT * FROM problems WHERE gymId = :gymId ORDER BY updatedAt DESC")
|
||||
fun getProblemsByGym(gymId: String): Flow<List<Problem>>
|
||||
@@ -20,7 +21,7 @@ interface ProblemDao {
|
||||
fun getProblemsByClimbType(climbType: ClimbType): Flow<List<Problem>>
|
||||
|
||||
@Query(
|
||||
"SELECT * FROM problems WHERE gymId = :gymId AND climbType = :climbType ORDER BY updatedAt DESC"
|
||||
"SELECT * FROM problems WHERE gymId = :gymId AND climbType = :climbType ORDER BY updatedAt DESC",
|
||||
)
|
||||
fun getProblemsByGymAndType(gymId: String, climbType: ClimbType): Flow<List<Problem>>
|
||||
|
||||
@@ -30,7 +31,8 @@ interface ProblemDao {
|
||||
@Query("SELECT * FROM problems WHERE gymId = :gymId AND isActive = 1 ORDER BY updatedAt DESC")
|
||||
fun getActiveProblemsByGym(gymId: String): Flow<List<Problem>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertProblem(problem: Problem)
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertProblem(problem: Problem)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertProblems(problems: List<Problem>)
|
||||
@@ -39,7 +41,8 @@ interface ProblemDao {
|
||||
|
||||
@Delete suspend fun deleteProblem(problem: Problem)
|
||||
|
||||
@Query("DELETE FROM problems WHERE id = :id") suspend fun deleteProblemById(id: String)
|
||||
@Query("DELETE FROM problems WHERE id = :id")
|
||||
suspend fun deleteProblemById(id: String)
|
||||
|
||||
@Query("SELECT COUNT(*) FROM problems WHERE gymId = :gymId")
|
||||
suspend fun getProblemsCountByGym(gymId: String): Int
|
||||
@@ -48,17 +51,19 @@ interface ProblemDao {
|
||||
suspend fun getActiveProblemsCount(): Int
|
||||
|
||||
@Query(
|
||||
"""
|
||||
"""
|
||||
SELECT * FROM problems
|
||||
WHERE (name LIKE '%' || :searchQuery || '%'
|
||||
OR description LIKE '%' || :searchQuery || '%'
|
||||
OR location LIKE '%' || :searchQuery || '%')
|
||||
ORDER BY updatedAt DESC
|
||||
"""
|
||||
""",
|
||||
)
|
||||
fun searchProblems(searchQuery: String): Flow<List<Problem>>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM problems") suspend fun getProblemsCount(): Int
|
||||
@Query("SELECT COUNT(*) FROM problems")
|
||||
suspend fun getProblemsCount(): Int
|
||||
|
||||
@Query("DELETE FROM problems") suspend fun deleteAllProblems()
|
||||
@Query("DELETE FROM problems")
|
||||
suspend fun deleteAllProblems()
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package com.atridad.ascently.data.format
|
||||
|
||||
import com.atridad.ascently.data.model.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// Root structure for Ascently backup data
|
||||
@Serializable
|
||||
data class ClimbDataBackup(
|
||||
val exportedAt: String,
|
||||
val version: String = "2.0",
|
||||
val formatVersion: String = "2.0",
|
||||
val gyms: List<BackupGym>,
|
||||
val problems: List<BackupProblem>,
|
||||
val sessions: List<BackupClimbSession>,
|
||||
val attempts: List<BackupAttempt>,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DeletedItem(
|
||||
val id: String,
|
||||
val type: String, // "gym", "problem", "session", "attempt"
|
||||
val deletedAt: String,
|
||||
)
|
||||
|
||||
// Platform-neutral gym representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupGym(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val location: String? = null,
|
||||
val supportedClimbTypes: List<ClimbType>,
|
||||
val difficultySystems: List<DifficultySystem>,
|
||||
@kotlinx.serialization.SerialName("customDifficultyGrades")
|
||||
val customDifficultyGrades: List<String>? = null,
|
||||
val notes: String? = null,
|
||||
val isDeleted: Boolean = false,
|
||||
val createdAt: String,
|
||||
val updatedAt: String,
|
||||
) {
|
||||
companion object {
|
||||
fun fromGym(gym: Gym): BackupGym {
|
||||
return BackupGym(
|
||||
id = gym.id,
|
||||
name = gym.name,
|
||||
location = gym.location,
|
||||
supportedClimbTypes = gym.supportedClimbTypes,
|
||||
difficultySystems = gym.difficultySystems,
|
||||
customDifficultyGrades = gym.customDifficultyGrades.ifEmpty { null },
|
||||
notes = gym.notes,
|
||||
isDeleted = false,
|
||||
createdAt = gym.createdAt,
|
||||
updatedAt = gym.updatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
fun createTombstone(id: String, deletedAt: String): BackupGym {
|
||||
return BackupGym(
|
||||
id = id,
|
||||
name = "DELETED",
|
||||
location = null,
|
||||
supportedClimbTypes = emptyList(),
|
||||
difficultySystems = emptyList(),
|
||||
customDifficultyGrades = null,
|
||||
notes = null,
|
||||
isDeleted = true,
|
||||
createdAt = deletedAt,
|
||||
updatedAt = deletedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun toGym(): Gym {
|
||||
return Gym(
|
||||
id = id,
|
||||
name = name,
|
||||
location = location,
|
||||
supportedClimbTypes = supportedClimbTypes,
|
||||
difficultySystems = difficultySystems,
|
||||
customDifficultyGrades = customDifficultyGrades ?: emptyList(),
|
||||
notes = notes,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-neutral problem representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupProblem(
|
||||
val id: String,
|
||||
val gymId: String,
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val climbType: ClimbType,
|
||||
val difficulty: DifficultyGrade,
|
||||
val tags: List<String>? = null,
|
||||
val location: String? = null,
|
||||
val imagePaths: List<String>? = null,
|
||||
val isActive: Boolean = true,
|
||||
val dateSet: String? = null,
|
||||
val notes: String? = null,
|
||||
val isDeleted: Boolean = false,
|
||||
val createdAt: String,
|
||||
val updatedAt: String,
|
||||
) {
|
||||
companion object {
|
||||
fun fromProblem(problem: Problem): BackupProblem {
|
||||
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 =
|
||||
if (problem.imagePaths.isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
problem.imagePaths.map { path -> path.substringAfterLast('/') }
|
||||
},
|
||||
isActive = problem.isActive,
|
||||
dateSet = problem.dateSet,
|
||||
notes = problem.notes,
|
||||
isDeleted = false,
|
||||
createdAt = problem.createdAt,
|
||||
updatedAt = problem.updatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
fun createTombstone(id: String, deletedAt: String): BackupProblem {
|
||||
return BackupProblem(
|
||||
id = id,
|
||||
gymId = "00000000-0000-0000-0000-000000000000",
|
||||
name = "DELETED",
|
||||
description = null,
|
||||
climbType = ClimbType.values().first(),
|
||||
difficulty = DifficultyGrade(DifficultySystem.values().first(), "0"),
|
||||
tags = null,
|
||||
location = null,
|
||||
imagePaths = null,
|
||||
isActive = false,
|
||||
dateSet = null,
|
||||
notes = null,
|
||||
isDeleted = true,
|
||||
createdAt = deletedAt,
|
||||
updatedAt = deletedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun toProblem(): Problem {
|
||||
return Problem(
|
||||
id = id,
|
||||
gymId = gymId,
|
||||
name = name,
|
||||
description = description,
|
||||
climbType = climbType,
|
||||
difficulty = difficulty,
|
||||
tags = tags ?: emptyList(),
|
||||
location = location,
|
||||
imagePaths = imagePaths ?: emptyList(),
|
||||
isActive = isActive,
|
||||
dateSet = dateSet,
|
||||
notes = notes,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
fun withUpdatedImagePaths(newImagePaths: List<String>): BackupProblem {
|
||||
return copy(imagePaths = newImagePaths.ifEmpty { null })
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-neutral climb session representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupClimbSession(
|
||||
val id: String,
|
||||
val gymId: String,
|
||||
val date: String,
|
||||
val startTime: String? = null,
|
||||
val endTime: String? = null,
|
||||
val duration: Long? = null,
|
||||
val status: SessionStatus,
|
||||
val notes: String? = null,
|
||||
val isDeleted: Boolean = false,
|
||||
val createdAt: String,
|
||||
val updatedAt: String,
|
||||
) {
|
||||
companion object {
|
||||
fun fromClimbSession(session: ClimbSession): BackupClimbSession {
|
||||
return 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,
|
||||
isDeleted = false,
|
||||
createdAt = session.createdAt,
|
||||
updatedAt = session.updatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
fun createTombstone(id: String, deletedAt: String): BackupClimbSession {
|
||||
return BackupClimbSession(
|
||||
id = id,
|
||||
gymId = "00000000-0000-0000-0000-000000000000",
|
||||
date = deletedAt,
|
||||
startTime = null,
|
||||
endTime = null,
|
||||
duration = null,
|
||||
status = SessionStatus.values().first(),
|
||||
notes = null,
|
||||
isDeleted = true,
|
||||
createdAt = deletedAt,
|
||||
updatedAt = deletedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun toClimbSession(): ClimbSession {
|
||||
return ClimbSession(
|
||||
id = id,
|
||||
gymId = gymId,
|
||||
date = date,
|
||||
startTime = startTime,
|
||||
endTime = endTime,
|
||||
duration = duration,
|
||||
status = status,
|
||||
notes = notes,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-neutral attempt representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupAttempt(
|
||||
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 isDeleted: Boolean = false,
|
||||
val createdAt: String,
|
||||
val updatedAt: String? = null,
|
||||
) {
|
||||
companion object {
|
||||
fun fromAttempt(attempt: Attempt): BackupAttempt {
|
||||
return 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,
|
||||
isDeleted = false,
|
||||
createdAt = attempt.createdAt,
|
||||
updatedAt = attempt.updatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
fun createTombstone(id: String, deletedAt: String): BackupAttempt {
|
||||
return BackupAttempt(
|
||||
id = id,
|
||||
sessionId = "00000000-0000-0000-0000-000000000000",
|
||||
problemId = "00000000-0000-0000-0000-000000000000",
|
||||
result = AttemptResult.values().first(),
|
||||
highestHold = null,
|
||||
notes = null,
|
||||
duration = null,
|
||||
restTime = null,
|
||||
timestamp = deletedAt,
|
||||
isDeleted = true,
|
||||
createdAt = deletedAt,
|
||||
updatedAt = deletedAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun toAttempt(): Attempt {
|
||||
return Attempt(
|
||||
id = id,
|
||||
sessionId = sessionId,
|
||||
problemId = problemId,
|
||||
result = result,
|
||||
highestHold = highestHold,
|
||||
notes = notes,
|
||||
duration = duration,
|
||||
restTime = restTime,
|
||||
timestamp = timestamp,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt ?: createdAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
package com.atridad.ascently.data.health
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.activity.result.contract.ActivityResultContract
|
||||
import androidx.health.connect.client.HealthConnectClient
|
||||
import androidx.health.connect.client.PermissionController
|
||||
import androidx.health.connect.client.permission.HealthPermission
|
||||
import androidx.health.connect.client.records.ExerciseSessionRecord
|
||||
import androidx.health.connect.client.records.HeartRateRecord
|
||||
import androidx.health.connect.client.records.TotalCaloriesBurnedRecord
|
||||
|
||||
import androidx.health.connect.client.units.Energy
|
||||
import com.atridad.ascently.data.model.ClimbSession
|
||||
import com.atridad.ascently.data.model.SessionStatus
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import java.time.ZoneOffset
|
||||
import androidx.core.content.edit
|
||||
|
||||
/**
|
||||
* Health Connect manager for Ascently that syncs climbing sessions to Samsung Health, Google Fit,
|
||||
* and other health apps.
|
||||
*/
|
||||
@SuppressLint("RestrictedApi")
|
||||
class HealthConnectManager(private val context: Context) {
|
||||
|
||||
private val preferences: SharedPreferences =
|
||||
context.getSharedPreferences("health_connect_prefs", Context.MODE_PRIVATE)
|
||||
|
||||
private val _isEnabled = MutableStateFlow(preferences.getBoolean("enabled", false))
|
||||
private val _hasPermissions = MutableStateFlow(preferences.getBoolean("permissions", false))
|
||||
private val _autoSync = MutableStateFlow(preferences.getBoolean("auto_sync", true))
|
||||
private val _isCompatible = MutableStateFlow(true)
|
||||
|
||||
val isEnabled: Flow<Boolean> = _isEnabled.asStateFlow()
|
||||
val hasPermissions: Flow<Boolean> = _hasPermissions.asStateFlow()
|
||||
val isCompatible: Flow<Boolean> = _isCompatible.asStateFlow()
|
||||
|
||||
companion object {
|
||||
private const val TAG = "HealthConnectManager"
|
||||
|
||||
val REQUIRED_PERMISSIONS =
|
||||
setOf(
|
||||
HealthPermission.getReadPermission(ExerciseSessionRecord::class),
|
||||
HealthPermission.getWritePermission(ExerciseSessionRecord::class),
|
||||
HealthPermission.getReadPermission(HeartRateRecord::class),
|
||||
HealthPermission.getWritePermission(HeartRateRecord::class),
|
||||
HealthPermission.getReadPermission(TotalCaloriesBurnedRecord::class),
|
||||
HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class),
|
||||
)
|
||||
}
|
||||
|
||||
private val healthConnectClient by lazy {
|
||||
try {
|
||||
HealthConnectClient.getOrCreate(context)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Failed to create Health Connect client" }
|
||||
_isCompatible.value = false
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun isHealthConnectAvailable(): Flow<Boolean> = flow {
|
||||
try {
|
||||
if (!_isCompatible.value) {
|
||||
emit(false)
|
||||
return@flow
|
||||
}
|
||||
val status = HealthConnectClient.getSdkStatus(context)
|
||||
emit(status == HealthConnectClient.SDK_AVAILABLE)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Error checking Health Connect availability" }
|
||||
_isCompatible.value = false
|
||||
emit(false)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setEnabled(enabled: Boolean) {
|
||||
preferences.edit().putBoolean("enabled", enabled).apply()
|
||||
_isEnabled.value = enabled
|
||||
|
||||
if (enabled && _isCompatible.value) {
|
||||
// Automatically request permissions when enabling
|
||||
try {
|
||||
val alreadyHasPermissions = hasAllPermissions()
|
||||
if (!alreadyHasPermissions) {
|
||||
AppLogger.d(TAG) { "Health Connect enabled - permissions will be requested by UI" }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
AppLogger.w(TAG, e) { "Error checking permissions when enabling Health Connect" }
|
||||
}
|
||||
} else if (!enabled) {
|
||||
setPermissionsGranted(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun setPermissionsGranted(granted: Boolean) {
|
||||
preferences.edit().putBoolean("permissions", granted).apply()
|
||||
_hasPermissions.value = granted
|
||||
}
|
||||
|
||||
suspend fun hasAllPermissions(): Boolean {
|
||||
return try {
|
||||
if (!_isCompatible.value || healthConnectClient == null) {
|
||||
return false
|
||||
}
|
||||
val grantedPermissions =
|
||||
healthConnectClient!!.permissionController.getGrantedPermissions()
|
||||
val hasAll =
|
||||
REQUIRED_PERMISSIONS.all { permission ->
|
||||
grantedPermissions.contains(permission)
|
||||
}
|
||||
setPermissionsGranted(hasAll)
|
||||
hasAll
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Error checking permissions" }
|
||||
setPermissionsGranted(false)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun isReady(): Boolean {
|
||||
return try {
|
||||
if (!_isEnabled.value || !_isCompatible.value || healthConnectClient == null) {
|
||||
return false
|
||||
}
|
||||
|
||||
val isAvailable =
|
||||
HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE
|
||||
val hasPerms = if (isAvailable) hasAllPermissions() else false
|
||||
isAvailable && hasPerms
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Error checking Health Connect readiness" }
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun getPermissionRequestContract(): ActivityResultContract<Set<String>, Set<String>> {
|
||||
return PermissionController.createRequestPermissionResultContract()
|
||||
}
|
||||
|
||||
fun getRequiredPermissions(): Set<String> {
|
||||
return try {
|
||||
REQUIRED_PERMISSIONS.map { it }.toSet()
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Error getting required permissions" }
|
||||
emptySet()
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
suspend fun syncCompletedSession(
|
||||
session: ClimbSession,
|
||||
gymName: String,
|
||||
attemptCount: Int = 0,
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
if (!isReady() || !_autoSync.value) {
|
||||
return Result.failure(
|
||||
IllegalStateException("Health Connect not ready or auto-sync disabled"),
|
||||
)
|
||||
}
|
||||
|
||||
if (session.status != SessionStatus.COMPLETED) {
|
||||
return Result.failure(
|
||||
IllegalArgumentException("Only completed sessions can be synced"),
|
||||
)
|
||||
}
|
||||
|
||||
val startTime = session.startTime?.let { DateFormatUtils.parseISO8601(it) }
|
||||
val endTime = session.endTime?.let { DateFormatUtils.parseISO8601(it) }
|
||||
|
||||
if (startTime == null || endTime == null) {
|
||||
return Result.failure(
|
||||
IllegalArgumentException("Session must have valid start and end times"),
|
||||
)
|
||||
}
|
||||
|
||||
AppLogger.d(TAG) { "Attempting to sync session '${session.id}' to Health Connect..." }
|
||||
|
||||
val records = mutableListOf<androidx.health.connect.client.records.Record>()
|
||||
|
||||
try {
|
||||
val exerciseSession =
|
||||
ExerciseSessionRecord(
|
||||
startTime = startTime,
|
||||
startZoneOffset =
|
||||
ZoneOffset.systemDefault().rules.getOffset(startTime),
|
||||
endTime = endTime,
|
||||
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||
exerciseType =
|
||||
ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING,
|
||||
title = "Rock Climbing at $gymName",
|
||||
metadata = androidx.health.connect.client.records.metadata.Metadata.manualEntry(),
|
||||
)
|
||||
records.add(exerciseSession)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.w(TAG, e) { "Failed to create exercise session record" }
|
||||
}
|
||||
|
||||
try {
|
||||
val durationMinutes = Duration.between(startTime, endTime).toMinutes()
|
||||
val estimatedCalories = estimateCaloriesForClimbing(durationMinutes, attemptCount)
|
||||
|
||||
if (estimatedCalories > 0) {
|
||||
val caloriesRecord =
|
||||
TotalCaloriesBurnedRecord(
|
||||
startTime = startTime,
|
||||
startZoneOffset =
|
||||
ZoneOffset.systemDefault().rules.getOffset(startTime),
|
||||
endTime = endTime,
|
||||
endZoneOffset =
|
||||
ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||
energy = Energy.calories(estimatedCalories),
|
||||
metadata = androidx.health.connect.client.records.metadata.Metadata.manualEntry(),
|
||||
)
|
||||
records.add(caloriesRecord)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
AppLogger.w(TAG, e) { "Failed to create calories record" }
|
||||
}
|
||||
|
||||
try {
|
||||
val heartRateRecord = createHeartRateRecord(startTime, endTime, attemptCount)
|
||||
heartRateRecord?.let { records.add(it) }
|
||||
} catch (e: Exception) {
|
||||
AppLogger.w(TAG, e) { "Failed to create heart rate record" }
|
||||
}
|
||||
|
||||
if (records.isNotEmpty() && healthConnectClient != null) {
|
||||
AppLogger.d(TAG) { "Writing ${records.size} records to Health Connect..." }
|
||||
healthConnectClient!!.insertRecords(records)
|
||||
AppLogger.i(TAG) {
|
||||
"Successfully synced ${records.size} records for session '${session.id}' to Health Connect"
|
||||
}
|
||||
|
||||
preferences
|
||||
.edit {
|
||||
putString("last_sync_success", DateFormatUtils.nowISO8601())
|
||||
}
|
||||
} else {
|
||||
val reason =
|
||||
when {
|
||||
records.isEmpty() -> "No records created"
|
||||
healthConnectClient == null -> "Health Connect client unavailable"
|
||||
else -> "Unknown reason"
|
||||
}
|
||||
AppLogger.w(TAG) { "Sync failed for session '${session.id}': $reason" }
|
||||
return Result.failure(Exception("Sync failed: $reason"))
|
||||
}
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Error syncing climbing session to Health Connect" }
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun autoSyncCompletedSession(
|
||||
session: ClimbSession,
|
||||
gymName: String,
|
||||
attemptCount: Int = 0,
|
||||
): Result<Unit> {
|
||||
return if (_autoSync.value && isReady() && session.status == SessionStatus.COMPLETED) {
|
||||
AppLogger.d(TAG) { "Auto-syncing completed session '${session.id}' to Health Connect..." }
|
||||
syncCompletedSession(session, gymName, attemptCount)
|
||||
} else {
|
||||
val reason =
|
||||
when {
|
||||
session.status != SessionStatus.COMPLETED -> "session not completed"
|
||||
!_autoSync.value -> "auto-sync disabled"
|
||||
!isReady() -> "Health Connect not ready"
|
||||
else -> "unknown reason"
|
||||
}
|
||||
AppLogger.d(TAG) { "Auto-sync skipped for session '${session.id}': $reason" }
|
||||
Result.success(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
private fun estimateCaloriesForClimbing(durationMinutes: Long, attemptCount: Int): Double {
|
||||
val baseCaloriesPerMinute = 8.0
|
||||
val intensityMultiplier =
|
||||
when {
|
||||
attemptCount >= 20 -> 1.3
|
||||
attemptCount >= 10 -> 1.1
|
||||
else -> 0.9
|
||||
}
|
||||
return durationMinutes * baseCaloriesPerMinute * intensityMultiplier
|
||||
}
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
private fun createHeartRateRecord(
|
||||
startTime: Instant,
|
||||
endTime: Instant,
|
||||
attemptCount: Int,
|
||||
): HeartRateRecord? {
|
||||
return try {
|
||||
val samples = mutableListOf<HeartRateRecord.Sample>()
|
||||
val intervalMinutes = 5L
|
||||
|
||||
val baseHeartRate =
|
||||
when {
|
||||
attemptCount >= 20 -> 155L
|
||||
attemptCount >= 10 -> 145L
|
||||
else -> 135L
|
||||
}
|
||||
|
||||
var currentTime = startTime
|
||||
while (currentTime.isBefore(endTime)) {
|
||||
val variation = (-15..15).random()
|
||||
val heartRate = (baseHeartRate + variation).coerceIn(110L, 180L)
|
||||
|
||||
samples.add(HeartRateRecord.Sample(time = currentTime, beatsPerMinute = heartRate))
|
||||
currentTime = currentTime.plusSeconds(intervalMinutes * 60)
|
||||
}
|
||||
|
||||
if (samples.isEmpty()) return null
|
||||
|
||||
HeartRateRecord(
|
||||
startTime = startTime,
|
||||
startZoneOffset = ZoneOffset.systemDefault().rules.getOffset(startTime),
|
||||
endTime = endTime,
|
||||
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||
samples = samples,
|
||||
metadata = androidx.health.connect.client.records.metadata.Metadata.manualEntry(),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Error creating heart rate record" }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun isReadySync(): Boolean {
|
||||
return _isEnabled.value && _hasPermissions.value
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.atridad.ascently.data.model
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class AttemptResult {
|
||||
SUCCESS,
|
||||
FALL,
|
||||
NO_PROGRESS,
|
||||
FLASH,
|
||||
}
|
||||
|
||||
@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"])],
|
||||
)
|
||||
@Immutable
|
||||
@Serializable
|
||||
data class Attempt(
|
||||
@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,
|
||||
val updatedAt: 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 = DateFormatUtils.nowISO8601(),
|
||||
): Attempt {
|
||||
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,
|
||||
updatedAt = now,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.atridad.ascently.data.model
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class SessionStatus {
|
||||
ACTIVE,
|
||||
COMPLETED,
|
||||
PAUSED,
|
||||
}
|
||||
|
||||
@Entity(
|
||||
tableName = "climb_sessions",
|
||||
foreignKeys =
|
||||
[
|
||||
ForeignKey(
|
||||
entity = Gym::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["gymId"],
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
),
|
||||
],
|
||||
indices = [Index(value = ["gymId"])],
|
||||
)
|
||||
@Immutable
|
||||
@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,
|
||||
) {
|
||||
companion object {
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
fun ClimbSession.complete(): ClimbSession {
|
||||
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 = DateFormatUtils.nowISO8601(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.atridad.ascently.data.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class ClimbType {
|
||||
ROPE,
|
||||
BOULDER,
|
||||
;
|
||||
|
||||
val displayName: String
|
||||
get() =
|
||||
when (this) {
|
||||
ROPE -> "Rope"
|
||||
BOULDER -> "Bouldering"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.atridad.ascently.data.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class DifficultySystem {
|
||||
// Bouldering
|
||||
V_SCALE,
|
||||
FONT,
|
||||
|
||||
// Rope
|
||||
YDS,
|
||||
CUSTOM,
|
||||
;
|
||||
|
||||
val displayName: String
|
||||
get() =
|
||||
when (this) {
|
||||
V_SCALE -> "V Scale"
|
||||
FONT -> "Font Scale"
|
||||
YDS -> "YDS (Yosemite)"
|
||||
CUSTOM -> "Custom"
|
||||
}
|
||||
|
||||
val isBoulderingSystem: Boolean
|
||||
get() =
|
||||
when (this) {
|
||||
V_SCALE, FONT -> true
|
||||
YDS -> false
|
||||
CUSTOM -> true
|
||||
}
|
||||
|
||||
val isRopeSystem: Boolean
|
||||
get() =
|
||||
when (this) {
|
||||
YDS -> true
|
||||
V_SCALE, FONT -> false
|
||||
CUSTOM -> true
|
||||
}
|
||||
|
||||
val availableGrades: List<String>
|
||||
get() =
|
||||
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 {
|
||||
fun systemsForClimbType(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) {
|
||||
|
||||
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.FONT -> {
|
||||
val fontMapping: Map<String, Int> =
|
||||
mapOf(
|
||||
"3" to 3,
|
||||
"4A" to 4,
|
||||
"4B" to 5,
|
||||
"4C" to 6,
|
||||
"5A" to 7,
|
||||
"5B" to 8,
|
||||
"5C" to 9,
|
||||
"6A" to 10,
|
||||
"6A+" to 11,
|
||||
"6B" to 12,
|
||||
"6B+" to 13,
|
||||
"6C" to 14,
|
||||
"6C+" to 15,
|
||||
"7A" to 16,
|
||||
"7A+" to 17,
|
||||
"7B" to 18,
|
||||
"7B+" to 19,
|
||||
"7C" to 20,
|
||||
"7C+" to 21,
|
||||
"8A" to 22,
|
||||
"8A+" to 23,
|
||||
"8B" to 24,
|
||||
"8B+" to 25,
|
||||
"8C" to 26,
|
||||
"8C+" to 27,
|
||||
)
|
||||
fontMapping[grade] ?: 0
|
||||
}
|
||||
DifficultySystem.YDS -> {
|
||||
val ydsMapping: Map<String, Int> =
|
||||
mapOf(
|
||||
"5.0" to 50,
|
||||
"5.1" to 51,
|
||||
"5.2" to 52,
|
||||
"5.3" to 53,
|
||||
"5.4" to 54,
|
||||
"5.5" to 55,
|
||||
"5.6" to 56,
|
||||
"5.7" to 57,
|
||||
"5.8" to 58,
|
||||
"5.9" to 59,
|
||||
"5.10a" to 60,
|
||||
"5.10b" to 61,
|
||||
"5.10c" to 62,
|
||||
"5.10d" to 63,
|
||||
"5.11a" to 64,
|
||||
"5.11b" to 65,
|
||||
"5.11c" to 66,
|
||||
"5.11d" to 67,
|
||||
"5.12a" to 68,
|
||||
"5.12b" to 69,
|
||||
"5.12c" to 70,
|
||||
"5.12d" to 71,
|
||||
"5.13a" to 72,
|
||||
"5.13b" to 73,
|
||||
"5.13c" to 74,
|
||||
"5.13d" to 75,
|
||||
"5.14a" to 76,
|
||||
"5.14b" to 77,
|
||||
"5.14c" to 78,
|
||||
"5.14d" to 79,
|
||||
"5.15a" to 80,
|
||||
"5.15b" to 81,
|
||||
"5.15c" to 82,
|
||||
"5.15d" to 83,
|
||||
)
|
||||
ydsMapping[grade] ?: 0
|
||||
}
|
||||
DifficultySystem.CUSTOM -> grade.toIntOrNull() ?: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
DifficultySystem.YDS -> compareYDSGrades(grade, other.grade)
|
||||
DifficultySystem.CUSTOM -> grade.compareTo(other.grade)
|
||||
}
|
||||
}
|
||||
|
||||
private fun compareVScaleGrades(grade1: String, grade2: String): Int {
|
||||
if (grade1 == "VB" && grade2 != "VB") return -1
|
||||
if (grade2 == "VB" && grade1 != "VB") return 1
|
||||
if (grade1 == "VB") return 0
|
||||
|
||||
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 {
|
||||
return grade1.compareTo(grade2)
|
||||
}
|
||||
|
||||
private fun compareYDSGrades(grade1: String, grade2: String): Int {
|
||||
return grade1.compareTo(grade2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.atridad.ascently.data.model
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Immutable
|
||||
@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,
|
||||
) {
|
||||
companion object {
|
||||
fun create(
|
||||
name: String,
|
||||
location: String? = null,
|
||||
supportedClimbTypes: List<ClimbType>,
|
||||
difficultySystems: List<DifficultySystem>,
|
||||
customDifficultyGrades: List<String> = emptyList(),
|
||||
notes: String? = null,
|
||||
): Gym {
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.atridad.ascently.data.model
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Immutable
|
||||
@Entity(
|
||||
tableName = "problems",
|
||||
foreignKeys =
|
||||
[
|
||||
ForeignKey(
|
||||
entity = Gym::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["gymId"],
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
),
|
||||
],
|
||||
indices = [Index(value = ["gymId"])],
|
||||
)
|
||||
@Serializable
|
||||
data class Problem(
|
||||
@PrimaryKey val id: String,
|
||||
val gymId: String,
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val climbType: ClimbType,
|
||||
val difficulty: DifficultyGrade,
|
||||
val tags: List<String> = emptyList(),
|
||||
val location: String? = null,
|
||||
val imagePaths: List<String> = emptyList(),
|
||||
val isActive: Boolean = true,
|
||||
val dateSet: String? = null,
|
||||
val notes: String? = null,
|
||||
val createdAt: String,
|
||||
val updatedAt: String,
|
||||
) {
|
||||
companion object {
|
||||
fun create(
|
||||
gymId: String,
|
||||
name: String? = null,
|
||||
description: String? = null,
|
||||
climbType: ClimbType,
|
||||
difficulty: DifficultyGrade,
|
||||
tags: List<String> = emptyList(),
|
||||
location: String? = null,
|
||||
imagePaths: List<String> = emptyList(),
|
||||
dateSet: String? = null,
|
||||
notes: String? = null,
|
||||
): Problem {
|
||||
val now = DateFormatUtils.nowISO8601()
|
||||
return Problem(
|
||||
id = java.util.UUID.randomUUID().toString(),
|
||||
gymId = gymId,
|
||||
name = name,
|
||||
description = description,
|
||||
climbType = climbType,
|
||||
difficulty = difficulty,
|
||||
tags = tags,
|
||||
location = location,
|
||||
imagePaths = imagePaths,
|
||||
isActive = true,
|
||||
dateSet = dateSet,
|
||||
notes = notes,
|
||||
createdAt = now,
|
||||
updatedAt = now,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,34 @@
|
||||
package com.atridad.openclimb.data.repository
|
||||
package com.atridad.ascently.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.core.content.edit
|
||||
import com.atridad.openclimb.data.database.OpenClimbDatabase
|
||||
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.format.DeletedItem
|
||||
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 com.atridad.ascently.data.database.AscentlyDatabase
|
||||
import com.atridad.ascently.data.format.BackupAttempt
|
||||
import com.atridad.ascently.data.format.BackupClimbSession
|
||||
import com.atridad.ascently.data.format.BackupGym
|
||||
import com.atridad.ascently.data.format.BackupProblem
|
||||
import com.atridad.ascently.data.format.ClimbDataBackup
|
||||
import com.atridad.ascently.data.format.DeletedItem
|
||||
import com.atridad.ascently.data.model.*
|
||||
import com.atridad.ascently.data.state.DataStateManager
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import com.atridad.ascently.utils.ZipExportImportUtils
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
|
||||
class ClimbRepository(database: OpenClimbDatabase, private val context: Context) {
|
||||
class ClimbRepository(database: AscentlyDatabase, 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 dataStateManager = DataStateManager(context)
|
||||
private val deletionPreferences: SharedPreferences =
|
||||
context.getSharedPreferences("deleted_items", Context.MODE_PRIVATE)
|
||||
context.getSharedPreferences("deleted_items", Context.MODE_PRIVATE)
|
||||
|
||||
private var autoSyncCallback: (() -> Unit)? = null
|
||||
|
||||
@@ -37,17 +39,20 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
|
||||
// Gym operations
|
||||
fun getAllGyms(): Flow<List<Gym>> = gymDao.getAllGyms()
|
||||
suspend fun getAllGymsSync(): List<Gym> = gymDao.getAllGyms().first()
|
||||
suspend fun getGymById(id: String): Gym? = gymDao.getGymById(id)
|
||||
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)
|
||||
trackDeletion(gym.id, "gym")
|
||||
@@ -57,16 +62,19 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
|
||||
// Problem operations
|
||||
fun getAllProblems(): Flow<List<Problem>> = problemDao.getAllProblems()
|
||||
suspend fun getAllProblemsSync(): List<Problem> = problemDao.getAllProblems().first()
|
||||
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)
|
||||
dataStateManager.updateDataState()
|
||||
}
|
||||
|
||||
suspend fun updateProblem(problem: Problem) {
|
||||
problemDao.updateProblem(problem)
|
||||
dataStateManager.updateDataState()
|
||||
}
|
||||
|
||||
suspend fun deleteProblem(problem: Problem) {
|
||||
problemDao.deleteProblem(problem)
|
||||
trackDeletion(problem.id, "problem")
|
||||
@@ -75,9 +83,11 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
|
||||
// Session operations
|
||||
fun getAllSessions(): Flow<List<ClimbSession>> = sessionDao.getAllSessions()
|
||||
suspend fun getAllSessionsSync(): List<ClimbSession> = sessionDao.getAllSessions().first()
|
||||
suspend fun getSessionById(id: String): ClimbSession? = sessionDao.getSessionById(id)
|
||||
fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>> =
|
||||
sessionDao.getSessionsByGym(gymId)
|
||||
sessionDao.getSessionsByGym(gymId)
|
||||
|
||||
suspend fun getActiveSession(): ClimbSession? = sessionDao.getActiveSession()
|
||||
fun getActiveSessionFlow(): Flow<ClimbSession?> = sessionDao.getActiveSessionFlow()
|
||||
suspend fun insertSession(session: ClimbSession) {
|
||||
@@ -88,6 +98,7 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
triggerAutoSync()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun updateSession(session: ClimbSession) {
|
||||
sessionDao.updateSession(session)
|
||||
dataStateManager.updateDataState()
|
||||
@@ -96,12 +107,14 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
triggerAutoSync()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deleteSession(session: ClimbSession) {
|
||||
sessionDao.deleteSession(session)
|
||||
trackDeletion(session.id, "session")
|
||||
dataStateManager.updateDataState()
|
||||
triggerAutoSync()
|
||||
}
|
||||
|
||||
suspend fun getLastUsedGym(): Gym? {
|
||||
val recentSessions = sessionDao.getRecentSessions(1).first()
|
||||
return if (recentSessions.isNotEmpty()) {
|
||||
@@ -113,18 +126,24 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
|
||||
// Attempt operations
|
||||
fun getAllAttempts(): Flow<List<Attempt>> = attemptDao.getAllAttempts()
|
||||
suspend fun getAllAttemptsSync(): List<Attempt> = attemptDao.getAllAttempts().first()
|
||||
suspend fun getAttemptById(id: String): Attempt? = attemptDao.getAttemptById(id)
|
||||
fun getAttemptsBySession(sessionId: String): Flow<List<Attempt>> =
|
||||
attemptDao.getAttemptsBySession(sessionId)
|
||||
attemptDao.getAttemptsBySession(sessionId)
|
||||
|
||||
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>> =
|
||||
attemptDao.getAttemptsByProblem(problemId)
|
||||
attemptDao.getAttemptsByProblem(problemId)
|
||||
|
||||
suspend fun insertAttempt(attempt: Attempt) {
|
||||
attemptDao.insertAttempt(attempt)
|
||||
dataStateManager.updateDataState()
|
||||
}
|
||||
|
||||
suspend fun updateAttempt(attempt: Attempt) {
|
||||
attemptDao.updateAttempt(attempt)
|
||||
dataStateManager.updateDataState()
|
||||
}
|
||||
|
||||
suspend fun deleteAttempt(attempt: Attempt) {
|
||||
attemptDao.deleteAttempt(attempt)
|
||||
trackDeletion(attempt.id, "attempt")
|
||||
@@ -141,38 +160,38 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
validateDataIntegrity(allGyms, allProblems, allSessions, allAttempts)
|
||||
|
||||
val backupData =
|
||||
ClimbDataBackup(
|
||||
exportedAt = DateFormatUtils.nowISO8601(),
|
||||
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) }
|
||||
)
|
||||
ClimbDataBackup(
|
||||
exportedAt = DateFormatUtils.nowISO8601(),
|
||||
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) },
|
||||
)
|
||||
|
||||
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 (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
.toSet()
|
||||
referencedImagePaths
|
||||
.filter { imagePath ->
|
||||
try {
|
||||
val imageFile =
|
||||
com.atridad.ascently.utils.ImageUtils.getImageFile(
|
||||
context,
|
||||
imagePath,
|
||||
)
|
||||
imageFile.exists() && imageFile.length() > 0
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
.toSet()
|
||||
|
||||
ZipExportImportUtils.createExportZipToUri(
|
||||
context = context,
|
||||
uri = uri,
|
||||
exportData = backupData,
|
||||
referencedImagePaths = validImagePaths
|
||||
context = context,
|
||||
uri = uri,
|
||||
exportData = backupData,
|
||||
referencedImagePaths = validImagePaths,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
throw Exception("Export failed: ${e.message}")
|
||||
@@ -192,11 +211,11 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
}
|
||||
|
||||
val importData =
|
||||
try {
|
||||
json.decodeFromString<ClimbDataBackup>(importResult.jsonContent)
|
||||
} catch (e: Exception) {
|
||||
throw Exception("Invalid data format: ${e.message}")
|
||||
}
|
||||
try {
|
||||
json.decodeFromString<ClimbDataBackup>(importResult.jsonContent)
|
||||
} catch (e: Exception) {
|
||||
throw Exception("Invalid data format: ${e.message}")
|
||||
}
|
||||
|
||||
validateImportData(importData)
|
||||
|
||||
@@ -214,17 +233,17 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
}
|
||||
|
||||
val updatedBackupProblems =
|
||||
ZipExportImportUtils.updateProblemImagePaths(
|
||||
importData.problems,
|
||||
importResult.importedImagePaths
|
||||
)
|
||||
ZipExportImportUtils.updateProblemImagePaths(
|
||||
importData.problems,
|
||||
importResult.importedImagePaths,
|
||||
)
|
||||
|
||||
updatedBackupProblems.forEach { backupProblem ->
|
||||
try {
|
||||
problemDao.insertProblem(backupProblem.toProblem())
|
||||
} catch (e: Exception) {
|
||||
throw Exception(
|
||||
"Failed to import problem '${backupProblem.name}': ${e.message}"
|
||||
"Failed to import problem '${backupProblem.name}': ${e.message}",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -251,30 +270,21 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 trackDeletion(itemId: String, itemType: String) {
|
||||
val currentDeletions = getDeletedItems().toMutableList()
|
||||
fun trackDeletion(itemId: String, itemType: String) {
|
||||
cleanupOldDeletions()
|
||||
val newDeletion =
|
||||
DeletedItem(id = itemId, type = itemType, deletedAt = DateFormatUtils.nowISO8601())
|
||||
currentDeletions.add(newDeletion)
|
||||
DeletedItem(id = itemId, type = itemType, deletedAt = DateFormatUtils.nowISO8601())
|
||||
|
||||
val json = json.encodeToString(newDeletion)
|
||||
deletionPreferences.edit { putString("deleted_${itemId}", json) }
|
||||
deletionPreferences.edit { putString("deleted_$itemId", json) }
|
||||
}
|
||||
|
||||
fun getDeletedItems(): List<DeletedItem> {
|
||||
@@ -299,24 +309,45 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
deletionPreferences.edit { clear() }
|
||||
}
|
||||
|
||||
private fun cleanupOldDeletions() {
|
||||
val allPrefs = deletionPreferences.all
|
||||
val cutoff = Instant.now().minusSeconds(90L * 24 * 60 * 60)
|
||||
|
||||
deletionPreferences.edit {
|
||||
for ((key, value) in allPrefs) {
|
||||
if (key.startsWith("deleted_") && value is String) {
|
||||
try {
|
||||
val deletion = json.decodeFromString<DeletedItem>(value)
|
||||
val deletedAt = Instant.parse(deletion.deletedAt)
|
||||
if (deletedAt.isBefore(cutoff)) {
|
||||
remove(key)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun validateDataIntegrity(
|
||||
gyms: List<Gym>,
|
||||
problems: List<Problem>,
|
||||
sessions: List<ClimbSession>,
|
||||
attempts: List<Attempt>
|
||||
gyms: List<Gym>,
|
||||
problems: List<Problem>,
|
||||
sessions: List<ClimbSession>,
|
||||
attempts: List<Attempt>,
|
||||
) {
|
||||
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"
|
||||
"Data integrity error: ${invalidProblems.size} problems reference non-existent gyms",
|
||||
)
|
||||
}
|
||||
|
||||
val invalidSessions = sessions.filter { it.gymId !in gymIds }
|
||||
if (invalidSessions.isNotEmpty()) {
|
||||
throw Exception(
|
||||
"Data integrity error: ${invalidSessions.size} sessions reference non-existent gyms"
|
||||
"Data integrity error: ${invalidSessions.size} sessions reference non-existent gyms",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -324,10 +355,10 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
val sessionIds = sessions.map { it.id }.toSet()
|
||||
|
||||
val invalidAttempts =
|
||||
attempts.filter { it.problemId !in problemIds || it.sessionId !in sessionIds }
|
||||
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"
|
||||
"Data integrity error: ${invalidAttempts.size} attempts reference non-existent problems or sessions",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -342,9 +373,9 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
}
|
||||
|
||||
if (importData.gyms.size > 1000 ||
|
||||
importData.problems.size > 10000 ||
|
||||
importData.sessions.size > 10000 ||
|
||||
importData.attempts.size > 100000
|
||||
importData.problems.size > 10000 ||
|
||||
importData.sessions.size > 10000 ||
|
||||
importData.attempts.size > 100000
|
||||
) {
|
||||
throw Exception("Import data is too large: possible corruption or malicious file")
|
||||
}
|
||||
@@ -394,10 +425,10 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
if (imagesDir.exists() && imagesDir.isDirectory) {
|
||||
val deletedCount = imagesDir.listFiles()?.size ?: 0
|
||||
imagesDir.deleteRecursively()
|
||||
android.util.Log.i("ClimbRepository", "Cleared $deletedCount image files")
|
||||
AppLogger.i("ClimbRepository") { "Cleared $deletedCount image files" }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.w("ClimbRepository", "Failed to clear some images: ${e.message}")
|
||||
AppLogger.w("ClimbRepository", e) { "Failed to clear some images: ${e.message}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.atridad.openclimb.data.state
|
||||
package com.atridad.ascently.data.state
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.atridad.openclimb.utils.DateFormatUtils
|
||||
import androidx.core.content.edit
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
|
||||
/**
|
||||
* Manages the overall data state timestamp for sync purposes. This tracks when any data in the
|
||||
@@ -14,19 +14,19 @@ class DataStateManager(context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DataStateManager"
|
||||
private const val PREFS_NAME = "openclimb_data_state"
|
||||
private const val PREFS_NAME = "ascently_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)
|
||||
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
|
||||
init {
|
||||
if (!isInitialized()) {
|
||||
updateDataState()
|
||||
markAsInitialized()
|
||||
Log.d(TAG, "DataStateManager initialized with timestamp: ${getLastModified()}")
|
||||
AppLogger.d(TAG) { "DataStateManager initialized with timestamp: ${getLastModified()}" }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ class DataStateManager(context: Context) {
|
||||
fun updateDataState() {
|
||||
val now = DateFormatUtils.nowISO8601()
|
||||
prefs.edit { putString(KEY_LAST_MODIFIED, now) }
|
||||
Log.d(TAG, "Data state updated to: $now")
|
||||
AppLogger.d(TAG) { "Data state updated to: $now" }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,7 +46,7 @@ class DataStateManager(context: Context) {
|
||||
*/
|
||||
fun getLastModified(): String {
|
||||
return prefs.getString(KEY_LAST_MODIFIED, DateFormatUtils.nowISO8601())
|
||||
?: DateFormatUtils.nowISO8601()
|
||||
?: DateFormatUtils.nowISO8601()
|
||||
}
|
||||
|
||||
/** Checks if the data state has been initialized. */
|
||||
@@ -58,5 +58,4 @@ class DataStateManager(context: Context) {
|
||||
private fun markAsInitialized() {
|
||||
prefs.edit { putBoolean(KEY_INITIALIZED, true) }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,649 @@
|
||||
package com.atridad.ascently.data.sync
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.util.Log
|
||||
import com.atridad.ascently.data.format.BackupAttempt
|
||||
import com.atridad.ascently.data.format.BackupClimbSession
|
||||
import com.atridad.ascently.data.format.BackupGym
|
||||
import com.atridad.ascently.data.format.BackupProblem
|
||||
import com.atridad.ascently.data.format.ClimbDataBackup
|
||||
import com.atridad.ascently.data.repository.ClimbRepository
|
||||
import com.atridad.ascently.data.state.DataStateManager
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class AscentlySyncProvider(
|
||||
private val context: Context,
|
||||
private val repository: ClimbRepository,
|
||||
private val dataStateManager: DataStateManager
|
||||
) : SyncProvider {
|
||||
|
||||
override val type = SyncProviderType.SERVER
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AscentlySyncProvider"
|
||||
}
|
||||
|
||||
private val sharedPreferences: SharedPreferences =
|
||||
context.getSharedPreferences("ascently_prefs", Context.MODE_PRIVATE)
|
||||
|
||||
private val httpClient =
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(45, TimeUnit.SECONDS)
|
||||
.readTimeout(90, TimeUnit.SECONDS)
|
||||
.writeTimeout(90, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
private val json = Json {
|
||||
prettyPrint = true
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
isLenient = true
|
||||
}
|
||||
|
||||
private val _isConnected = MutableStateFlow(false)
|
||||
override val isConnected: StateFlow<Boolean> = _isConnected.asStateFlow()
|
||||
|
||||
private val _isConfigured = MutableStateFlow(false)
|
||||
override val isConfigured: StateFlow<Boolean> = _isConfigured.asStateFlow()
|
||||
|
||||
var isOfflineMode: Boolean
|
||||
get() = sharedPreferences.getBoolean(Keys.OFFLINE_MODE, false)
|
||||
set(value) = sharedPreferences.edit().putBoolean(Keys.OFFLINE_MODE, value).apply()
|
||||
|
||||
object Keys {
|
||||
const val SERVER_URL = "sync_server_url"
|
||||
const val AUTH_TOKEN = "sync_auth_token"
|
||||
const val IS_CONNECTED = "is_connected"
|
||||
const val LAST_SYNC_TIME = "last_sync_time"
|
||||
const val OFFLINE_MODE = "offline_mode"
|
||||
}
|
||||
|
||||
init {
|
||||
loadInitialState()
|
||||
}
|
||||
|
||||
private fun loadInitialState() {
|
||||
_isConnected.value = sharedPreferences.getBoolean(Keys.IS_CONNECTED, false)
|
||||
updateConfiguredState()
|
||||
}
|
||||
|
||||
private fun updateConfiguredState() {
|
||||
val url = serverUrl
|
||||
val token = authToken
|
||||
_isConfigured.value = url.isNotBlank() && token.isNotBlank()
|
||||
}
|
||||
|
||||
var serverUrl: String
|
||||
get() = sharedPreferences.getString(Keys.SERVER_URL, "") ?: ""
|
||||
set(value) {
|
||||
sharedPreferences.edit().putString(Keys.SERVER_URL, value).apply()
|
||||
updateConfiguredState()
|
||||
}
|
||||
|
||||
var authToken: String
|
||||
get() = sharedPreferences.getString(Keys.AUTH_TOKEN, "") ?: ""
|
||||
set(value) {
|
||||
sharedPreferences.edit().putString(Keys.AUTH_TOKEN, value).apply()
|
||||
updateConfiguredState()
|
||||
}
|
||||
|
||||
private fun isNetworkAvailable(): Boolean {
|
||||
val connectivityManager =
|
||||
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val network = connectivityManager.activeNetwork ?: return false
|
||||
val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
|
||||
|
||||
return when {
|
||||
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
|
||||
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
|
||||
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun sync() = withContext(Dispatchers.IO) {
|
||||
if (isOfflineMode) {
|
||||
AppLogger.i(TAG) { "Sync skipped: Offline mode is enabled." }
|
||||
return@withContext
|
||||
}
|
||||
|
||||
if (!isConfigured.value) {
|
||||
throw SyncException.NotConfigured
|
||||
}
|
||||
|
||||
if (!isNetworkAvailable()) {
|
||||
throw SyncException.NotConnected
|
||||
}
|
||||
|
||||
val lastSyncTimeStr = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
||||
|
||||
if (lastSyncTimeStr != null) {
|
||||
AppLogger.i(TAG) { "Last sync time found ($lastSyncTimeStr), attempting delta sync" }
|
||||
try {
|
||||
performDeltaSync()
|
||||
sharedPreferences.edit()
|
||||
.putString(Keys.LAST_SYNC_TIME, DateFormatUtils.nowISO8601())
|
||||
.apply()
|
||||
return@withContext
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Delta sync failed, falling back to full sync check: ${e.message}" }
|
||||
}
|
||||
}
|
||||
|
||||
val localBackup = createBackupFromRepository()
|
||||
val serverBackup = try {
|
||||
downloadData()
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Failed to download data: ${e.message}" }
|
||||
throw e
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
if (!hasLocalData && hasServerData) {
|
||||
AppLogger.i(TAG) { "Performing full restore from server" }
|
||||
AppLogger.i(TAG) { "Syncing images from server first..." }
|
||||
val imagePathMapping = syncImagesFromServer(serverBackup)
|
||||
|
||||
AppLogger.i(TAG) { "Importing data after images..." }
|
||||
importBackupToRepository(serverBackup, imagePathMapping)
|
||||
AppLogger.i(TAG) { "Full restore completed" }
|
||||
} else if (hasLocalData && !hasServerData) {
|
||||
AppLogger.i(TAG) { "Uploading local data to server" }
|
||||
uploadData(localBackup)
|
||||
AppLogger.i(TAG) { "Uploading local images to server..." }
|
||||
syncImagesToServer()
|
||||
AppLogger.i(TAG) { "Initial upload completed" }
|
||||
} else if (hasLocalData && hasServerData) {
|
||||
AppLogger.i(TAG) { "Merging local and server data" }
|
||||
mergeDataSafely(localBackup, serverBackup)
|
||||
AppLogger.i(TAG) { "Safe merge completed" }
|
||||
} else {
|
||||
AppLogger.i(TAG) { "No data to sync" }
|
||||
}
|
||||
|
||||
sharedPreferences.edit()
|
||||
.putString(Keys.LAST_SYNC_TIME, DateFormatUtils.nowISO8601())
|
||||
.apply()
|
||||
}
|
||||
|
||||
override fun disconnect() {
|
||||
_isConnected.value = false
|
||||
sharedPreferences.edit()
|
||||
.remove(Keys.LAST_SYNC_TIME)
|
||||
.putBoolean(Keys.IS_CONNECTED, false)
|
||||
.apply()
|
||||
}
|
||||
|
||||
private suspend fun performDeltaSync() {
|
||||
val lastSyncTimeStr = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
||||
?: throw SyncException.General("No last sync time for delta sync")
|
||||
|
||||
val lastSyncDate = parseISO8601(lastSyncTimeStr) ?: Instant.EPOCH
|
||||
|
||||
val allGyms = repository.getAllGymsSync()
|
||||
val modifiedGyms = allGyms.filter {
|
||||
(parseISO8601(it.updatedAt) ?: Instant.MIN).isAfter(lastSyncDate)
|
||||
}.map { BackupGym.fromGym(it) }.toMutableList()
|
||||
|
||||
val allProblems = repository.getAllProblemsSync()
|
||||
val modifiedProblems = allProblems.filter {
|
||||
(parseISO8601(it.updatedAt) ?: Instant.MIN).isAfter(lastSyncDate)
|
||||
}.map { problem ->
|
||||
val backupProblem = BackupProblem.fromProblem(problem)
|
||||
if (!problem.imagePaths.isEmpty()) {
|
||||
val normalizedPaths = problem.imagePaths.mapIndexed { index, _ ->
|
||||
"${problem.id}_${index}.jpg"
|
||||
}
|
||||
backupProblem.withUpdatedImagePaths(normalizedPaths)
|
||||
} else {
|
||||
backupProblem
|
||||
}
|
||||
}.toMutableList()
|
||||
|
||||
val allSessions = repository.getAllSessionsSync()
|
||||
val modifiedSessions = allSessions.filter {
|
||||
(parseISO8601(it.updatedAt) ?: Instant.MIN).isAfter(lastSyncDate)
|
||||
}.map { BackupClimbSession.fromClimbSession(it) }.toMutableList()
|
||||
|
||||
val allAttempts = repository.getAllAttemptsSync()
|
||||
val modifiedAttempts = allAttempts.filter {
|
||||
val updated = it.updatedAt
|
||||
(parseISO8601(updated) ?: Instant.MIN).isAfter(lastSyncDate)
|
||||
}.map { BackupAttempt.fromAttempt(it) }.toMutableList()
|
||||
|
||||
val deletedItems = repository.getDeletedItems().filter {
|
||||
val deletedAt = parseISO8601(it.deletedAt) ?: Instant.MIN
|
||||
deletedAt.isAfter(lastSyncDate)
|
||||
}
|
||||
|
||||
for (item in deletedItems) {
|
||||
when (item.type) {
|
||||
"gym" -> modifiedGyms.add(BackupGym.createTombstone(item.id, item.deletedAt))
|
||||
"problem" -> modifiedProblems.add(BackupProblem.createTombstone(item.id, item.deletedAt))
|
||||
"session" -> modifiedSessions.add(BackupClimbSession.createTombstone(item.id, item.deletedAt))
|
||||
"attempt" -> modifiedAttempts.add(BackupAttempt.createTombstone(item.id, item.deletedAt))
|
||||
}
|
||||
}
|
||||
|
||||
AppLogger.i(TAG) { "Delta Sync: Sending gyms=${modifiedGyms.size}, problems=${modifiedProblems.size}, sessions=${modifiedSessions.size}, attempts=${modifiedAttempts.size}" }
|
||||
|
||||
val deltaRequest = DeltaSyncRequest(
|
||||
lastSyncTime = lastSyncTimeStr,
|
||||
gyms = modifiedGyms,
|
||||
problems = modifiedProblems,
|
||||
sessions = modifiedSessions,
|
||||
attempts = modifiedAttempts
|
||||
)
|
||||
|
||||
val requestBody = json.encodeToString(DeltaSyncRequest.serializer(), deltaRequest)
|
||||
.toRequestBody("application/json".toMediaType())
|
||||
|
||||
val request = Request.Builder()
|
||||
.url("$serverUrl/sync/delta")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.post(requestBody)
|
||||
.build()
|
||||
|
||||
val response = withContext(Dispatchers.IO) {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
if (response.code == 401) throw SyncException.Unauthorized
|
||||
throw SyncException.ServerError(response.code)
|
||||
}
|
||||
val body = response.body?.string() ?: throw SyncException.InvalidResponse("Empty response")
|
||||
json.decodeFromString<DeltaSyncResponse>(body)
|
||||
}
|
||||
}
|
||||
|
||||
if (response.requestFullSync) {
|
||||
throw SyncException.General("Server requested full sync")
|
||||
}
|
||||
|
||||
AppLogger.i(TAG) { "Delta Sync: Received gyms=${response.gyms.size}, problems=${response.problems.size}, sessions=${response.sessions.size}, attempts=${response.attempts.size}" }
|
||||
|
||||
applyDeltaResponse(response)
|
||||
syncModifiedImages(modifiedProblems)
|
||||
|
||||
repository.clearDeletedItems()
|
||||
|
||||
sharedPreferences.edit()
|
||||
.putString(Keys.LAST_SYNC_TIME, response.serverTime)
|
||||
.apply()
|
||||
}
|
||||
|
||||
private fun parseISO8601(dateStr: String?): Instant? {
|
||||
if (dateStr == null) return null
|
||||
return try {
|
||||
Instant.parse(dateStr)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyDeltaResponse(response: DeltaSyncResponse) {
|
||||
val imagePathMapping = mutableMapOf<String, String>()
|
||||
for (problem in response.problems) {
|
||||
if (problem.isDeleted) continue
|
||||
|
||||
val paths = problem.imagePaths ?: continue
|
||||
for ((index, path) in paths.withIndex()) {
|
||||
val serverFilename = path.substringAfterLast('/')
|
||||
try {
|
||||
val imageData = downloadImage(serverFilename)
|
||||
val localFilename = "${problem.id}_${index}.jpg"
|
||||
saveImageLocally(localFilename, imageData)
|
||||
imagePathMapping[serverFilename] = localFilename
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Failed to download image $serverFilename: ${e.message}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (gym in response.gyms) {
|
||||
if (gym.isDeleted) {
|
||||
val serverUpdate = parseISO8601(gym.updatedAt) ?: Instant.MAX
|
||||
val existing = repository.getGymById(gym.id)
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate) || serverUpdate == localUpdate) {
|
||||
repository.deleteGym(existing)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
val existing = repository.getGymById(gym.id)
|
||||
val serverUpdate = parseISO8601(gym.updatedAt) ?: Instant.MIN
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate)) {
|
||||
repository.updateGym(gym.toGym())
|
||||
}
|
||||
} else {
|
||||
repository.insertGym(gym.toGym())
|
||||
}
|
||||
}
|
||||
|
||||
for (problem in response.problems) {
|
||||
if (problem.isDeleted) {
|
||||
val serverUpdate = parseISO8601(problem.updatedAt) ?: Instant.MAX
|
||||
val existing = repository.getProblemById(problem.id)
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate) || serverUpdate == localUpdate) {
|
||||
repository.deleteProblem(existing)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
var problemToMerge = problem
|
||||
if (imagePathMapping.isNotEmpty() && !problem.imagePaths.isNullOrEmpty()) {
|
||||
val updatedPaths = problem.imagePaths.map { imagePathMapping[it.substringAfterLast('/')] ?: it }
|
||||
problemToMerge = problem.withUpdatedImagePaths(updatedPaths)
|
||||
}
|
||||
|
||||
val existing = repository.getProblemById(problem.id)
|
||||
val serverUpdate = parseISO8601(problem.updatedAt) ?: Instant.MIN
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate)) {
|
||||
repository.updateProblem(problemToMerge.toProblem())
|
||||
}
|
||||
} else {
|
||||
repository.insertProblem(problemToMerge.toProblem())
|
||||
}
|
||||
}
|
||||
|
||||
for (session in response.sessions) {
|
||||
if (session.isDeleted) {
|
||||
val serverUpdate = parseISO8601(session.updatedAt) ?: Instant.MAX
|
||||
val existing = repository.getSessionById(session.id)
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate) || serverUpdate == localUpdate) {
|
||||
repository.deleteSession(existing)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
val existing = repository.getSessionById(session.id)
|
||||
val serverUpdate = parseISO8601(session.updatedAt) ?: Instant.MIN
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate)) {
|
||||
repository.updateSession(session.toClimbSession())
|
||||
}
|
||||
} else {
|
||||
repository.insertSession(session.toClimbSession())
|
||||
}
|
||||
}
|
||||
|
||||
for (attempt in response.attempts) {
|
||||
if (attempt.isDeleted) {
|
||||
val serverUpdate = parseISO8601(attempt.updatedAt ?: attempt.createdAt) ?: Instant.MAX
|
||||
val existing = repository.getAttemptById(attempt.id)
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate) || serverUpdate == localUpdate) {
|
||||
repository.deleteAttempt(existing)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
val existing = repository.getAttemptById(attempt.id)
|
||||
val serverUpdate = parseISO8601(attempt.updatedAt ?: attempt.createdAt) ?: Instant.MIN
|
||||
if (existing != null) {
|
||||
val localUpdate = parseISO8601(existing.updatedAt) ?: Instant.MIN
|
||||
if (serverUpdate.isAfter(localUpdate)) {
|
||||
repository.updateAttempt(attempt.toAttempt())
|
||||
}
|
||||
} else {
|
||||
repository.insertAttempt(attempt.toAttempt())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun syncModifiedImages(modifiedProblems: List<BackupProblem>) {
|
||||
for (problem in modifiedProblems) {
|
||||
if (problem.isDeleted) continue
|
||||
val paths = problem.imagePaths ?: continue
|
||||
for (path in paths) {
|
||||
val localFile = getLocalImageFile(path)
|
||||
if (localFile != null && localFile.exists()) {
|
||||
try {
|
||||
uploadImage(path, localFile.readBytes())
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Failed to upload image $path: ${e.message}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getLocalImageFile(filename: String): File? {
|
||||
val dir = context.getExternalFilesDir("images") ?: return null
|
||||
return File(dir, filename)
|
||||
}
|
||||
|
||||
private fun saveImageLocally(filename: String, data: ByteArray) {
|
||||
val dir = context.getExternalFilesDir("images") ?: return
|
||||
if (!dir.exists()) dir.mkdirs()
|
||||
File(dir, filename).writeBytes(data)
|
||||
}
|
||||
|
||||
private suspend fun downloadData(): ClimbDataBackup {
|
||||
val request = Request.Builder()
|
||||
.url("$serverUrl/sync")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
return withContext(Dispatchers.IO) {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
if (response.code == 401) throw SyncException.Unauthorized
|
||||
throw SyncException.ServerError(response.code)
|
||||
}
|
||||
val body = response.body?.string() ?: throw SyncException.InvalidResponse("Empty body")
|
||||
json.decodeFromString<ClimbDataBackup>(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun uploadData(backup: ClimbDataBackup) {
|
||||
val requestBody = json.encodeToString(backup).toRequestBody("application/json".toMediaType())
|
||||
val request = Request.Builder()
|
||||
.url("$serverUrl/sync")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.put(requestBody)
|
||||
.build()
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
if (response.code == 401) throw SyncException.Unauthorized
|
||||
throw SyncException.ServerError(response.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun syncImagesFromServer(backup: ClimbDataBackup): Map<String, String> {
|
||||
val mapping = mutableMapOf<String, String>()
|
||||
for (problem in backup.problems) {
|
||||
if (problem.isDeleted) continue
|
||||
val paths = problem.imagePaths ?: continue
|
||||
for ((index, path) in paths.withIndex()) {
|
||||
val serverFilename = path.substringAfterLast('/')
|
||||
try {
|
||||
val imageData = downloadImage(serverFilename)
|
||||
val localFilename = "${problem.id}_${index}.jpg"
|
||||
saveImageLocally(localFilename, imageData)
|
||||
mapping[serverFilename] = localFilename
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to sync image $serverFilename", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
return mapping
|
||||
}
|
||||
|
||||
private suspend fun syncImagesToServer() {
|
||||
val problems = repository.getAllProblemsSync()
|
||||
for (problem in problems) {
|
||||
for (path in problem.imagePaths) {
|
||||
val file = getLocalImageFile(path)
|
||||
if (file != null && file.exists()) {
|
||||
try {
|
||||
uploadImage(path, file.readBytes())
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to upload image $path", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun downloadImage(filename: String): ByteArray {
|
||||
val request = Request.Builder()
|
||||
.url("$serverUrl/images/download?filename=$filename")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.build()
|
||||
|
||||
return withContext(Dispatchers.IO) {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
if (response.code == 404) throw SyncException.ImageNotFound
|
||||
throw SyncException.ServerError(response.code)
|
||||
}
|
||||
response.body?.bytes() ?: throw SyncException.InvalidResponse("Empty image body")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun uploadImage(filename: String, data: ByteArray) {
|
||||
val requestBody = data.toRequestBody("application/octet-stream".toMediaType())
|
||||
val request = Request.Builder()
|
||||
.url("$serverUrl/images/upload?filename=$filename")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.post(requestBody)
|
||||
.build()
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
throw SyncException.ServerError(response.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun createBackupFromRepository(): ClimbDataBackup {
|
||||
val gyms = repository.getAllGymsSync().map { BackupGym.fromGym(it) }
|
||||
val problems = repository.getAllProblemsSync().map { BackupProblem.fromProblem(it) }
|
||||
val sessions = repository.getAllSessionsSync().map { BackupClimbSession.fromClimbSession(it) }
|
||||
val attempts = repository.getAllAttemptsSync().map { BackupAttempt.fromAttempt(it) }
|
||||
|
||||
return ClimbDataBackup(
|
||||
exportedAt = DateFormatUtils.nowISO8601(),
|
||||
gyms = gyms,
|
||||
problems = problems,
|
||||
sessions = sessions,
|
||||
attempts = attempts
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun importBackupToRepository(backup: ClimbDataBackup, imagePathMapping: Map<String, String>) {
|
||||
for (gym in backup.gyms) {
|
||||
if (!gym.isDeleted) repository.insertGym(gym.toGym())
|
||||
}
|
||||
|
||||
for (problem in backup.problems) {
|
||||
if (!problem.isDeleted) {
|
||||
var p = problem
|
||||
if (imagePathMapping.isNotEmpty() && !problem.imagePaths.isNullOrEmpty()) {
|
||||
val updatedPaths = problem.imagePaths.map { imagePathMapping[it.substringAfterLast('/')] ?: it }
|
||||
p = problem.withUpdatedImagePaths(updatedPaths)
|
||||
}
|
||||
repository.insertProblem(p.toProblem())
|
||||
}
|
||||
}
|
||||
|
||||
for (session in backup.sessions) {
|
||||
if (!session.isDeleted) repository.insertSession(session.toClimbSession())
|
||||
}
|
||||
|
||||
for (attempt in backup.attempts) {
|
||||
if (!attempt.isDeleted) repository.insertAttempt(attempt.toAttempt())
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun mergeDataSafely(local: ClimbDataBackup, server: ClimbDataBackup) {
|
||||
val deltaResponse = DeltaSyncResponse(
|
||||
serverTime = server.exportedAt,
|
||||
gyms = server.gyms,
|
||||
problems = server.problems,
|
||||
sessions = server.sessions,
|
||||
attempts = server.attempts,
|
||||
)
|
||||
applyDeltaResponse(deltaResponse)
|
||||
}
|
||||
|
||||
override suspend fun testConnection() {
|
||||
if (!isConfigured.value) throw SyncException.NotConfigured
|
||||
|
||||
val request = Request.Builder()
|
||||
.url("$serverUrl/health")
|
||||
.apply {
|
||||
if (authToken.isNotBlank()) header("Authorization", "Bearer $authToken")
|
||||
}
|
||||
.head() // Using HEAD as originally, or GET
|
||||
.build()
|
||||
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful && response.code != 405) {
|
||||
throw SyncException.ServerError(response.code)
|
||||
}
|
||||
_isConnected.value = true
|
||||
sharedPreferences.edit().putBoolean(Keys.IS_CONNECTED, true).apply()
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_isConnected.value = false
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.atridad.ascently.data.sync
|
||||
|
||||
import com.atridad.ascently.data.format.BackupAttempt
|
||||
import com.atridad.ascently.data.format.BackupClimbSession
|
||||
import com.atridad.ascently.data.format.BackupGym
|
||||
import com.atridad.ascently.data.format.BackupProblem
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** Request structure for delta sync - sends only changes since last sync */
|
||||
@Serializable
|
||||
data class DeltaSyncRequest(
|
||||
val lastSyncTime: String,
|
||||
val gyms: List<BackupGym>,
|
||||
val problems: List<BackupProblem>,
|
||||
val sessions: List<BackupClimbSession>,
|
||||
val attempts: List<BackupAttempt>,
|
||||
)
|
||||
|
||||
/** Response structure for delta sync - receives only changes from server */
|
||||
@Serializable
|
||||
data class DeltaSyncResponse(
|
||||
val serverTime: String,
|
||||
val requestFullSync: Boolean = false,
|
||||
val gyms: List<BackupGym>,
|
||||
val problems: List<BackupProblem>,
|
||||
val sessions: List<BackupClimbSession>,
|
||||
val attempts: List<BackupAttempt>,
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.atridad.ascently.data.sync
|
||||
|
||||
import java.io.IOException
|
||||
import java.io.Serializable
|
||||
|
||||
sealed class SyncException(message: String) : IOException(message), Serializable {
|
||||
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.")
|
||||
|
||||
object ImageNotFound : SyncException("Image not found on server")
|
||||
|
||||
data class ServerError(val code: Int) : SyncException("Server error: HTTP $code")
|
||||
data class InvalidResponse(val details: String) :
|
||||
SyncException("Invalid server response: $details")
|
||||
|
||||
data class NetworkError(val details: String) : SyncException("Network error: $details")
|
||||
|
||||
data class General(val details: String) : SyncException(details)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.atridad.ascently.data.sync
|
||||
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
interface SyncProvider {
|
||||
val type: SyncProviderType
|
||||
val isConfigured: StateFlow<Boolean>
|
||||
val isConnected: StateFlow<Boolean>
|
||||
|
||||
suspend fun sync()
|
||||
suspend fun testConnection()
|
||||
fun disconnect()
|
||||
}
|
||||
|
||||
enum class SyncProviderType {
|
||||
NONE,
|
||||
SERVER,
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.atridad.ascently.data.sync
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.core.content.edit
|
||||
import com.atridad.ascently.data.repository.ClimbRepository
|
||||
import com.atridad.ascently.data.state.DataStateManager
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class SyncService(private val context: Context, private val repository: ClimbRepository) {
|
||||
|
||||
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
private val syncMutex = Mutex()
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SyncService"
|
||||
}
|
||||
|
||||
// Currently we only support one provider, but this allows for future expansion
|
||||
private val provider: SyncProvider = AscentlySyncProvider(context, repository, DataStateManager(context))
|
||||
|
||||
// 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()
|
||||
|
||||
// Delegate to provider
|
||||
val isConnected: StateFlow<Boolean> = provider.isConnected
|
||||
val isConfiguredFlow: StateFlow<Boolean> = provider.isConfigured
|
||||
|
||||
private val _isTesting = MutableStateFlow(false)
|
||||
val isTesting: StateFlow<Boolean> = _isTesting.asStateFlow()
|
||||
|
||||
private val _isAutoSyncEnabled = MutableStateFlow(true)
|
||||
val isAutoSyncEnabled: StateFlow<Boolean> = _isAutoSyncEnabled.asStateFlow()
|
||||
|
||||
// Debounced sync properties
|
||||
private var syncJob: Job? = null
|
||||
private var pendingChanges = false
|
||||
private val syncDebounceDelay = 2000L // 2 seconds
|
||||
|
||||
private val sharedPreferences: SharedPreferences =
|
||||
context.getSharedPreferences("sync_preferences", Context.MODE_PRIVATE)
|
||||
|
||||
private object Keys {
|
||||
const val LAST_SYNC_TIME = "last_sync_time"
|
||||
const val AUTO_SYNC_ENABLED = "auto_sync_enabled"
|
||||
}
|
||||
|
||||
init {
|
||||
loadInitialState()
|
||||
repository.setAutoSyncCallback { serviceScope.launch { triggerAutoSync() } }
|
||||
}
|
||||
|
||||
private fun loadInitialState() {
|
||||
_lastSyncTime.value = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
||||
_isAutoSyncEnabled.value = sharedPreferences.getBoolean(Keys.AUTO_SYNC_ENABLED, true)
|
||||
}
|
||||
|
||||
// Proxy properties for Ascently provider configuration
|
||||
var serverUrl: String
|
||||
get() = (provider as? AscentlySyncProvider)?.serverUrl ?: ""
|
||||
set(value) {
|
||||
(provider as? AscentlySyncProvider)?.serverUrl = value
|
||||
}
|
||||
|
||||
var authToken: String
|
||||
get() = (provider as? AscentlySyncProvider)?.authToken ?: ""
|
||||
set(value) {
|
||||
(provider as? AscentlySyncProvider)?.authToken = value
|
||||
}
|
||||
|
||||
fun setAutoSyncEnabled(enabled: Boolean) {
|
||||
_isAutoSyncEnabled.value = enabled
|
||||
sharedPreferences.edit { putBoolean(Keys.AUTO_SYNC_ENABLED, enabled) }
|
||||
}
|
||||
|
||||
suspend fun syncWithServer() {
|
||||
if (!isConfiguredFlow.value) {
|
||||
throw SyncException.NotConfigured
|
||||
}
|
||||
|
||||
syncMutex.withLock {
|
||||
_isSyncing.value = true
|
||||
_syncError.value = null
|
||||
|
||||
try {
|
||||
provider.sync()
|
||||
|
||||
// Update last sync time from shared prefs (provider updates it)
|
||||
_lastSyncTime.value = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
||||
} catch (e: Exception) {
|
||||
_syncError.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
_isSyncing.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun testConnection() {
|
||||
_isTesting.value = true
|
||||
_syncError.value = null
|
||||
try {
|
||||
provider.testConnection()
|
||||
} catch (e: Exception) {
|
||||
_syncError.value = "Connection error: ${e.message}"
|
||||
throw e
|
||||
} finally {
|
||||
_isTesting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
fun triggerAutoSync() {
|
||||
if (!isConfiguredFlow.value || !isConnected.value || !_isAutoSyncEnabled.value) {
|
||||
return
|
||||
}
|
||||
if (_isSyncing.value) {
|
||||
pendingChanges = true
|
||||
return
|
||||
}
|
||||
syncJob?.cancel()
|
||||
syncJob =
|
||||
serviceScope.launch {
|
||||
delay(syncDebounceDelay)
|
||||
try {
|
||||
syncWithServer()
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(TAG, e) { "Auto-sync failed" }
|
||||
}
|
||||
if (pendingChanges) {
|
||||
pendingChanges = false
|
||||
triggerAutoSync()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearConfiguration() {
|
||||
syncJob?.cancel()
|
||||
provider.disconnect()
|
||||
setAutoSyncEnabled(true)
|
||||
_lastSyncTime.value = null
|
||||
_syncError.value = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.atridad.ascently.navigation
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
|
||||
data class BottomNavigationItem(val screen: Screen, val icon: ImageVector, val label: String)
|
||||
|
||||
val bottomNavigationItems =
|
||||
listOf(
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Sessions,
|
||||
icon = Icons.Default.PlayArrow,
|
||||
label = "Sessions",
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Problems,
|
||||
icon = Icons.Default.Star,
|
||||
label = "Problems",
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Analytics,
|
||||
icon = Icons.Default.Info,
|
||||
label = "Analytics",
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Gyms,
|
||||
icon = Icons.Default.LocationOn,
|
||||
label = "Gyms",
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Settings,
|
||||
icon = Icons.Default.Settings,
|
||||
label = "Settings",
|
||||
),
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.navigation
|
||||
package com.atridad.ascently.navigation
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
package com.atridad.ascently.service
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.atridad.ascently.MainActivity
|
||||
import com.atridad.ascently.R
|
||||
import com.atridad.ascently.data.database.AscentlyDatabase
|
||||
import com.atridad.ascently.data.repository.ClimbRepository
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import com.atridad.ascently.widget.ClimbStatsWidgetProvider
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.firstOrNull
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
class SessionTrackingService : Service() {
|
||||
|
||||
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
private var notificationJob: Job? = null
|
||||
private var monitoringJob: Job? = null
|
||||
|
||||
private lateinit var repository: ClimbRepository
|
||||
private lateinit var notificationManager: NotificationManager
|
||||
|
||||
companion object {
|
||||
private const val LOG_TAG = "SessionTrackingService"
|
||||
const val NOTIFICATION_ID = 1001
|
||||
const val CHANNEL_ID = "session_tracking_channel"
|
||||
const val ACTION_START_SESSION = "start_session"
|
||||
const val ACTION_STOP_SESSION = "stop_session"
|
||||
const val EXTRA_SESSION_ID = "session_id"
|
||||
|
||||
fun createStartIntent(context: Context, sessionId: String): Intent {
|
||||
return Intent(context, SessionTrackingService::class.java).apply {
|
||||
action = ACTION_START_SESSION
|
||||
putExtra(EXTRA_SESSION_ID, sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
fun createStopIntent(context: Context, sessionId: String): Intent {
|
||||
return Intent(context, SessionTrackingService::class.java).apply {
|
||||
action = ACTION_STOP_SESSION
|
||||
putExtra(EXTRA_SESSION_ID, sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
val database = AscentlyDatabase.getDatabase(this)
|
||||
repository = ClimbRepository(database, this)
|
||||
notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_START_SESSION -> {
|
||||
val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)
|
||||
if (sessionId != null) {
|
||||
startSessionTracking(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
ACTION_STOP_SESSION -> {
|
||||
val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)
|
||||
serviceScope.launch {
|
||||
try {
|
||||
val targetSession =
|
||||
when {
|
||||
sessionId != null -> repository.getSessionById(sessionId)
|
||||
else -> repository.getActiveSession()
|
||||
}
|
||||
if (targetSession != null &&
|
||||
targetSession.status ==
|
||||
com.atridad.ascently.data.model.SessionStatus.ACTIVE
|
||||
) {
|
||||
val completed =
|
||||
with(com.atridad.ascently.data.model.ClimbSession) {
|
||||
targetSession.complete()
|
||||
}
|
||||
repository.updateSession(completed)
|
||||
}
|
||||
} finally {
|
||||
stopSessionTracking()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return START_REDELIVER_INTENT
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun startSessionTracking(sessionId: String) {
|
||||
notificationJob?.cancel()
|
||||
monitoringJob?.cancel()
|
||||
|
||||
try {
|
||||
createAndShowNotification(sessionId)
|
||||
// Update widget when session tracking starts
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(this)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(LOG_TAG, e) { "Failed to initialize session tracking notification" }
|
||||
}
|
||||
|
||||
notificationJob =
|
||||
serviceScope.launch {
|
||||
try {
|
||||
if (!isNotificationActive()) {
|
||||
delay(1000L)
|
||||
createAndShowNotification(sessionId)
|
||||
}
|
||||
|
||||
while (isActive) {
|
||||
delay(5000L)
|
||||
updateNotification(sessionId)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(LOG_TAG, e) { "Notification updater loop crashed" }
|
||||
}
|
||||
}
|
||||
|
||||
monitoringJob =
|
||||
serviceScope.launch {
|
||||
try {
|
||||
while (isActive) {
|
||||
delay(10000L)
|
||||
|
||||
if (!isNotificationActive()) {
|
||||
updateNotification(sessionId)
|
||||
}
|
||||
|
||||
val session = repository.getSessionById(sessionId)
|
||||
if (session == null ||
|
||||
session.status !=
|
||||
com.atridad.ascently.data.model.SessionStatus
|
||||
.ACTIVE
|
||||
) {
|
||||
stopSessionTracking()
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(LOG_TAG, e) { "Session monitoring loop crashed" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopSessionTracking() {
|
||||
notificationJob?.cancel()
|
||||
monitoringJob?.cancel()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
// Update widget when session tracking stops
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(this)
|
||||
}
|
||||
|
||||
private fun isNotificationActive(): Boolean {
|
||||
return try {
|
||||
val activeNotifications = notificationManager.activeNotifications
|
||||
activeNotifications.any { it.id == NOTIFICATION_ID }
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun updateNotification(sessionId: String) {
|
||||
try {
|
||||
createAndShowNotification(sessionId)
|
||||
// Update widget when notification updates
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(this)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(LOG_TAG, e) { "Failed to update notification; retrying in 10s" }
|
||||
|
||||
try {
|
||||
delay(10000L)
|
||||
createAndShowNotification(sessionId)
|
||||
} catch (retryException: Exception) {
|
||||
AppLogger.e(LOG_TAG, retryException) { "Retrying notification update failed" }
|
||||
stopSessionTracking()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createAndShowNotification(sessionId: String) {
|
||||
try {
|
||||
val session = runBlocking { repository.getSessionById(sessionId) }
|
||||
if (session == null ||
|
||||
session.status != com.atridad.ascently.data.model.SessionStatus.ACTIVE
|
||||
) {
|
||||
stopSessionTracking()
|
||||
return
|
||||
}
|
||||
|
||||
val gym = runBlocking { repository.getGymById(session.gymId) }
|
||||
|
||||
val attempts = runBlocking {
|
||||
repository.getAttemptsBySession(sessionId).firstOrNull() ?: emptyList()
|
||||
}
|
||||
|
||||
val notificationBuilder =
|
||||
NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_mountains)
|
||||
.setOngoing(true)
|
||||
.setAutoCancel(false)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setCategory(NotificationCompat.CATEGORY_SERVICE)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(createOpenAppIntent())
|
||||
.addAction(
|
||||
R.drawable.ic_mountains,
|
||||
"Open Session",
|
||||
createOpenAppIntent(),
|
||||
)
|
||||
.addAction(
|
||||
android.R.drawable.ic_menu_close_clear_cancel,
|
||||
"End Session",
|
||||
createStopPendingIntent(sessionId),
|
||||
)
|
||||
|
||||
// Use Live Update
|
||||
if (Build.VERSION.SDK_INT >= 36) {
|
||||
val startTimeMillis =
|
||||
session.startTime?.let { startTime ->
|
||||
try {
|
||||
DateFormatUtils.parseISO8601(startTime)?.toEpochMilli()
|
||||
?: System.currentTimeMillis()
|
||||
} catch (_: Exception) {
|
||||
System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
?: System.currentTimeMillis()
|
||||
|
||||
notificationBuilder
|
||||
.setContentTitle("Climbing Session Active")
|
||||
.setContentText(
|
||||
"${gym?.name ?: "Gym"} • ${attempts.size} attempts",
|
||||
)
|
||||
.setWhen(startTimeMillis)
|
||||
.setUsesChronometer(true)
|
||||
.setShowWhen(true)
|
||||
|
||||
val extras = Bundle()
|
||||
extras.putBoolean("android.extra.REQUEST_PROMOTED_ONGOING", true)
|
||||
notificationBuilder.setExtras(extras)
|
||||
} else {
|
||||
// Fallback for older versions
|
||||
val duration =
|
||||
session.startTime?.let { startTime ->
|
||||
try {
|
||||
val start = DateFormatUtils.parseISO8601(startTime)
|
||||
val now = java.time.Instant.now()
|
||||
val totalSeconds = if (start != null) ChronoUnit.SECONDS.between(start, now) else 0L
|
||||
val hours = totalSeconds / 3600
|
||||
val minutes = (totalSeconds % 3600) / 60
|
||||
val seconds = totalSeconds % 60
|
||||
|
||||
when {
|
||||
hours > 0 -> "${hours}h ${minutes}m ${seconds}s"
|
||||
minutes > 0 -> "${minutes}m ${seconds}s"
|
||||
else -> "${totalSeconds}s"
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
"Active"
|
||||
}
|
||||
}
|
||||
?: "Active"
|
||||
|
||||
notificationBuilder
|
||||
.setContentTitle("Climbing Session Active")
|
||||
.setContentText(
|
||||
"${gym?.name ?: "Gym"} • $duration • ${attempts.size} attempts",
|
||||
)
|
||||
}
|
||||
|
||||
val notification = notificationBuilder.build()
|
||||
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
|
||||
notificationManager.notify(NOTIFICATION_ID, notification)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e(LOG_TAG, e) { "Failed to build session tracking notification" }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun createOpenAppIntent(): PendingIntent {
|
||||
val intent =
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
action = "OPEN_SESSION"
|
||||
}
|
||||
return PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
}
|
||||
|
||||
private fun createStopPendingIntent(sessionId: String): PendingIntent {
|
||||
val intent = createStopIntent(this, sessionId)
|
||||
return PendingIntent.getService(
|
||||
this,
|
||||
1,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
}
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val channel =
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Session Tracking",
|
||||
NotificationManager.IMPORTANCE_DEFAULT,
|
||||
)
|
||||
.apply {
|
||||
description = "Shows active climbing session information"
|
||||
setShowBadge(false)
|
||||
lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
|
||||
enableLights(false)
|
||||
enableVibration(false)
|
||||
setSound(null, null)
|
||||
}
|
||||
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
notificationJob?.cancel()
|
||||
monitoringJob?.cancel()
|
||||
serviceScope.cancel()
|
||||
}
|
||||
}
|
||||
390
android/app/src/main/java/com/atridad/ascently/ui/AscentlyApp.kt
Normal file
390
android/app/src/main/java/com/atridad/ascently/ui/AscentlyApp.kt
Normal file
@@ -0,0 +1,390 @@
|
||||
package com.atridad.ascently.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.NavHostController
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import androidx.navigation.toRoute
|
||||
import com.atridad.ascently.data.database.AscentlyDatabase
|
||||
import com.atridad.ascently.data.repository.ClimbRepository
|
||||
import com.atridad.ascently.data.sync.SyncService
|
||||
import com.atridad.ascently.navigation.Screen
|
||||
import com.atridad.ascently.navigation.bottomNavigationItems
|
||||
import com.atridad.ascently.ui.components.NotificationPermissionDialog
|
||||
import com.atridad.ascently.ui.screens.*
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModelFactory
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import com.atridad.ascently.utils.AppShortcutManager
|
||||
import com.atridad.ascently.utils.NotificationPermissionUtils
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AscentlyApp(
|
||||
shortcutAction: String? = null,
|
||||
lastUsedGymId: String? = null,
|
||||
onShortcutActionProcessed: () -> Unit = {},
|
||||
) {
|
||||
val navController = rememberNavController()
|
||||
val context = LocalContext.current
|
||||
|
||||
var lastUsedGym by remember { mutableStateOf<com.atridad.ascently.data.model.Gym?>(null) }
|
||||
|
||||
val database = remember { AscentlyDatabase.getDatabase(context) }
|
||||
val repository = remember { ClimbRepository(database, context) }
|
||||
val syncService = remember { SyncService(context, repository) }
|
||||
val viewModel: ClimbViewModel =
|
||||
viewModel(factory = ClimbViewModelFactory(repository, syncService, context))
|
||||
|
||||
var showNotificationPermissionDialog by remember { mutableStateOf(false) }
|
||||
var hasCheckedNotificationPermission by remember { mutableStateOf(false) }
|
||||
|
||||
val permissionLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
) { isGranted: Boolean ->
|
||||
if (!isGranted) {
|
||||
showNotificationPermissionDialog = false
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (!hasCheckedNotificationPermission) {
|
||||
hasCheckedNotificationPermission = true
|
||||
|
||||
if (NotificationPermissionUtils.shouldRequestNotificationPermission() &&
|
||||
!NotificationPermissionUtils.isNotificationPermissionGranted(context)
|
||||
) {
|
||||
showNotificationPermissionDialog = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) { viewModel.ensureSessionTrackingServiceRunning(context) }
|
||||
|
||||
LaunchedEffect(Unit) { syncService.triggerAutoSync() }
|
||||
|
||||
val activeSession by viewModel.activeSession.collectAsState()
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
|
||||
LaunchedEffect(gyms) {
|
||||
if (gyms.isNotEmpty() && lastUsedGym == null) {
|
||||
lastUsedGym = viewModel.getLastUsedGym()
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(activeSession, gyms, lastUsedGym) {
|
||||
AppShortcutManager.updateShortcuts(
|
||||
context = context,
|
||||
hasActiveSession = activeSession != null,
|
||||
hasGyms = gyms.isNotEmpty(),
|
||||
lastUsedGym = if (activeSession == null && gyms.size > 1) lastUsedGym else null,
|
||||
)
|
||||
}
|
||||
|
||||
LaunchedEffect(shortcutAction) {
|
||||
when (shortcutAction) {
|
||||
AppShortcutManager.ACTION_START_SESSION -> {
|
||||
navController.navigate(Screen.Sessions) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
|
||||
AppShortcutManager.ACTION_END_SESSION -> {
|
||||
navController.navigate(Screen.Sessions) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
}
|
||||
|
||||
activeSession?.let { session -> viewModel.endSession(context, session.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(shortcutAction, activeSession, gyms, lastUsedGym) {
|
||||
if (shortcutAction == AppShortcutManager.ACTION_START_SESSION && gyms.isNotEmpty()) {
|
||||
AppLogger.d("AscentlyApp") { "Processing shortcut action: activeSession=$activeSession, gyms.size=${gyms.size}, lastUsedGymId=$lastUsedGymId, lastUsedGym=${lastUsedGym?.name}" }
|
||||
|
||||
if (activeSession == null) {
|
||||
if (NotificationPermissionUtils.shouldRequestNotificationPermission() &&
|
||||
!NotificationPermissionUtils.isNotificationPermissionGranted(
|
||||
context,
|
||||
)
|
||||
) {
|
||||
AppLogger.d("AscentlyApp") { "Showing notification permission dialog" }
|
||||
showNotificationPermissionDialog = true
|
||||
} else {
|
||||
if (gyms.size == 1) {
|
||||
AppLogger.d("AscentlyApp") { "Starting session with single gym: ${gyms.first().name}" }
|
||||
viewModel.startSession(context, gyms.first().id)
|
||||
} else {
|
||||
val targetGym =
|
||||
lastUsedGymId?.let { gymId -> gyms.find { it.id == gymId } }
|
||||
?: lastUsedGym
|
||||
|
||||
if (targetGym != null) {
|
||||
AppLogger.d("AscentlyApp") { "Starting session with target gym: ${targetGym.name}" }
|
||||
viewModel.startSession(context, targetGym.id)
|
||||
} else {
|
||||
AppLogger.d("AscentlyApp") { "No target gym found, navigating to selection" }
|
||||
navController.navigate(Screen.AddEditSession())
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
AppLogger.d("AscentlyApp") { "Active session already exists: ${activeSession?.id}" }
|
||||
}
|
||||
|
||||
onShortcutActionProcessed()
|
||||
}
|
||||
}
|
||||
|
||||
var fabConfig by remember { mutableStateOf<FabConfig?>(null) }
|
||||
|
||||
Scaffold(
|
||||
bottomBar = { AscentlyBottomNavigation(navController = navController) },
|
||||
floatingActionButton = {
|
||||
fabConfig?.let { config ->
|
||||
FloatingActionButton(
|
||||
onClick = config.onClick,
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = config.icon,
|
||||
contentDescription = config.contentDescription,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
) { innerPadding ->
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = Screen.Sessions,
|
||||
modifier = Modifier.padding(innerPadding),
|
||||
) {
|
||||
composable<Screen.Sessions> {
|
||||
LaunchedEffect(gyms, activeSession) {
|
||||
fabConfig =
|
||||
if (gyms.isNotEmpty() && activeSession == null) {
|
||||
FabConfig(
|
||||
icon = Icons.Default.PlayArrow,
|
||||
contentDescription = "Start Session",
|
||||
onClick = {
|
||||
if (NotificationPermissionUtils
|
||||
.shouldRequestNotificationPermission() &&
|
||||
!NotificationPermissionUtils
|
||||
.isNotificationPermissionGranted(
|
||||
context,
|
||||
)
|
||||
) {
|
||||
showNotificationPermissionDialog = true
|
||||
} else {
|
||||
navController.navigate(Screen.AddEditSession())
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
SessionsScreen(
|
||||
viewModel = viewModel,
|
||||
onNavigateToSessionDetail = { sessionId ->
|
||||
navController.navigate(Screen.SessionDetail(sessionId))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.Problems> {
|
||||
LaunchedEffect(gyms) {
|
||||
fabConfig =
|
||||
if (gyms.isNotEmpty()) {
|
||||
FabConfig(
|
||||
icon = Icons.Default.Add,
|
||||
contentDescription = "Add Problem",
|
||||
onClick = {
|
||||
navController.navigate(Screen.AddEditProblem())
|
||||
},
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
ProblemsScreen(
|
||||
viewModel = viewModel,
|
||||
onNavigateToProblemDetail = { problemId ->
|
||||
navController.navigate(Screen.ProblemDetail(problemId))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.Analytics> {
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AnalyticsScreen(viewModel = viewModel)
|
||||
}
|
||||
|
||||
composable<Screen.Gyms> {
|
||||
LaunchedEffect(Unit) {
|
||||
fabConfig =
|
||||
FabConfig(
|
||||
icon = Icons.Default.Add,
|
||||
contentDescription = "Add Gym",
|
||||
onClick = { navController.navigate(Screen.AddEditGym()) },
|
||||
)
|
||||
}
|
||||
GymsScreen(
|
||||
viewModel = viewModel,
|
||||
onNavigateToGymDetail = { gymId ->
|
||||
navController.navigate(Screen.GymDetail(gymId))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.Settings> {
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
SettingsScreen(viewModel = viewModel)
|
||||
}
|
||||
|
||||
composable<Screen.SessionDetail> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.SessionDetail>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
SessionDetailScreen(
|
||||
sessionId = args.sessionId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
onNavigateToProblemDetail = { problemId ->
|
||||
navController.navigate(Screen.ProblemDetail(problemId))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.ProblemDetail> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.ProblemDetail>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
ProblemDetailScreen(
|
||||
problemId = args.problemId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
onNavigateToEdit = { problemId ->
|
||||
navController.navigate(Screen.AddEditProblem(problemId = problemId))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.GymDetail> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.GymDetail>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
GymDetailScreen(
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
onNavigateToEdit = { gymId ->
|
||||
navController.navigate(Screen.AddEditGym(gymId = gymId))
|
||||
},
|
||||
onNavigateToSessionDetail = { sessionId ->
|
||||
navController.navigate(Screen.SessionDetail(sessionId))
|
||||
},
|
||||
onNavigateToProblemDetail = { problemId ->
|
||||
navController.navigate(Screen.ProblemDetail(problemId))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.AddEditGym> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.AddEditGym>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AddEditGymScreen(
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.AddEditProblem> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.AddEditProblem>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AddEditProblemScreen(
|
||||
problemId = args.problemId,
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.AddEditSession> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.AddEditSession>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AddEditSessionScreen(
|
||||
sessionId = args.sessionId,
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showNotificationPermissionDialog) {
|
||||
NotificationPermissionDialog(
|
||||
onDismiss = { showNotificationPermissionDialog = false },
|
||||
onRequestPermission = {
|
||||
permissionLauncher.launch(
|
||||
NotificationPermissionUtils.getNotificationPermissionString(),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AscentlyBottomNavigation(navController: NavHostController) {
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
|
||||
NavigationBar {
|
||||
bottomNavigationItems.forEach { item ->
|
||||
val isSelected =
|
||||
when (item.screen) {
|
||||
is Screen.Sessions -> currentRoute?.contains("Session") == true
|
||||
is Screen.Problems -> currentRoute?.contains("Problem") == true
|
||||
is Screen.Gyms -> currentRoute?.contains("Gym") == true
|
||||
is Screen.Analytics -> currentRoute?.contains("Analytics") == true
|
||||
is Screen.Settings -> currentRoute?.contains("Settings") == true
|
||||
else -> currentRoute?.contains(item.screen::class.simpleName ?: "") == true
|
||||
}
|
||||
|
||||
NavigationBarItem(
|
||||
icon = { Icon(item.icon, contentDescription = item.label) },
|
||||
label = { Text(item.label) },
|
||||
selected = isSelected,
|
||||
onClick = {
|
||||
navController.navigate(item.screen) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
// Don't restore state - always start fresh when switching tabs
|
||||
restoreState = false
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class FabConfig(
|
||||
val icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
val contentDescription: String,
|
||||
val onClick: () -> Unit,
|
||||
)
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.ascently.data.model.ClimbSession
|
||||
import com.atridad.ascently.data.model.Gym
|
||||
import com.atridad.ascently.ui.theme.CustomIcons
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import kotlinx.coroutines.delay
|
||||
import java.time.Instant
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
@Composable
|
||||
fun ActiveSessionBanner(
|
||||
activeSession: ClimbSession?,
|
||||
gym: Gym?,
|
||||
onSessionClick: () -> Unit,
|
||||
onEndSession: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
if (activeSession == null) return
|
||||
|
||||
val sessionId = activeSession.id
|
||||
val startTimeString = activeSession.startTime
|
||||
val gymName = gym?.name ?: "Unknown Gym"
|
||||
|
||||
var elapsedSeconds by remember(sessionId) { mutableLongStateOf(0L) }
|
||||
|
||||
LaunchedEffect(sessionId, startTimeString) {
|
||||
if (startTimeString == null) return@LaunchedEffect
|
||||
|
||||
while (true) {
|
||||
elapsedSeconds = calculateElapsedSeconds(startTimeString)
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
|
||||
val durationText = remember(elapsedSeconds) {
|
||||
formatDuration(elapsedSeconds)
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onSessionClick() },
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Default.PlayArrow,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Active Session",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
)
|
||||
|
||||
if (startTimeString != null) {
|
||||
Text(
|
||||
text = durationText,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
FilledIconButton(
|
||||
onClick = onEndSession,
|
||||
colors = IconButtonDefaults.filledIconButtonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error,
|
||||
contentColor = MaterialTheme.colorScheme.onError,
|
||||
),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = CustomIcons.Stop(MaterialTheme.colorScheme.onError),
|
||||
contentDescription = "End session",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateElapsedSeconds(startTimeString: String): Long {
|
||||
return try {
|
||||
val startTime = DateFormatUtils.parseISO8601(startTimeString) ?: return 0L
|
||||
val now = Instant.now()
|
||||
ChronoUnit.SECONDS.between(startTime, now).coerceAtLeast(0)
|
||||
} catch (_: Exception) {
|
||||
0L
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatDuration(totalSeconds: Long): String {
|
||||
val hours = totalSeconds / 3600
|
||||
val minutes = (totalSeconds % 3600) / 60
|
||||
val seconds = totalSeconds % 60
|
||||
|
||||
return when {
|
||||
hours > 0 -> "${hours}h ${minutes}m ${seconds}s"
|
||||
minutes > 0 -> "${minutes}m ${seconds}s"
|
||||
else -> "${seconds}s"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -23,25 +23,25 @@ data class BarChartDataPoint(val label: String, val value: Int, val gradeNumeric
|
||||
|
||||
/** Configuration for bar chart styling */
|
||||
data class BarChartStyle(
|
||||
val barColor: Color,
|
||||
val gridColor: Color,
|
||||
val textColor: Color,
|
||||
val backgroundColor: Color
|
||||
val barColor: Color,
|
||||
val gridColor: Color,
|
||||
val textColor: Color,
|
||||
val backgroundColor: Color,
|
||||
)
|
||||
|
||||
/** Custom Bar Chart for displaying grade distribution */
|
||||
@Composable
|
||||
fun BarChart(
|
||||
data: List<BarChartDataPoint>,
|
||||
modifier: Modifier = Modifier,
|
||||
style: BarChartStyle =
|
||||
BarChartStyle(
|
||||
barColor = MaterialTheme.colorScheme.primary,
|
||||
gridColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
||||
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
backgroundColor = MaterialTheme.colorScheme.surface
|
||||
),
|
||||
showGrid: Boolean = true
|
||||
data: List<BarChartDataPoint>,
|
||||
modifier: Modifier = Modifier,
|
||||
style: BarChartStyle =
|
||||
BarChartStyle(
|
||||
barColor = MaterialTheme.colorScheme.primary,
|
||||
gridColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
||||
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
backgroundColor = MaterialTheme.colorScheme.surface,
|
||||
),
|
||||
showGrid: Boolean = true,
|
||||
) {
|
||||
val textMeasurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
@@ -68,42 +68,44 @@ fun BarChart(
|
||||
|
||||
// Draw background
|
||||
drawRect(
|
||||
color = style.backgroundColor,
|
||||
topLeft = Offset(padding, padding),
|
||||
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight)
|
||||
color = style.backgroundColor,
|
||||
topLeft = Offset(padding, padding),
|
||||
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight),
|
||||
)
|
||||
|
||||
// Draw grid
|
||||
if (showGrid) {
|
||||
drawGrid(
|
||||
padding = padding,
|
||||
chartWidth = chartWidth,
|
||||
chartHeight = chartHeight,
|
||||
gridColor = style.gridColor,
|
||||
maxValue = maxValue,
|
||||
textMeasurer = textMeasurer,
|
||||
textColor = style.textColor
|
||||
padding = padding,
|
||||
chartWidth = chartWidth,
|
||||
chartHeight = chartHeight,
|
||||
gridColor = style.gridColor,
|
||||
maxValue = maxValue,
|
||||
textMeasurer = textMeasurer,
|
||||
textColor = style.textColor,
|
||||
)
|
||||
}
|
||||
|
||||
// Draw bars and labels
|
||||
sortedData.forEachIndexed { index, dataPoint ->
|
||||
val barHeight =
|
||||
if (maxValue > 0) {
|
||||
(dataPoint.value.toFloat() / maxValue.toFloat()) * chartHeight * 0.8f
|
||||
} else 0f
|
||||
if (maxValue > 0) {
|
||||
(dataPoint.value.toFloat() / maxValue.toFloat()) * chartHeight * 0.8f
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
|
||||
val barX =
|
||||
padding +
|
||||
barSpacing +
|
||||
index * (barWidth + barSpacing / (barCount - 1).coerceAtLeast(1))
|
||||
padding +
|
||||
barSpacing +
|
||||
index * (barWidth + barSpacing / (barCount - 1).coerceAtLeast(1))
|
||||
val barY = padding + chartHeight - barHeight
|
||||
|
||||
// Draw bar
|
||||
drawRect(
|
||||
color = style.barColor,
|
||||
topLeft = Offset(barX, barY),
|
||||
size = androidx.compose.ui.geometry.Size(barWidth, barHeight)
|
||||
color = style.barColor,
|
||||
topLeft = Offset(barX, barY),
|
||||
size = androidx.compose.ui.geometry.Size(barWidth, barHeight),
|
||||
)
|
||||
|
||||
// Draw value on bar
|
||||
@@ -114,24 +116,24 @@ fun BarChart(
|
||||
|
||||
// Position text
|
||||
val textY =
|
||||
if (barHeight > textSize.size.height + 8.dp.toPx()) {
|
||||
barY + 8.dp.toPx()
|
||||
} else {
|
||||
barY - 4.dp.toPx()
|
||||
}
|
||||
if (barHeight > textSize.size.height + 8.dp.toPx()) {
|
||||
barY + 8.dp.toPx()
|
||||
} else {
|
||||
barY - 4.dp.toPx()
|
||||
}
|
||||
|
||||
val textColor =
|
||||
if (barHeight > textSize.size.height + 8.dp.toPx()) {
|
||||
Color.White
|
||||
} else {
|
||||
style.textColor
|
||||
}
|
||||
if (barHeight > textSize.size.height + 8.dp.toPx()) {
|
||||
Color.White
|
||||
} else {
|
||||
style.textColor
|
||||
}
|
||||
|
||||
drawText(
|
||||
textMeasurer = textMeasurer,
|
||||
text = valueText,
|
||||
style = textStyle.copy(color = textColor),
|
||||
topLeft = Offset(barX + barWidth / 2f - textSize.size.width / 2f, textY)
|
||||
textMeasurer = textMeasurer,
|
||||
text = valueText,
|
||||
style = textStyle.copy(color = textColor),
|
||||
topLeft = Offset(barX + barWidth / 2f - textSize.size.width / 2f, textY),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -141,14 +143,14 @@ fun BarChart(
|
||||
val labelTextSize = textMeasurer.measure(gradeText, labelTextStyle)
|
||||
|
||||
drawText(
|
||||
textMeasurer = textMeasurer,
|
||||
text = gradeText,
|
||||
style = labelTextStyle,
|
||||
topLeft =
|
||||
Offset(
|
||||
barX + barWidth / 2f - labelTextSize.size.width / 2f,
|
||||
padding + chartHeight + 8.dp.toPx()
|
||||
)
|
||||
textMeasurer = textMeasurer,
|
||||
text = gradeText,
|
||||
style = labelTextStyle,
|
||||
topLeft =
|
||||
Offset(
|
||||
barX + barWidth / 2f - labelTextSize.size.width / 2f,
|
||||
padding + chartHeight + 8.dp.toPx(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -156,37 +158,37 @@ fun BarChart(
|
||||
}
|
||||
|
||||
private fun DrawScope.drawGrid(
|
||||
padding: Float,
|
||||
chartWidth: Float,
|
||||
chartHeight: Float,
|
||||
gridColor: Color,
|
||||
maxValue: Int,
|
||||
textMeasurer: TextMeasurer,
|
||||
textColor: Color
|
||||
padding: Float,
|
||||
chartWidth: Float,
|
||||
chartHeight: Float,
|
||||
gridColor: Color,
|
||||
maxValue: Int,
|
||||
textMeasurer: TextMeasurer,
|
||||
textColor: Color,
|
||||
) {
|
||||
val textStyle = TextStyle(color = textColor, fontSize = 10.sp)
|
||||
|
||||
// Horizontal grid lines
|
||||
val gridLines =
|
||||
when {
|
||||
maxValue <= 5 -> (0..maxValue).toList()
|
||||
maxValue <= 10 -> (0..maxValue step 2).toList()
|
||||
maxValue <= 20 -> (0..maxValue step 5).toList()
|
||||
else -> {
|
||||
val step = (maxValue / 5).coerceAtLeast(1)
|
||||
(0..maxValue step step).toList()
|
||||
}
|
||||
when {
|
||||
maxValue <= 5 -> (0..maxValue).toList()
|
||||
maxValue <= 10 -> (0..maxValue step 2).toList()
|
||||
maxValue <= 20 -> (0..maxValue step 5).toList()
|
||||
else -> {
|
||||
val step = (maxValue / 5).coerceAtLeast(1)
|
||||
(0..maxValue step step).toList()
|
||||
}
|
||||
}
|
||||
|
||||
gridLines.forEach { value ->
|
||||
val y = padding + chartHeight - (value.toFloat() / maxValue.toFloat()) * chartHeight * 0.8f
|
||||
|
||||
// Draw grid line
|
||||
drawLine(
|
||||
color = gridColor,
|
||||
start = Offset(padding, y),
|
||||
end = Offset(padding + chartWidth, y),
|
||||
strokeWidth = 1.dp.toPx()
|
||||
color = gridColor,
|
||||
start = Offset(padding, y),
|
||||
end = Offset(padding + chartWidth, y),
|
||||
strokeWidth = 1.dp.toPx(),
|
||||
)
|
||||
|
||||
// Draw Y-axis label
|
||||
@@ -194,14 +196,14 @@ private fun DrawScope.drawGrid(
|
||||
val text = value.toString()
|
||||
val textSize = textMeasurer.measure(text, textStyle)
|
||||
drawText(
|
||||
textMeasurer = textMeasurer,
|
||||
text = text,
|
||||
style = textStyle,
|
||||
topLeft =
|
||||
Offset(
|
||||
padding - textSize.size.width - 8.dp.toPx(),
|
||||
y - textSize.size.height / 2f
|
||||
)
|
||||
textMeasurer = textMeasurer,
|
||||
text = text,
|
||||
style = textStyle,
|
||||
topLeft =
|
||||
Offset(
|
||||
padding - textSize.size.width - 8.dp.toPx(),
|
||||
y - textSize.size.height / 2f,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.pager.HorizontalPager
|
||||
import androidx.compose.foundation.pager.rememberPagerState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDismiss: () -> Unit) {
|
||||
val pagerState = rememberPagerState(initialPage = initialIndex, pageCount = { imagePaths.size })
|
||||
val thumbnailListState = rememberLazyListState()
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
|
||||
// Handle back button press
|
||||
BackHandler { onDismiss() }
|
||||
|
||||
// Auto-scroll thumbnail list to center current image
|
||||
LaunchedEffect(pagerState.currentPage) {
|
||||
if (imagePaths.size > 1) {
|
||||
thumbnailListState.animateScrollToItem(
|
||||
index = pagerState.currentPage,
|
||||
scrollOffset = -200,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties =
|
||||
DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = true),
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize().background(Color.Black).systemBarsPadding()) {
|
||||
// Main image pager
|
||||
HorizontalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { page ->
|
||||
OrientationAwareImage(
|
||||
imagePath = imagePaths[page],
|
||||
contentDescription = "Full screen image",
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
|
||||
// Top bar with back button and counter
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().align(Alignment.TopStart),
|
||||
color = Color.Black.copy(alpha = 0.6f),
|
||||
) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
// Back button
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = "Close",
|
||||
tint = Color.White,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
|
||||
// Image counter
|
||||
if (imagePaths.size > 1) {
|
||||
Text(
|
||||
text = "${pagerState.currentPage + 1} / ${imagePaths.size}",
|
||||
color = Color.White,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// Thumbnail strip at bottom (if multiple images)
|
||||
if (imagePaths.size > 1) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().align(Alignment.BottomCenter),
|
||||
color = Color.Black.copy(alpha = 0.6f),
|
||||
) {
|
||||
LazyRow(
|
||||
state = thumbnailListState,
|
||||
modifier = Modifier.padding(vertical = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp),
|
||||
) {
|
||||
itemsIndexed(imagePaths) { index, imagePath ->
|
||||
val isSelected = index == pagerState.currentPage
|
||||
|
||||
Box(
|
||||
modifier =
|
||||
Modifier.size(48.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable {
|
||||
coroutineScope.launch {
|
||||
pagerState.animateScrollToPage(index)
|
||||
}
|
||||
},
|
||||
) {
|
||||
OrientationAwareImage(
|
||||
imagePath = imagePath,
|
||||
contentDescription = "Thumbnail ${index + 1}",
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
|
||||
// Selection indicator
|
||||
if (isSelected) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier.fillMaxSize()
|
||||
.background(
|
||||
Color.White.copy(alpha = 0.3f),
|
||||
RoundedCornerShape(8.dp),
|
||||
),
|
||||
)
|
||||
Box(
|
||||
modifier =
|
||||
Modifier.fillMaxSize()
|
||||
.background(
|
||||
Color.Transparent,
|
||||
RoundedCornerShape(8.dp),
|
||||
)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(
|
||||
Color.White.copy(alpha = 0.2f),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
@@ -15,26 +15,26 @@ import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun ImageDisplay(
|
||||
imagePaths: List<String>,
|
||||
modifier: Modifier = Modifier,
|
||||
imageSize: Int = 120,
|
||||
onImageClick: ((Int) -> Unit)? = null
|
||||
imagePaths: List<String>,
|
||||
modifier: Modifier = Modifier,
|
||||
imageSize: Int = 120,
|
||||
onImageClick: ((Int) -> Unit)? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
LocalContext.current
|
||||
|
||||
if (imagePaths.isNotEmpty()) {
|
||||
LazyRow(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
itemsIndexed(imagePaths) { index, imagePath ->
|
||||
OrientationAwareImage(
|
||||
imagePath = imagePath,
|
||||
contentDescription = "Problem photo",
|
||||
modifier =
|
||||
Modifier.size(imageSize.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable(enabled = onImageClick != null) {
|
||||
onImageClick?.invoke(index)
|
||||
},
|
||||
contentScale = ContentScale.Crop
|
||||
imagePath = imagePath,
|
||||
contentDescription = "Problem photo",
|
||||
modifier =
|
||||
Modifier.size(imageSize.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable(enabled = onImageClick != null) {
|
||||
onImageClick?.invoke(index)
|
||||
},
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -43,17 +43,17 @@ fun ImageDisplay(
|
||||
|
||||
@Composable
|
||||
fun ImageDisplaySection(
|
||||
imagePaths: List<String>,
|
||||
modifier: Modifier = Modifier,
|
||||
title: String = "Photos",
|
||||
onImageClick: ((Int) -> Unit)? = null
|
||||
imagePaths: List<String>,
|
||||
modifier: Modifier = Modifier,
|
||||
title: String = "Photos",
|
||||
onImageClick: ((Int) -> Unit)? = null,
|
||||
) {
|
||||
if (imagePaths.isNotEmpty()) {
|
||||
Column(modifier = modifier) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
@@ -0,0 +1,286 @@
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.CameraAlt
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PhotoLibrary
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.FileProvider
|
||||
import com.atridad.ascently.utils.ImageUtils
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
@Composable
|
||||
fun ImagePicker(
|
||||
imageUris: List<String>,
|
||||
onImagesChanged: (List<String>) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
maxImages: Int = 5,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var tempImageUris by remember { mutableStateOf(imageUris) }
|
||||
var showImageSourceDialog by remember { mutableStateOf(false) }
|
||||
var cameraImageUri by remember { mutableStateOf<Uri?>(null) }
|
||||
|
||||
// Image picker launcher
|
||||
val imagePickerLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.GetMultipleContents(),
|
||||
) { uris ->
|
||||
if (uris.isNotEmpty()) {
|
||||
val currentCount = tempImageUris.size
|
||||
val remainingSlots = maxImages - currentCount
|
||||
val urisToProcess = uris.take(remainingSlots)
|
||||
|
||||
// Process images
|
||||
val newImagePaths = mutableListOf<String>()
|
||||
urisToProcess.forEach { uri ->
|
||||
val imagePath = ImageUtils.saveTemporaryImageFromUri(context, uri)
|
||||
if (imagePath != null) {
|
||||
newImagePaths.add(imagePath)
|
||||
}
|
||||
}
|
||||
|
||||
if (newImagePaths.isNotEmpty()) {
|
||||
val updatedUris = tempImageUris + newImagePaths
|
||||
tempImageUris = updatedUris
|
||||
onImagesChanged(updatedUris)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Camera launcher
|
||||
val cameraLauncher =
|
||||
rememberLauncherForActivityResult(contract = ActivityResultContracts.TakePicture()) {
|
||||
success ->
|
||||
if (success) {
|
||||
cameraImageUri?.let { uri ->
|
||||
val imagePath = ImageUtils.saveTemporaryImageFromUri(context, uri)
|
||||
if (imagePath != null) {
|
||||
val updatedUris = tempImageUris + imagePath
|
||||
tempImageUris = updatedUris
|
||||
onImagesChanged(updatedUris)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Camera permission launcher
|
||||
val cameraPermissionLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
) { isGranted ->
|
||||
if (isGranted) {
|
||||
// Create image file for camera
|
||||
val imageFile = createImageFile(context)
|
||||
val uri =
|
||||
FileProvider.getUriForFile(
|
||||
context,
|
||||
"${context.packageName}.fileprovider",
|
||||
imageFile,
|
||||
)
|
||||
cameraImageUri = uri
|
||||
cameraLauncher.launch(uri)
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = modifier) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = "Photos (${tempImageUris.size}/$maxImages)",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
|
||||
if (tempImageUris.size < maxImages) {
|
||||
TextButton(onClick = { showImageSourceDialog = true }) {
|
||||
Icon(
|
||||
Icons.Default.Add,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Add Photos")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (tempImageUris.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(tempImageUris) { imagePath ->
|
||||
ImageItem(
|
||||
imagePath = imagePath,
|
||||
onRemove = {
|
||||
val updatedUris = tempImageUris.filter { it != imagePath }
|
||||
tempImageUris = updatedUris
|
||||
onImagesChanged(updatedUris)
|
||||
|
||||
// Delete the image file
|
||||
ImageUtils.deleteImage(context, imagePath)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().height(100.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
Icons.Default.Add,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Add photos of this problem",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Image Source Selection Dialog
|
||||
if (showImageSourceDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showImageSourceDialog = false },
|
||||
title = { Text("Add Photo") },
|
||||
text = { Text("Choose how you'd like to add a photo") },
|
||||
confirmButton = {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
showImageSourceDialog = false
|
||||
imagePickerLauncher.launch("image/*")
|
||||
},
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.PhotoLibrary,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Gallery")
|
||||
}
|
||||
|
||||
TextButton(
|
||||
onClick = {
|
||||
showImageSourceDialog = false
|
||||
when (
|
||||
ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.CAMERA,
|
||||
)
|
||||
) {
|
||||
PackageManager.PERMISSION_GRANTED -> {
|
||||
// Create image file for camera
|
||||
val imageFile = createImageFile(context)
|
||||
val uri =
|
||||
FileProvider.getUriForFile(
|
||||
context,
|
||||
"${context.packageName}.fileprovider",
|
||||
imageFile,
|
||||
)
|
||||
cameraImageUri = uri
|
||||
cameraLauncher.launch(uri)
|
||||
}
|
||||
else -> {
|
||||
cameraPermissionLauncher.launch(
|
||||
Manifest.permission.CAMERA,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.CameraAlt,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Camera")
|
||||
}
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showImageSourceDialog = false }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createImageFile(context: android.content.Context): File {
|
||||
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
|
||||
val imageFileName = "JPEG_${timeStamp}_"
|
||||
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
|
||||
return File.createTempFile(imageFileName, ".jpg", storageDir)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ImageItem(imagePath: String, onRemove: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
ImageUtils.getImageFile(context, imagePath)
|
||||
|
||||
Box(modifier = modifier.size(80.dp)) {
|
||||
OrientationAwareImage(
|
||||
imagePath = imagePath,
|
||||
contentDescription = "Problem photo",
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
|
||||
IconButton(onClick = onRemove, modifier = Modifier.align(Alignment.TopEnd).size(24.dp)) {
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = "Remove photo",
|
||||
modifier = Modifier.fillMaxSize().padding(2.dp),
|
||||
tint = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -25,7 +25,7 @@ import androidx.compose.ui.unit.sp
|
||||
data class ChartDataPoint(
|
||||
val x: Float,
|
||||
val y: Float,
|
||||
val label: String? = null
|
||||
val label: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -37,7 +37,7 @@ data class ChartStyle(
|
||||
val lineWidth: Float = 3f,
|
||||
val gridColor: Color,
|
||||
val textColor: Color,
|
||||
val backgroundColor: Color
|
||||
val backgroundColor: Color,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -52,59 +52,59 @@ fun LineChart(
|
||||
fillColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
|
||||
gridColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
||||
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
backgroundColor = MaterialTheme.colorScheme.surface
|
||||
backgroundColor = MaterialTheme.colorScheme.surface,
|
||||
),
|
||||
showGrid: Boolean = true,
|
||||
xAxisFormatter: (Float) -> String = { it.toString() },
|
||||
yAxisFormatter: (Float) -> String = { it.toString() }
|
||||
yAxisFormatter: (Float) -> String = { it.toString() },
|
||||
) {
|
||||
val textMeasurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
|
||||
|
||||
Box(modifier = modifier) {
|
||||
Canvas(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp)
|
||||
.padding(16.dp),
|
||||
) {
|
||||
if (data.isEmpty()) return@Canvas
|
||||
|
||||
|
||||
val padding = with(density) { 32.dp.toPx() }
|
||||
val chartWidth = size.width - padding * 2
|
||||
val chartHeight = size.height - padding * 2
|
||||
|
||||
|
||||
// Calculate data bounds
|
||||
val dataMinY = data.minOf { it.y }
|
||||
val dataMaxY = data.maxOf { it.y }
|
||||
|
||||
|
||||
// Add some padding to Y-axis (10% above and below the data range)
|
||||
val yPadding = if (dataMaxY == dataMinY) 1f else (dataMaxY - dataMinY) * 0.1f
|
||||
val minY = dataMinY - yPadding
|
||||
val maxY = dataMaxY + yPadding
|
||||
|
||||
|
||||
val minX = data.minOf { it.x }
|
||||
val maxX = data.maxOf { it.x }
|
||||
|
||||
|
||||
val xRange = if (maxX - minX == 0f) 1f else maxX - minX // Minimum range of 1 for single points
|
||||
val yRange = maxY - minY
|
||||
|
||||
|
||||
// Ensure we have valid ranges
|
||||
if (yRange == 0f) return@Canvas
|
||||
|
||||
|
||||
// Convert data points to screen coordinates
|
||||
val screenPoints = data.map { point ->
|
||||
val x = padding + (point.x - minX) / xRange * chartWidth
|
||||
val y = padding + chartHeight - (point.y - minY) / yRange * chartHeight
|
||||
Offset(x, y)
|
||||
}
|
||||
|
||||
|
||||
// Draw background
|
||||
drawRect(
|
||||
color = style.backgroundColor,
|
||||
topLeft = Offset(padding, padding),
|
||||
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight)
|
||||
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight),
|
||||
)
|
||||
|
||||
|
||||
// Draw grid
|
||||
if (showGrid) {
|
||||
drawGrid(
|
||||
@@ -120,49 +120,49 @@ fun LineChart(
|
||||
textColor = style.textColor,
|
||||
xAxisFormatter = xAxisFormatter,
|
||||
yAxisFormatter = yAxisFormatter,
|
||||
actualDataPoints = data
|
||||
actualDataPoints = data,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// Draw area fill
|
||||
if (screenPoints.size > 1) {
|
||||
drawAreaFill(
|
||||
points = screenPoints,
|
||||
padding = padding,
|
||||
chartHeight = chartHeight,
|
||||
fillColor = style.fillColor
|
||||
fillColor = style.fillColor,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// Draw line
|
||||
if (screenPoints.size > 1) {
|
||||
drawLine(
|
||||
points = screenPoints,
|
||||
lineColor = style.lineColor,
|
||||
lineWidth = style.lineWidth
|
||||
lineWidth = style.lineWidth,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// Draw data points - more pronounced
|
||||
screenPoints.forEach { point ->
|
||||
// Draw outer circle (larger)
|
||||
drawCircle(
|
||||
color = style.lineColor,
|
||||
radius = 8f,
|
||||
center = point
|
||||
center = point,
|
||||
)
|
||||
// Draw inner circle (white center)
|
||||
drawCircle(
|
||||
color = style.backgroundColor,
|
||||
radius = 5f,
|
||||
center = point
|
||||
center = point,
|
||||
)
|
||||
// Draw border for better visibility
|
||||
drawCircle(
|
||||
color = style.lineColor,
|
||||
radius = 8f,
|
||||
center = point,
|
||||
style = Stroke(width = 2f)
|
||||
style = Stroke(width = 2f),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -182,43 +182,43 @@ private fun DrawScope.drawGrid(
|
||||
textColor: Color,
|
||||
xAxisFormatter: (Float) -> String,
|
||||
yAxisFormatter: (Float) -> String,
|
||||
actualDataPoints: List<ChartDataPoint>
|
||||
actualDataPoints: List<ChartDataPoint>,
|
||||
) {
|
||||
val textStyle = TextStyle(
|
||||
color = textColor,
|
||||
fontSize = 10.sp
|
||||
fontSize = 10.sp,
|
||||
)
|
||||
|
||||
|
||||
// Draw vertical grid lines (X-axis) - only at integer values for sessions
|
||||
val xRange = maxX - minX
|
||||
if (xRange > 0) {
|
||||
val startX = kotlin.math.ceil(minX).toInt()
|
||||
val endX = kotlin.math.floor(maxX).toInt()
|
||||
|
||||
|
||||
for (sessionNum in startX..endX) {
|
||||
val x = padding + (sessionNum.toFloat() - minX) / xRange * chartWidth
|
||||
|
||||
|
||||
// Draw grid line
|
||||
drawLine(
|
||||
color = gridColor,
|
||||
start = Offset(x, padding),
|
||||
end = Offset(x, padding + chartHeight),
|
||||
strokeWidth = 1.dp.toPx()
|
||||
strokeWidth = 1.dp.toPx(),
|
||||
)
|
||||
|
||||
|
||||
// X-axis labels removed per user request
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Draw horizontal grid lines (Y-axis) - only at actual data point values
|
||||
val yRange = maxY - minY
|
||||
if (yRange > 0) {
|
||||
// Get unique Y values from actual data points
|
||||
val actualYValues = actualDataPoints.map { kotlin.math.round(it.y).toInt() }.toSet()
|
||||
|
||||
|
||||
actualYValues.forEach { gradeValue ->
|
||||
val y = padding + chartHeight - (gradeValue.toFloat() - minY) / yRange * chartHeight
|
||||
|
||||
|
||||
// Only draw if within chart bounds
|
||||
if (y >= padding && y <= padding + chartHeight) {
|
||||
// Draw grid line
|
||||
@@ -226,9 +226,9 @@ private fun DrawScope.drawGrid(
|
||||
color = gridColor,
|
||||
start = Offset(padding, y),
|
||||
end = Offset(padding + chartWidth, y),
|
||||
strokeWidth = 1.dp.toPx()
|
||||
strokeWidth = 1.dp.toPx(),
|
||||
)
|
||||
|
||||
|
||||
// Draw label
|
||||
val text = yAxisFormatter(gradeValue.toFloat())
|
||||
val textSize = textMeasurer.measure(text, textStyle)
|
||||
@@ -238,8 +238,8 @@ private fun DrawScope.drawGrid(
|
||||
style = textStyle,
|
||||
topLeft = Offset(
|
||||
padding - textSize.size.width - 8.dp.toPx(),
|
||||
y - textSize.size.height / 2f
|
||||
)
|
||||
y - textSize.size.height / 2f,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -250,38 +250,38 @@ private fun DrawScope.drawAreaFill(
|
||||
points: List<Offset>,
|
||||
padding: Float,
|
||||
chartHeight: Float,
|
||||
fillColor: Color
|
||||
fillColor: Color,
|
||||
) {
|
||||
val bottomY = padding + chartHeight // This represents the bottom of the chart area
|
||||
|
||||
|
||||
val path = Path().apply {
|
||||
// Start from bottom-left (at chart bottom level)
|
||||
moveTo(points.first().x, bottomY)
|
||||
|
||||
|
||||
// Draw to first point
|
||||
lineTo(points.first().x, points.first().y)
|
||||
|
||||
|
||||
// Draw line through all points
|
||||
for (i in 1 until points.size) {
|
||||
lineTo(points[i].x, points[i].y)
|
||||
}
|
||||
|
||||
|
||||
// Close the path by going to bottom-right (at chart bottom level) and back to start
|
||||
lineTo(points.last().x, bottomY)
|
||||
lineTo(points.first().x, bottomY)
|
||||
close()
|
||||
}
|
||||
|
||||
|
||||
drawPath(
|
||||
path = path,
|
||||
color = fillColor
|
||||
color = fillColor,
|
||||
)
|
||||
}
|
||||
|
||||
private fun DrawScope.drawLine(
|
||||
points: List<Offset>,
|
||||
lineColor: Color,
|
||||
lineWidth: Float
|
||||
lineWidth: Float,
|
||||
) {
|
||||
val path = Path().apply {
|
||||
moveTo(points.first().x, points.first().y)
|
||||
@@ -289,14 +289,14 @@ private fun DrawScope.drawLine(
|
||||
lineTo(points[i].x, points[i].y)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
drawPath(
|
||||
path = path,
|
||||
color = lineColor,
|
||||
style = Stroke(
|
||||
width = lineWidth,
|
||||
cap = StrokeCap.Round,
|
||||
join = StrokeJoin.Round
|
||||
)
|
||||
join = StrokeJoin.Round,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
@@ -7,81 +7,68 @@ import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
|
||||
@Composable
|
||||
fun NotificationPermissionDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onRequestPermission: () -> Unit
|
||||
) {
|
||||
fun NotificationPermissionDialog(onDismiss: () -> Unit, onRequestPermission: () -> Unit) {
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(
|
||||
dismissOnBackPress = false,
|
||||
dismissOnClickOutside = false
|
||||
)
|
||||
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false),
|
||||
) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
shape = MaterialTheme.shapes.medium
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Notifications,
|
||||
contentDescription = "Notifications",
|
||||
modifier = Modifier.size(48.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
|
||||
Text(
|
||||
text = "Enable Notifications",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = MaterialTheme.typography.headlineSmall.fontWeight,
|
||||
textAlign = TextAlign.Center
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
|
||||
Text(
|
||||
text = "OpenClimb needs notification permission to show your active climbing session. This helps you track your progress and ensures the session doesn't get interrupted.",
|
||||
text =
|
||||
"Ascently needs notification permission to show your active climbing session. This helps you track your progress and ensures the session doesn't get interrupted.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
TextButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
TextButton(onClick = onDismiss, modifier = Modifier.weight(1f)) {
|
||||
Text("Not Now")
|
||||
}
|
||||
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
onRequestPermission()
|
||||
onDismiss()
|
||||
},
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text("Enable")
|
||||
}
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("Enable") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +1,68 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.atridad.openclimb.utils.ImageUtils
|
||||
import java.io.File
|
||||
import com.atridad.ascently.utils.ImageUtils
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
@Composable
|
||||
fun OrientationAwareImage(
|
||||
imagePath: String,
|
||||
contentDescription: String? = null,
|
||||
modifier: Modifier = Modifier,
|
||||
contentScale: ContentScale = ContentScale.Fit
|
||||
imagePath: String,
|
||||
modifier: Modifier = Modifier,
|
||||
contentDescription: String? = null,
|
||||
contentScale: ContentScale = ContentScale.Fit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var imageBitmap by
|
||||
remember(imagePath) { mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null) }
|
||||
remember(imagePath) { mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null) }
|
||||
var isLoading by remember(imagePath) { mutableStateOf(true) }
|
||||
|
||||
LaunchedEffect(imagePath) {
|
||||
isLoading = true
|
||||
val bitmap =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val imageFile = ImageUtils.getImageFile(context, imagePath)
|
||||
if (!imageFile.exists()) return@withContext null
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val imageFile = ImageUtils.getImageFile(context, imagePath)
|
||||
if (!imageFile.exists()) return@withContext null
|
||||
|
||||
val originalBitmap =
|
||||
BitmapFactory.decodeFile(imageFile.absolutePath)
|
||||
?: return@withContext null
|
||||
val correctedBitmap = correctImageOrientation(imageFile, originalBitmap)
|
||||
correctedBitmap.asImageBitmap()
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
val originalBitmap =
|
||||
BitmapFactory.decodeFile(imageFile.absolutePath)
|
||||
?: return@withContext null
|
||||
val correctedBitmap = correctImageOrientation(imageFile, originalBitmap)
|
||||
correctedBitmap.asImageBitmap()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
imageBitmap = bitmap
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
Box(modifier = modifier) {
|
||||
if (isLoading) {
|
||||
CircularProgressIndicator(modifier = Modifier.fillMaxSize())
|
||||
CircularProgressIndicator(modifier = Modifier.size(32.dp).align(Alignment.Center))
|
||||
} else {
|
||||
imageBitmap?.let { bitmap ->
|
||||
Image(
|
||||
bitmap = bitmap,
|
||||
contentDescription = contentDescription,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = contentScale
|
||||
bitmap = bitmap,
|
||||
contentDescription = contentDescription,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = contentScale,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -67,16 +70,16 @@ fun OrientationAwareImage(
|
||||
}
|
||||
|
||||
private fun correctImageOrientation(
|
||||
imageFile: File,
|
||||
bitmap: android.graphics.Bitmap
|
||||
imageFile: File,
|
||||
bitmap: android.graphics.Bitmap,
|
||||
): android.graphics.Bitmap {
|
||||
return try {
|
||||
val exif = ExifInterface(imageFile.absolutePath)
|
||||
val orientation =
|
||||
exif.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
)
|
||||
exif.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
|
||||
val matrix = Matrix()
|
||||
var needsTransform = false
|
||||
@@ -113,15 +116,7 @@ private fun correctImageOrientation(
|
||||
needsTransform = true
|
||||
}
|
||||
else -> {
|
||||
if (orientation == ExifInterface.ORIENTATION_UNDEFINED || orientation == 0) {
|
||||
if (imageFile.name.startsWith("problem_") &&
|
||||
imageFile.name.contains("_") &&
|
||||
imageFile.name.endsWith(".jpg")
|
||||
) {
|
||||
matrix.postRotate(90f)
|
||||
needsTransform = true
|
||||
}
|
||||
}
|
||||
// Default case - no transformation needed
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,21 +124,21 @@ private fun correctImageOrientation(
|
||||
bitmap
|
||||
} else {
|
||||
val rotatedBitmap =
|
||||
android.graphics.Bitmap.createBitmap(
|
||||
bitmap,
|
||||
0,
|
||||
0,
|
||||
bitmap.width,
|
||||
bitmap.height,
|
||||
matrix,
|
||||
true
|
||||
)
|
||||
android.graphics.Bitmap.createBitmap(
|
||||
bitmap,
|
||||
0,
|
||||
0,
|
||||
bitmap.width,
|
||||
bitmap.height,
|
||||
matrix,
|
||||
true,
|
||||
)
|
||||
if (rotatedBitmap != bitmap) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
rotatedBitmap
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
bitmap
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
package com.atridad.ascently.ui.components
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
@@ -26,23 +26,23 @@ fun SyncIndicator(isSyncing: StateFlow<Boolean>, modifier: Modifier = Modifier)
|
||||
val syncing by isSyncing.collectAsState()
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = syncing,
|
||||
enter = scaleIn() + fadeIn(),
|
||||
exit = scaleOut() + fadeOut(),
|
||||
modifier = modifier
|
||||
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
|
||||
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
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
package com.atridad.ascently.ui.health
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.ascently.data.health.HealthConnectManager
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HealthConnectCard(modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
val healthConnectManager = remember { HealthConnectManager(context) }
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
|
||||
// State tracking
|
||||
var isHealthConnectAvailable by remember { mutableStateOf(false) }
|
||||
var isLoading by remember { mutableStateOf(true) }
|
||||
var errorMessage by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
// Collect flows
|
||||
val isEnabled by healthConnectManager.isEnabled.collectAsState(initial = false)
|
||||
val hasPermissions by healthConnectManager.hasPermissions.collectAsState(initial = false)
|
||||
|
||||
val isCompatible by healthConnectManager.isCompatible.collectAsState(initial = true)
|
||||
|
||||
// Permission launcher
|
||||
val permissionLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = healthConnectManager.getPermissionRequestContract(),
|
||||
) { _ ->
|
||||
coroutineScope.launch {
|
||||
val allGranted = healthConnectManager.hasAllPermissions()
|
||||
if (!allGranted) {
|
||||
errorMessage =
|
||||
"Some Health Connect permissions were not granted. Please grant all permissions to enable syncing."
|
||||
} else {
|
||||
errorMessage = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check Health Connect availability on first load
|
||||
LaunchedEffect(Unit) {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
healthConnectManager.isHealthConnectAvailable().collect { available ->
|
||||
isHealthConnectAvailable = available
|
||||
isLoading = false
|
||||
|
||||
if (!available && isCompatible) {
|
||||
errorMessage = "Health Connect is not available on this device"
|
||||
} else if (!isCompatible) {
|
||||
errorMessage =
|
||||
"Health Connect API compatibility issue. Please update your device or the app."
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
isLoading = false
|
||||
errorMessage = "Error checking Health Connect availability: ${e.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
// Header with icon and title
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.HealthAndSafety,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint =
|
||||
if (isHealthConnectAvailable && isEnabled && hasPermissions) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Health Connect",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Text(
|
||||
text =
|
||||
when {
|
||||
isLoading -> "Checking availability..."
|
||||
!isCompatible -> "API Issue"
|
||||
!isHealthConnectAvailable -> "Not available"
|
||||
isEnabled && hasPermissions -> "Connected"
|
||||
isEnabled && !hasPermissions -> "Needs permissions"
|
||||
else -> "Disabled"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color =
|
||||
when {
|
||||
isLoading ->
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = 0.7f,
|
||||
)
|
||||
|
||||
!isCompatible -> MaterialTheme.colorScheme.error
|
||||
!isHealthConnectAvailable -> MaterialTheme.colorScheme.error
|
||||
isEnabled && hasPermissions ->
|
||||
MaterialTheme.colorScheme.primary
|
||||
|
||||
isEnabled && !hasPermissions ->
|
||||
MaterialTheme.colorScheme.tertiary
|
||||
|
||||
else ->
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = 0.7f,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Main toggle switch
|
||||
Switch(
|
||||
checked = isEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
coroutineScope.launch {
|
||||
if (enabled && isHealthConnectAvailable) {
|
||||
healthConnectManager.setEnabled(true)
|
||||
try {
|
||||
val permissionSet =
|
||||
healthConnectManager.getRequiredPermissions()
|
||||
if (permissionSet.isNotEmpty()) {
|
||||
permissionLauncher.launch(permissionSet)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
errorMessage = "Error requesting permissions: ${e.message}"
|
||||
}
|
||||
} else {
|
||||
healthConnectManager.setEnabled(false)
|
||||
errorMessage = null
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = isHealthConnectAvailable && !isLoading && isCompatible,
|
||||
)
|
||||
}
|
||||
|
||||
if (isEnabled) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text = "Climbing sessions will be automatically added to Health Connect when completed.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
if (!hasPermissions) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.3f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
Text(
|
||||
text = "Permissions needed",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
"Grant Health Connect permissions to sync your climbing sessions",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = 0.8f,
|
||||
),
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
val permissionSet =
|
||||
healthConnectManager
|
||||
.getRequiredPermissions()
|
||||
if (permissionSet.isNotEmpty()) {
|
||||
permissionLauncher.launch(permissionSet)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
errorMessage =
|
||||
"Error requesting permissions: ${e.message}"
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Grant Permissions") }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text(
|
||||
text =
|
||||
"Sync your climbing sessions to Samsung Health, Google Fit, and other fitness apps through Health Connect.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f),
|
||||
)
|
||||
}
|
||||
errorMessage?.let { error ->
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.5f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,868 @@
|
||||
package com.atridad.ascently.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.ascently.data.model.*
|
||||
import com.atridad.ascently.ui.components.ImagePicker
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import java.time.LocalDateTime
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack: () -> Unit) {
|
||||
var name by remember { mutableStateOf("") }
|
||||
var location by remember { mutableStateOf("") }
|
||||
var notes by remember { mutableStateOf("") }
|
||||
var selectedClimbTypes by remember { mutableStateOf(setOf<ClimbType>()) }
|
||||
var selectedDifficultySystems by remember { mutableStateOf(setOf<DifficultySystem>()) }
|
||||
|
||||
val isEditing = gymId != null
|
||||
|
||||
// Calculate available difficulty systems based on selected climb types
|
||||
val availableDifficultySystems =
|
||||
if (selectedClimbTypes.isEmpty()) {
|
||||
emptyList()
|
||||
} else {
|
||||
selectedClimbTypes
|
||||
.flatMap { climbType -> DifficultySystem.systemsForClimbType(climbType) }
|
||||
.distinct()
|
||||
}
|
||||
|
||||
// Reset selected difficulty systems when available systems change
|
||||
LaunchedEffect(availableDifficultySystems) {
|
||||
selectedDifficultySystems =
|
||||
selectedDifficultySystems.filter { it in availableDifficultySystems }.toSet()
|
||||
}
|
||||
|
||||
// Load existing gym data for editing
|
||||
LaunchedEffect(gymId) {
|
||||
if (gymId != null) {
|
||||
val existingGym = viewModel.getGymById(gymId).first()
|
||||
existingGym?.let { gym ->
|
||||
name = gym.name
|
||||
location = gym.location ?: ""
|
||||
notes = gym.notes ?: ""
|
||||
selectedClimbTypes = gym.supportedClimbTypes.toSet()
|
||||
selectedDifficultySystems = gym.difficultySystems.toSet()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(if (isEditing) "Edit Gym" else "Add Gym") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = "Back",
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
val gym =
|
||||
Gym.create(
|
||||
name,
|
||||
location,
|
||||
selectedClimbTypes.toList(),
|
||||
selectedDifficultySystems.toList(),
|
||||
notes = notes,
|
||||
)
|
||||
|
||||
if (isEditing) {
|
||||
viewModel.updateGym(gym.copy(id = gymId))
|
||||
} else {
|
||||
viewModel.addGym(gym)
|
||||
}
|
||||
onNavigateBack()
|
||||
},
|
||||
enabled =
|
||||
name.isNotBlank() &&
|
||||
selectedClimbTypes.isNotEmpty() &&
|
||||
selectedDifficultySystems.isNotEmpty(),
|
||||
) { Text("Save") }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { paddingValues ->
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
// Name field
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("Gym Name") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
// Location field
|
||||
OutlinedTextField(
|
||||
value = location,
|
||||
onValueChange = { location = it },
|
||||
label = { Text("Location (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
// Climb Types
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Supported Climb Types",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
ClimbType.entries.forEach { climbType ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.selectable(
|
||||
selected = climbType in selectedClimbTypes,
|
||||
onClick = {
|
||||
selectedClimbTypes =
|
||||
if (climbType in
|
||||
selectedClimbTypes
|
||||
) {
|
||||
selectedClimbTypes -
|
||||
climbType
|
||||
} else {
|
||||
selectedClimbTypes +
|
||||
climbType
|
||||
}
|
||||
},
|
||||
role = Role.Checkbox,
|
||||
),
|
||||
) {
|
||||
Checkbox(
|
||||
checked = climbType in selectedClimbTypes,
|
||||
onCheckedChange = null,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(climbType.displayName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Difficulty Systems
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Difficulty Systems",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (selectedClimbTypes.isEmpty()) {
|
||||
Text(
|
||||
text =
|
||||
"Select climb types first to see available difficulty systems",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
)
|
||||
} else {
|
||||
availableDifficultySystems.forEach { system ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.selectable(
|
||||
selected =
|
||||
system in
|
||||
selectedDifficultySystems,
|
||||
onClick = {
|
||||
selectedDifficultySystems =
|
||||
if (system in
|
||||
selectedDifficultySystems
|
||||
) {
|
||||
selectedDifficultySystems -
|
||||
system
|
||||
} else {
|
||||
selectedDifficultySystems +
|
||||
system
|
||||
}
|
||||
},
|
||||
role = Role.Checkbox,
|
||||
),
|
||||
) {
|
||||
Checkbox(
|
||||
checked = system in selectedDifficultySystems,
|
||||
onCheckedChange = null,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(system.displayName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notes field
|
||||
OutlinedTextField(
|
||||
value = notes,
|
||||
onValueChange = { notes = it },
|
||||
label = { Text("Notes (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 3,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddEditProblemScreen(
|
||||
problemId: String?,
|
||||
gymId: String?,
|
||||
viewModel: ClimbViewModel,
|
||||
onNavigateBack: () -> Unit,
|
||||
) {
|
||||
val isEditing = problemId != null
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
|
||||
// Problem form state
|
||||
var selectedGym by remember {
|
||||
mutableStateOf<Gym?>(gymId?.let { id -> gyms.find { it.id == id } })
|
||||
}
|
||||
var problemName by remember { mutableStateOf("") }
|
||||
var description by remember { mutableStateOf("") }
|
||||
var selectedClimbType by remember { mutableStateOf(ClimbType.BOULDER) }
|
||||
var selectedDifficultySystem by remember { mutableStateOf(DifficultySystem.V_SCALE) }
|
||||
var difficultyGrade by remember { mutableStateOf("") }
|
||||
|
||||
var location by remember { mutableStateOf("") }
|
||||
var tags by remember { mutableStateOf("") }
|
||||
var notes by remember { mutableStateOf("") }
|
||||
var isActive by remember { mutableStateOf(true) }
|
||||
var imagePaths by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||
|
||||
// Load existing problem data for editing
|
||||
LaunchedEffect(problemId) {
|
||||
if (problemId != null) {
|
||||
val existingProblem = viewModel.getProblemById(problemId).first()
|
||||
existingProblem?.let { p ->
|
||||
problemName = p.name ?: ""
|
||||
description = p.description ?: ""
|
||||
selectedClimbType = p.climbType
|
||||
selectedDifficultySystem = p.difficulty.system
|
||||
difficultyGrade = p.difficulty.grade
|
||||
|
||||
location = p.location ?: ""
|
||||
tags = p.tags.joinToString(", ")
|
||||
notes = p.notes ?: ""
|
||||
isActive = p.isActive
|
||||
imagePaths = p.imagePaths
|
||||
selectedGym = gyms.find { it.id == p.gymId }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(gymId, gyms) {
|
||||
if (gymId != null && selectedGym == null) {
|
||||
selectedGym = gyms.find { it.id == gymId }
|
||||
}
|
||||
}
|
||||
|
||||
val availableClimbTypes = selectedGym?.supportedClimbTypes ?: ClimbType.entries.toList()
|
||||
val availableDifficultySystems =
|
||||
DifficultySystem.systemsForClimbType(selectedClimbType).filter { system ->
|
||||
selectedGym?.difficultySystems?.contains(system) != false
|
||||
}
|
||||
|
||||
// Auto-select climb type if there's only one available
|
||||
LaunchedEffect(availableClimbTypes) {
|
||||
if (availableClimbTypes.size == 1 && selectedClimbType != availableClimbTypes.first()) {
|
||||
selectedClimbType = availableClimbTypes.first()
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-select or reset difficulty system based on climb type
|
||||
LaunchedEffect(selectedClimbType, availableDifficultySystems) {
|
||||
when {
|
||||
// If current system is not compatible, select the first available one
|
||||
selectedDifficultySystem !in availableDifficultySystems -> {
|
||||
selectedDifficultySystem =
|
||||
availableDifficultySystems.firstOrNull() ?: DifficultySystem.CUSTOM
|
||||
}
|
||||
// If there's only one available system and nothing is selected, auto-select it
|
||||
availableDifficultySystems.size == 1 &&
|
||||
selectedDifficultySystem != availableDifficultySystems.first() -> {
|
||||
selectedDifficultySystem = availableDifficultySystems.first()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset grade when difficulty system changes (unless it's a valid grade for the new system)
|
||||
LaunchedEffect(selectedDifficultySystem) {
|
||||
val availableGrades = selectedDifficultySystem.availableGrades
|
||||
if (availableGrades.isNotEmpty() && difficultyGrade !in availableGrades) {
|
||||
difficultyGrade = ""
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(if (isEditing) "Edit Problem" else "Add Problem") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = "Back",
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
selectedGym?.let { gym ->
|
||||
val difficulty =
|
||||
DifficultyGrade(
|
||||
system = selectedDifficultySystem,
|
||||
grade = difficultyGrade,
|
||||
numericValue =
|
||||
when (
|
||||
selectedDifficultySystem
|
||||
) {
|
||||
DifficultySystem.V_SCALE ->
|
||||
difficultyGrade
|
||||
.removePrefix(
|
||||
"V",
|
||||
)
|
||||
.toIntOrNull()
|
||||
?: 0
|
||||
else ->
|
||||
difficultyGrade
|
||||
.hashCode() %
|
||||
100 // Simple mapping for other systems
|
||||
},
|
||||
)
|
||||
|
||||
val problem =
|
||||
Problem.create(
|
||||
gymId = gym.id,
|
||||
name = problemName.ifBlank { null },
|
||||
description =
|
||||
description.ifBlank { null },
|
||||
climbType = selectedClimbType,
|
||||
difficulty = difficulty,
|
||||
tags =
|
||||
tags.split(",")
|
||||
.map { it.trim() }
|
||||
.filter {
|
||||
it.isNotBlank()
|
||||
},
|
||||
location = location.ifBlank { null },
|
||||
imagePaths = imagePaths,
|
||||
notes = notes.ifBlank { null },
|
||||
)
|
||||
|
||||
if (isEditing) {
|
||||
problemId.let { id ->
|
||||
viewModel.updateProblem(problem.copy(id = id))
|
||||
}
|
||||
} else {
|
||||
viewModel.addProblem(problem)
|
||||
}
|
||||
onNavigateBack()
|
||||
}
|
||||
},
|
||||
enabled = selectedGym != null && difficultyGrade.isNotBlank(),
|
||||
) { Text("Save") }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { paddingValues ->
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
// Gym Selection
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Select Gym",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (gyms.isEmpty()) {
|
||||
Text(
|
||||
text = "No gyms available. Add a gym first.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
} else {
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(gyms) { gym ->
|
||||
FilterChip(
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Basic Problem Info
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Problem Details",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = problemName,
|
||||
onValueChange = { problemName = it },
|
||||
label = { Text("Problem Name (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = { Text("e.g., 'The Overhang Monster', 'Yellow V4'") },
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = description,
|
||||
onValueChange = { description = it },
|
||||
label = { Text("Description (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 2,
|
||||
placeholder = { Text("Describe the problem, holds, style, etc.") },
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = location,
|
||||
onValueChange = { location = it },
|
||||
label = { Text("Location (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = { Text("e.g., 'Cave area', 'Wall 3', 'Right side'") },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Climb Type
|
||||
if (selectedGym != null) {
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Climb Type",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
availableClimbTypes.forEach { climbType ->
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = climbType },
|
||||
label = { Text(climbType.displayName) },
|
||||
selected = selectedClimbType == climbType,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Difficulty
|
||||
if (selectedGym != null) {
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Difficulty",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = "Difficulty System",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(availableDifficultySystems) { system ->
|
||||
FilterChip(
|
||||
onClick = { selectedDifficultySystem = system },
|
||||
label = { Text(system.displayName) },
|
||||
selected = selectedDifficultySystem == system,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (selectedDifficultySystem == DifficultySystem.CUSTOM) {
|
||||
OutlinedTextField(
|
||||
value = difficultyGrade,
|
||||
onValueChange = { newValue ->
|
||||
// Only allow integers for custom scales
|
||||
if (newValue.isEmpty() || newValue.all { it.isDigit() }
|
||||
) {
|
||||
difficultyGrade = newValue
|
||||
}
|
||||
},
|
||||
label = { Text("Grade *") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = {
|
||||
Text("Enter numeric grade (e.g. 5, 10, 15)")
|
||||
},
|
||||
supportingText = {
|
||||
Text("Custom grades must be whole numbers")
|
||||
},
|
||||
keyboardOptions =
|
||||
KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
)
|
||||
} else {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
val availableGrades = selectedDifficultySystem.availableGrades
|
||||
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = !expanded },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = difficultyGrade,
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text("Grade *") },
|
||||
trailingIcon = {
|
||||
ExposedDropdownMenuDefaults.TrailingIcon(
|
||||
expanded = expanded,
|
||||
)
|
||||
},
|
||||
colors =
|
||||
ExposedDropdownMenuDefaults
|
||||
.outlinedTextFieldColors(),
|
||||
modifier =
|
||||
Modifier.menuAnchor(
|
||||
ExposedDropdownMenuAnchorType
|
||||
.PrimaryNotEditable,
|
||||
enabled = true,
|
||||
)
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false },
|
||||
) {
|
||||
availableGrades.forEach { grade ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(grade) },
|
||||
onClick = {
|
||||
difficultyGrade = grade
|
||||
expanded = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Images Section
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Photos",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
ImagePicker(
|
||||
imageUris = imagePaths,
|
||||
onImagesChanged = { imagePaths = it },
|
||||
maxImages = 5,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Additional Info",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = tags,
|
||||
onValueChange = { tags = it },
|
||||
label = { Text("Tags (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = { Text("e.g., crimpy, dynamic (comma-separated)") },
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = notes,
|
||||
onValueChange = { notes = it },
|
||||
label = { Text("Notes (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 3,
|
||||
placeholder = { Text("Any additional notes about this problem") },
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.selectable(
|
||||
selected = isActive,
|
||||
onClick = { isActive = !isActive },
|
||||
role = Role.Checkbox,
|
||||
),
|
||||
) {
|
||||
Checkbox(checked = isActive, onCheckedChange = null)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Problem is currently active",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddEditSessionScreen(
|
||||
sessionId: String?,
|
||||
gymId: String?,
|
||||
viewModel: ClimbViewModel,
|
||||
onNavigateBack: () -> Unit,
|
||||
) {
|
||||
val isEditing = sessionId != null
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
val context = LocalContext.current
|
||||
|
||||
// Session form state
|
||||
var selectedGym by remember {
|
||||
mutableStateOf<Gym?>(gymId?.let { id -> gyms.find { it.id == id } })
|
||||
}
|
||||
var sessionDate by remember { mutableStateOf(LocalDateTime.now().toLocalDate().toString()) }
|
||||
var duration by remember { mutableStateOf("") }
|
||||
var sessionNotes by remember { mutableStateOf("") }
|
||||
|
||||
// Load existing session data for editing
|
||||
LaunchedEffect(sessionId) {
|
||||
if (sessionId != null) {
|
||||
val existingSession = viewModel.getSessionById(sessionId).first()
|
||||
existingSession?.let { session ->
|
||||
selectedGym = gyms.find { it.id == session.gymId }
|
||||
sessionDate = session.date.split("T")[0] // Extract date part
|
||||
duration = session.duration?.toString() ?: ""
|
||||
sessionNotes = session.notes ?: ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(gymId, gyms) {
|
||||
if (gymId != null && selectedGym == null) {
|
||||
selectedGym = gyms.find { it.id == gymId }
|
||||
} else if (gymId == null && selectedGym == null && gyms.size == 1) {
|
||||
// Auto-select the gym if there's only one available
|
||||
selectedGym = gyms.first()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(if (isEditing) "Edit Session" else "Add Session") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = "Back",
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
selectedGym?.let { gym ->
|
||||
if (isEditing) {
|
||||
val session =
|
||||
ClimbSession.create(
|
||||
gymId = gym.id,
|
||||
notes =
|
||||
sessionNotes.ifBlank {
|
||||
null
|
||||
},
|
||||
)
|
||||
sessionId.let { id ->
|
||||
viewModel.updateSession(session.copy(id = id))
|
||||
}
|
||||
} else {
|
||||
viewModel.startSession(
|
||||
context,
|
||||
gym.id,
|
||||
sessionNotes.ifBlank { null },
|
||||
)
|
||||
}
|
||||
onNavigateBack()
|
||||
}
|
||||
},
|
||||
enabled = selectedGym != null,
|
||||
) { Text("Save") }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { paddingValues ->
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
// Gym Selection
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Select Gym",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (gyms.isEmpty()) {
|
||||
Text(
|
||||
text = "No gyms available. Add a gym first.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
} else {
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(gyms) { gym ->
|
||||
FilterChip(
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Session Details
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Session Details",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = sessionDate,
|
||||
onValueChange = { sessionDate = it },
|
||||
label = { Text("Date (YYYY-MM-DD)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = duration,
|
||||
onValueChange = { duration = it },
|
||||
label = { Text("Duration (minutes)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions =
|
||||
KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = sessionNotes,
|
||||
onValueChange = { sessionNotes = it },
|
||||
label = { Text("Session Notes (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 3,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
package com.atridad.ascently.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.ascently.R
|
||||
import com.atridad.ascently.data.model.AttemptResult
|
||||
import com.atridad.ascently.data.model.ClimbType
|
||||
import com.atridad.ascently.data.model.DifficultySystem
|
||||
import com.atridad.ascently.ui.components.BarChart
|
||||
import com.atridad.ascently.ui.components.BarChartDataPoint
|
||||
import com.atridad.ascently.ui.components.SyncIndicator
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import java.time.LocalDateTime
|
||||
|
||||
@Composable
|
||||
fun AnalyticsScreen(viewModel: ClimbViewModel) {
|
||||
val sessions by viewModel.sessions.collectAsState()
|
||||
val problems by viewModel.problems.collectAsState()
|
||||
val attempts by viewModel.attempts.collectAsState()
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
|
||||
val gradeDistributionData = remember(sessions, problems, attempts) {
|
||||
calculateGradeDistribution(sessions, problems, attempts)
|
||||
}
|
||||
|
||||
val favoriteGym = remember(sessions, gyms) {
|
||||
sessions.groupBy { it.gymId }.maxByOrNull { it.value.size }?.let { (gymId, sessionList) ->
|
||||
gyms.find { it.id == gymId }?.name to sessionList.size
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
item {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "Ascently Logo",
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Text(
|
||||
text = "Analytics",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
}
|
||||
|
||||
// Overall Stats
|
||||
item {
|
||||
OverallStatsCard(
|
||||
totalSessions = sessions.size,
|
||||
totalProblems = problems.size,
|
||||
totalAttempts = attempts.size,
|
||||
totalGyms = gyms.size,
|
||||
)
|
||||
}
|
||||
|
||||
// Grade Distribution Chart
|
||||
item {
|
||||
GradeDistributionChartCard(gradeDistributionData = gradeDistributionData)
|
||||
}
|
||||
|
||||
// Favorite Gym
|
||||
item {
|
||||
FavoriteGymCard(
|
||||
gymName = favoriteGym?.first ?: "No sessions yet",
|
||||
sessionCount = favoriteGym?.second ?: 0,
|
||||
)
|
||||
}
|
||||
|
||||
// Recent Activity
|
||||
item {
|
||||
val recentSessions = sessions.take(5)
|
||||
RecentActivityCard(recentSessions = recentSessions.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun OverallStatsCard(totalSessions: Int, totalProblems: Int, totalAttempts: Int, totalGyms: Int) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Overall Stats",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||
) {
|
||||
StatItem(label = "Sessions", value = totalSessions.toString())
|
||||
StatItem(label = "Problems", value = totalProblems.toString())
|
||||
StatItem(label = "Attempts", value = totalAttempts.toString())
|
||||
StatItem(label = "Gyms", value = totalGyms.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionDataPoint>) {
|
||||
// Find all grading systems that have been used in the data
|
||||
val usedSystems =
|
||||
remember(gradeDistributionData) {
|
||||
gradeDistributionData.map { it.difficultySystem }.distinct()
|
||||
}
|
||||
|
||||
var selectedSystem by
|
||||
remember(usedSystems) {
|
||||
mutableStateOf(usedSystems.firstOrNull() ?: DifficultySystem.V_SCALE)
|
||||
}
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var showAllTime by remember { mutableStateOf(true) }
|
||||
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Grade Distribution",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Toggles section
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
// Time period toggle
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// All Time button
|
||||
FilterChip(
|
||||
onClick = { showAllTime = true },
|
||||
label = {
|
||||
Text("All Time", style = MaterialTheme.typography.bodySmall)
|
||||
},
|
||||
selected = showAllTime,
|
||||
colors =
|
||||
FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor =
|
||||
MaterialTheme.colorScheme.primary,
|
||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimary,
|
||||
),
|
||||
)
|
||||
|
||||
// 7 Days button
|
||||
FilterChip(
|
||||
onClick = { showAllTime = false },
|
||||
label = { Text("7 Days", style = MaterialTheme.typography.bodySmall) },
|
||||
selected = !showAllTime,
|
||||
colors =
|
||||
FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor =
|
||||
MaterialTheme.colorScheme.primary,
|
||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimary,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// Scale selector dropdown
|
||||
if (usedSystems.size > 1) {
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = !expanded },
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value =
|
||||
when (selectedSystem) {
|
||||
DifficultySystem.V_SCALE -> "V-Scale"
|
||||
DifficultySystem.FONT -> "Font"
|
||||
DifficultySystem.YDS -> "YDS"
|
||||
DifficultySystem.CUSTOM -> "Custom"
|
||||
},
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
trailingIcon = {
|
||||
ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
|
||||
},
|
||||
modifier =
|
||||
Modifier.menuAnchor(
|
||||
type =
|
||||
ExposedDropdownMenuAnchorType
|
||||
.PrimaryNotEditable,
|
||||
enabled = true,
|
||||
)
|
||||
.width(120.dp),
|
||||
textStyle = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false },
|
||||
) {
|
||||
usedSystems.forEach { system ->
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
when (system) {
|
||||
DifficultySystem.V_SCALE -> "V-Scale"
|
||||
DifficultySystem.FONT -> "Font"
|
||||
DifficultySystem.YDS -> "YDS"
|
||||
DifficultySystem.CUSTOM -> "Custom"
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
selectedSystem = system
|
||||
expanded = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Filter grade distribution data by selected scale and time period
|
||||
val filteredGradeData =
|
||||
remember(gradeDistributionData, selectedSystem, showAllTime) {
|
||||
val systemFiltered =
|
||||
gradeDistributionData.filter {
|
||||
it.difficultySystem == selectedSystem
|
||||
}
|
||||
|
||||
if (showAllTime) {
|
||||
systemFiltered
|
||||
} else {
|
||||
// Filter for last 7 days
|
||||
val sevenDaysAgo = LocalDateTime.now().minusDays(7)
|
||||
systemFiltered.filter { dataPoint ->
|
||||
try {
|
||||
val attemptDate =
|
||||
DateFormatUtils.parseToLocalDateTime(dataPoint.date)
|
||||
attemptDate?.isAfter(sevenDaysAgo) == true
|
||||
} catch (_: Exception) {
|
||||
// If date parsing fails, include the data point
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filteredGradeData.isNotEmpty()) {
|
||||
// Group by grade and sum counts
|
||||
val gradeGroups =
|
||||
filteredGradeData
|
||||
.groupBy { it.grade }
|
||||
.mapValues { (_, dataPoints) -> dataPoints.sumOf { it.count } }
|
||||
.map { (grade, count) ->
|
||||
val firstDataPoint =
|
||||
filteredGradeData.first { it.grade == grade }
|
||||
BarChartDataPoint(
|
||||
label = grade,
|
||||
value = count,
|
||||
gradeNumeric = firstDataPoint.gradeNumeric,
|
||||
)
|
||||
}
|
||||
|
||||
BarChart(data = gradeGroups, modifier = Modifier.fillMaxWidth().height(220.dp))
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
"Successful climbs by ${when (selectedSystem) {
|
||||
DifficultySystem.V_SCALE -> "V-grade"
|
||||
DifficultySystem.FONT -> "Font grade"
|
||||
DifficultySystem.YDS -> "YDS grade"
|
||||
DifficultySystem.CUSTOM -> "custom grade"
|
||||
}}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().height(220.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "No data",
|
||||
modifier = Modifier.size(48.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = "No data available.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Text(
|
||||
text =
|
||||
if (showAllTime) {
|
||||
"Complete some climbs to see your grade distribution!"
|
||||
} else {
|
||||
"No climbs in the last 7 days"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FavoriteGymCard(gymName: String, sessionCount: Int) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Favorite Gym",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
|
||||
if (sessionCount > 0) {
|
||||
Text(
|
||||
text = "$sessionCount sessions",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RecentActivityCard(recentSessions: Int) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Recent Activity",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
if (recentSessions > 0) {
|
||||
"You've had $recentSessions recent sessions"
|
||||
} else {
|
||||
"No recent activity"
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class GradeDistributionDataPoint(
|
||||
val date: String,
|
||||
val grade: String,
|
||||
val gradeNumeric: Int,
|
||||
val count: Int,
|
||||
val climbType: ClimbType,
|
||||
val difficultySystem: DifficultySystem,
|
||||
)
|
||||
|
||||
fun calculateGradeDistribution(
|
||||
sessions: List<com.atridad.ascently.data.model.ClimbSession>,
|
||||
problems: List<com.atridad.ascently.data.model.Problem>,
|
||||
attempts: List<com.atridad.ascently.data.model.Attempt>,
|
||||
): List<GradeDistributionDataPoint> {
|
||||
if (sessions.isEmpty() || problems.isEmpty() || attempts.isEmpty()) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
// Get all successful attempts
|
||||
val successfulAttempts =
|
||||
attempts.filter {
|
||||
it.result == AttemptResult.SUCCESS || it.result == AttemptResult.FLASH
|
||||
}
|
||||
|
||||
if (successfulAttempts.isEmpty()) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
// Map attempts to problems and create grade distribution data
|
||||
val gradeDistribution = mutableMapOf<String, GradeDistributionDataPoint>()
|
||||
|
||||
successfulAttempts.forEach { attempt ->
|
||||
val problem = problems.find { it.id == attempt.problemId }
|
||||
val session = sessions.find { it.id == attempt.sessionId }
|
||||
|
||||
if (problem != null && session != null) {
|
||||
val key = "${problem.difficulty.system.name}-${problem.difficulty.grade}"
|
||||
|
||||
val existing = gradeDistribution[key]
|
||||
if (existing != null) {
|
||||
gradeDistribution[key] = existing.copy(count = existing.count + 1)
|
||||
} else {
|
||||
gradeDistribution[key] =
|
||||
GradeDistributionDataPoint(
|
||||
date = attempt.timestamp,
|
||||
grade = problem.difficulty.grade,
|
||||
gradeNumeric =
|
||||
gradeToNumeric(
|
||||
problem.difficulty.system,
|
||||
problem.difficulty.grade,
|
||||
),
|
||||
count = 1,
|
||||
climbType = problem.climbType,
|
||||
difficultySystem = problem.difficulty.system,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return gradeDistribution.values.toList()
|
||||
}
|
||||
|
||||
fun gradeToNumeric(system: DifficultySystem, grade: String): Int {
|
||||
return when (system) {
|
||||
DifficultySystem.V_SCALE -> {
|
||||
when (grade) {
|
||||
"VB" -> 0
|
||||
else -> grade.removePrefix("V").toIntOrNull() ?: 0
|
||||
}
|
||||
}
|
||||
DifficultySystem.FONT -> {
|
||||
when (grade) {
|
||||
"3" -> 3
|
||||
"4A" -> 4
|
||||
"4B" -> 5
|
||||
"4C" -> 6
|
||||
"5A" -> 7
|
||||
"5B" -> 8
|
||||
"5C" -> 9
|
||||
"6A" -> 10
|
||||
"6A+" -> 11
|
||||
"6B" -> 12
|
||||
"6B+" -> 13
|
||||
"6C" -> 14
|
||||
"6C+" -> 15
|
||||
"7A" -> 16
|
||||
"7A+" -> 17
|
||||
"7B" -> 18
|
||||
"7B+" -> 19
|
||||
"7C" -> 20
|
||||
"7C+" -> 21
|
||||
"8A" -> 22
|
||||
"8A+" -> 23
|
||||
"8B" -> 24
|
||||
"8B+" -> 25
|
||||
"8C" -> 26
|
||||
"8C+" -> 27
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
DifficultySystem.YDS -> {
|
||||
when (grade) {
|
||||
"5.0" -> 50
|
||||
"5.1" -> 51
|
||||
"5.2" -> 52
|
||||
"5.3" -> 53
|
||||
"5.4" -> 54
|
||||
"5.5" -> 55
|
||||
"5.6" -> 56
|
||||
"5.7" -> 57
|
||||
"5.8" -> 58
|
||||
"5.9" -> 59
|
||||
"5.10a" -> 60
|
||||
"5.10b" -> 61
|
||||
"5.10c" -> 62
|
||||
"5.10d" -> 63
|
||||
"5.11a" -> 64
|
||||
"5.11b" -> 65
|
||||
"5.11c" -> 66
|
||||
"5.11d" -> 67
|
||||
"5.12a" -> 68
|
||||
"5.12b" -> 69
|
||||
"5.12c" -> 70
|
||||
"5.12d" -> 71
|
||||
"5.13a" -> 72
|
||||
"5.13b" -> 73
|
||||
"5.13c" -> 74
|
||||
"5.13d" -> 75
|
||||
"5.14a" -> 76
|
||||
"5.14b" -> 77
|
||||
"5.14c" -> 78
|
||||
"5.14d" -> 79
|
||||
"5.15a" -> 80
|
||||
"5.15b" -> 81
|
||||
"5.15c" -> 82
|
||||
"5.15d" -> 83
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
DifficultySystem.CUSTOM -> {
|
||||
// Custom grades are numeric strings, so parse them directly
|
||||
grade.toIntOrNull() ?: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.screens
|
||||
package com.atridad.ascently.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
@@ -10,10 +10,10 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.painterResource
|
||||
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
|
||||
import com.atridad.ascently.R
|
||||
import com.atridad.ascently.data.model.Gym
|
||||
import com.atridad.ascently.ui.components.SyncIndicator
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -22,21 +22,21 @@ fun GymsScreen(viewModel: ClimbViewModel, onNavigateToGymDetail: (String) -> Uni
|
||||
|
||||
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 = "Ascently Logo",
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Text(
|
||||
text = "Climbing Gyms",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f)
|
||||
text = "Climbing Gyms",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
@@ -45,14 +45,14 @@ fun GymsScreen(viewModel: ClimbViewModel, onNavigateToGymDetail: (String) -> Uni
|
||||
|
||||
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 ->
|
||||
items(gyms, key = { it.id }) { gym ->
|
||||
GymCard(gym = gym, onClick = { onNavigateToGymDetail(gym.id) })
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
@@ -67,17 +67,17 @@ 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,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -86,9 +86,9 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
||||
Row {
|
||||
gym.supportedClimbTypes.forEach { climbType ->
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
label = { Text(climbType.getDisplayName()) },
|
||||
modifier = Modifier.padding(end = 4.dp)
|
||||
onClick = {},
|
||||
label = { Text(climbType.displayName) },
|
||||
modifier = Modifier.padding(end = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -96,10 +96,10 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
||||
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.displayName }}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -107,10 +107,10 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package com.atridad.ascently.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.ascently.R
|
||||
import com.atridad.ascently.data.model.Attempt
|
||||
import com.atridad.ascently.data.model.AttemptResult
|
||||
import com.atridad.ascently.data.model.ClimbType
|
||||
import com.atridad.ascently.data.model.Gym
|
||||
import com.atridad.ascently.data.model.Problem
|
||||
import com.atridad.ascently.ui.components.SyncIndicator
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String) -> Unit) {
|
||||
val problems by viewModel.problems.collectAsState()
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
val attempts by viewModel.attempts.collectAsState()
|
||||
|
||||
// Filter state
|
||||
var selectedClimbType by remember { mutableStateOf<ClimbType?>(null) }
|
||||
var selectedGym by remember { mutableStateOf<Gym?>(null) }
|
||||
|
||||
// Apply filters
|
||||
val filteredProblems = remember(problems, selectedClimbType, selectedGym) {
|
||||
problems.filter { problem ->
|
||||
val climbTypeMatch = selectedClimbType?.let { it == problem.climbType } != false
|
||||
val gymMatch = selectedGym?.let { it.id == problem.gymId } != false
|
||||
climbTypeMatch && gymMatch
|
||||
}
|
||||
}
|
||||
|
||||
// Separate active and inactive problems
|
||||
val activeProblems = remember(filteredProblems) { filteredProblems.filter { it.isActive } }
|
||||
val inactiveProblems = remember(filteredProblems) { filteredProblems.filter { !it.isActive } }
|
||||
val sortedProblems = remember(activeProblems, inactiveProblems) { activeProblems + inactiveProblems }
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "Ascently Logo",
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Text(
|
||||
text = "Climbing Problems",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Filters Section
|
||||
if (problems.isNotEmpty()) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Filters",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Climb Type Filter
|
||||
Text(
|
||||
text = "Climb Type",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
item {
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = null },
|
||||
label = { Text("All Types") },
|
||||
selected = selectedClimbType == null,
|
||||
)
|
||||
}
|
||||
items(ClimbType.entries) { climbType ->
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = climbType },
|
||||
label = { Text(climbType.displayName) },
|
||||
selected = selectedClimbType == climbType,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Gym Filter
|
||||
Text(
|
||||
text = "Gym",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
item {
|
||||
FilterChip(
|
||||
onClick = { selectedGym = null },
|
||||
label = { Text("All Gyms") },
|
||||
selected = selectedGym == null,
|
||||
)
|
||||
}
|
||||
items(gyms) { gym ->
|
||||
FilterChip(
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Filter result count
|
||||
if (selectedClimbType != null || selectedGym != null) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
text =
|
||||
"Showing ${filteredProblems.size} of ${problems.size} problems (${activeProblems.size} active, ${inactiveProblems.size} reset)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
|
||||
if (filteredProblems.isEmpty()) {
|
||||
EmptyStateMessage(
|
||||
title =
|
||||
if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty()) "No Gyms Available" else "No Problems Yet"
|
||||
} else {
|
||||
"No Problems Match Filters"
|
||||
},
|
||||
message =
|
||||
if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty()) {
|
||||
"Add a gym first to start tracking problems and routes!"
|
||||
} else {
|
||||
"Start tracking your favorite problems and routes!"
|
||||
}
|
||||
} else {
|
||||
"Try adjusting your filters to see more problems."
|
||||
},
|
||||
onActionClick = {},
|
||||
actionText = "",
|
||||
)
|
||||
} else {
|
||||
LazyColumn {
|
||||
items(sortedProblems, key = { it.id }) { problem ->
|
||||
ProblemCard(
|
||||
problem = problem,
|
||||
gymName = gyms.find { it.id == problem.gymId }?.name ?: "Unknown Gym",
|
||||
attempts = attempts,
|
||||
onClick = { onNavigateToProblemDetail(problem.id) },
|
||||
onToggleActive = {
|
||||
val updatedProblem = problem.copy(isActive = !problem.isActive)
|
||||
viewModel.updateProblem(updatedProblem)
|
||||
},
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ProblemCard(
|
||||
problem: Problem,
|
||||
gymName: String,
|
||||
attempts: List<Attempt>,
|
||||
onClick: () -> Unit,
|
||||
onToggleActive: (() -> Unit)? = null,
|
||||
) {
|
||||
val isCompleted =
|
||||
attempts.any { attempt ->
|
||||
attempt.problemId == problem.id &&
|
||||
(
|
||||
attempt.result == AttemptResult.SUCCESS ||
|
||||
attempt.result == AttemptResult.FLASH
|
||||
)
|
||||
}
|
||||
|
||||
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = problem.name ?: "Unnamed Problem",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color =
|
||||
if (problem.isActive) {
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
|
||||
},
|
||||
)
|
||||
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = if (problem.isActive) 1f else 0.6f,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (problem.imagePaths.isNotEmpty()) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Image,
|
||||
contentDescription = "Has images",
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
|
||||
if (isCompleted) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CheckCircle,
|
||||
contentDescription = "Completed",
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.tertiary,
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = problem.difficulty.grade,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = problem.climbType.displayName,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
problem.location?.let { location ->
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Location: $location",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
if (problem.tags.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Row {
|
||||
problem.tags.take(3).forEach { tag ->
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
label = { Text(tag) },
|
||||
modifier = Modifier.padding(end = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!problem.isActive) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "Reset / No Longer Set",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.tertiary,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
}
|
||||
|
||||
// Toggle active button
|
||||
if (onToggleActive != null) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
OutlinedButton(
|
||||
onClick = onToggleActive,
|
||||
colors =
|
||||
ButtonDefaults.outlinedButtonColors(
|
||||
contentColor =
|
||||
if (problem.isActive) {
|
||||
MaterialTheme.colorScheme.tertiary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.primary
|
||||
},
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
text = if (problem.isActive) "Mark as Reset" else "Mark as Active",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
package com.atridad.ascently.ui.screens
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.List
|
||||
import androidx.compose.material.icons.filled.CalendarMonth
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.edit
|
||||
import com.atridad.ascently.R
|
||||
import com.atridad.ascently.data.model.ClimbSession
|
||||
import com.atridad.ascently.data.model.SessionStatus
|
||||
import com.atridad.ascently.ui.components.ActiveSessionBanner
|
||||
import com.atridad.ascently.ui.components.SyncIndicator
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||
import com.atridad.ascently.utils.DateFormatUtils
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.TextStyle
|
||||
import java.util.Locale
|
||||
|
||||
enum class ViewMode {
|
||||
LIST,
|
||||
CALENDAR,
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
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()
|
||||
|
||||
val sharedPreferences =
|
||||
context.getSharedPreferences("SessionsPreferences", Context.MODE_PRIVATE)
|
||||
val savedViewMode = sharedPreferences.getString("view_mode", "LIST")
|
||||
var viewMode by remember {
|
||||
mutableStateOf(if (savedViewMode == "CALENDAR") ViewMode.CALENDAR else ViewMode.LIST)
|
||||
}
|
||||
var selectedMonth by remember { mutableStateOf(YearMonth.now()) }
|
||||
var selectedDate by remember { mutableStateOf<LocalDate?>(LocalDate.now()) }
|
||||
|
||||
val completedSessions = remember(sessions) {
|
||||
sessions.filter { it.status == SessionStatus.COMPLETED }
|
||||
}
|
||||
val activeSessionGym = remember(activeSession, gyms) {
|
||||
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),
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "Ascently Logo",
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Text(
|
||||
text = "Climbing Sessions",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
|
||||
IconButton(
|
||||
onClick = {
|
||||
viewMode =
|
||||
if (viewMode == ViewMode.LIST) ViewMode.CALENDAR else ViewMode.LIST
|
||||
selectedDate = null
|
||||
sharedPreferences.edit { putString("view_mode", viewMode.name) }
|
||||
},
|
||||
) {
|
||||
Icon(
|
||||
imageVector =
|
||||
if (viewMode == ViewMode.LIST) {
|
||||
Icons.Default.CalendarMonth
|
||||
} else {
|
||||
Icons.AutoMirrored.Filled.List
|
||||
},
|
||||
contentDescription =
|
||||
if (viewMode == ViewMode.LIST) "Calendar View" else "List View",
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
ActiveSessionBanner(
|
||||
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 = "",
|
||||
)
|
||||
} else {
|
||||
when (viewMode) {
|
||||
ViewMode.LIST -> {
|
||||
LazyColumn {
|
||||
items(completedSessions, key = { it.id }) { session ->
|
||||
SessionCard(
|
||||
session = session,
|
||||
gymName = gyms.find { it.id == session.gymId }?.name
|
||||
?: "Unknown Gym",
|
||||
onClick = { onNavigateToSessionDetail(session.id) },
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
ViewMode.CALENDAR -> {
|
||||
CalendarView(
|
||||
sessions = completedSessions,
|
||||
gyms = gyms,
|
||||
selectedMonth = selectedMonth,
|
||||
onMonthChange = { selectedMonth = it },
|
||||
selectedDate = selectedDate,
|
||||
onDateSelected = { selectedDate = it },
|
||||
onNavigateToSessionDetail = onNavigateToSessionDetail,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SessionCard(session: ClimbSession, gymName: String, onClick: () -> Unit) {
|
||||
val formattedDate = remember(session.date) {
|
||||
DateFormatUtils.formatDateForDisplay(session.date)
|
||||
}
|
||||
|
||||
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Text(
|
||||
text = formattedDate,
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmptyStateMessage(
|
||||
title: String,
|
||||
message: String,
|
||||
onActionClick: () -> Unit,
|
||||
actionText: String,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
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,
|
||||
)
|
||||
|
||||
if (actionText.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Button(onClick = onActionClick) { Text(actionText) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CalendarView(
|
||||
sessions: List<ClimbSession>,
|
||||
gyms: List<com.atridad.ascently.data.model.Gym>,
|
||||
selectedMonth: YearMonth,
|
||||
onMonthChange: (YearMonth) -> Unit,
|
||||
selectedDate: LocalDate?,
|
||||
onDateSelected: (LocalDate?) -> Unit,
|
||||
onNavigateToSessionDetail: (String) -> Unit,
|
||||
) {
|
||||
val sessionsByDate =
|
||||
remember(sessions) {
|
||||
sessions.groupBy {
|
||||
try {
|
||||
java.time.Instant.parse(it.date)
|
||||
.atZone(java.time.ZoneId.systemDefault())
|
||||
.toLocalDate()
|
||||
} catch (_: Exception) {
|
||||
LocalDate.parse(it.date, DateTimeFormatter.ISO_LOCAL_DATE)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val firstDayOfMonth = selectedMonth.atDay(1)
|
||||
val daysInMonth = selectedMonth.lengthOfMonth()
|
||||
val firstDayOfWeek = firstDayOfMonth.dayOfWeek.value % 7
|
||||
val totalCells =
|
||||
((firstDayOfWeek + daysInMonth) / 7.0).let {
|
||||
if (it == it.toInt().toDouble()) it.toInt() * 7 else (it.toInt() + 1) * 7
|
||||
}
|
||||
val numRows = totalCells / 7
|
||||
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
),
|
||||
) {
|
||||
Column(
|
||||
modifier =
|
||||
Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
IconButton(onClick = { onMonthChange(selectedMonth.minusMonths(1)) }) {
|
||||
Text("‹", style = MaterialTheme.typography.headlineMedium)
|
||||
}
|
||||
|
||||
Text(
|
||||
text =
|
||||
"${selectedMonth.month.getDisplayName(TextStyle.FULL, Locale.getDefault())} ${selectedMonth.year}",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
IconButton(onClick = { onMonthChange(selectedMonth.plusMonths(1)) }) {
|
||||
Text("›", style = MaterialTheme.typography.headlineMedium)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
val today = LocalDate.now()
|
||||
onMonthChange(YearMonth.from(today))
|
||||
onDateSelected(today)
|
||||
},
|
||||
shape = RoundedCornerShape(50),
|
||||
colors =
|
||||
ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
),
|
||||
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "Today",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
listOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat").forEach { day ->
|
||||
Text(
|
||||
text = day,
|
||||
modifier = Modifier.weight(1f),
|
||||
textAlign = TextAlign.Center,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
items(numRows) { rowIndex ->
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
for (colIndex in 0 until 7) {
|
||||
val index = rowIndex * 7 + colIndex
|
||||
val dayNumber = index - firstDayOfWeek + 1
|
||||
|
||||
Box(modifier = Modifier.weight(1f)) {
|
||||
if (dayNumber in 1..daysInMonth) {
|
||||
val date = selectedMonth.atDay(dayNumber)
|
||||
val sessionsOnDate = sessionsByDate[date] ?: emptyList()
|
||||
val isSelected = date == selectedDate
|
||||
val isToday = date == LocalDate.now()
|
||||
|
||||
CalendarDay(
|
||||
day = dayNumber,
|
||||
hasSession = sessionsOnDate.isNotEmpty(),
|
||||
isSelected = isSelected,
|
||||
isToday = isToday,
|
||||
onClick = {
|
||||
if (sessionsOnDate.isNotEmpty()) {
|
||||
onDateSelected(if (isSelected) null else date)
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Spacer(modifier = Modifier.aspectRatio(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedDate != null) {
|
||||
val sessionsOnSelectedDate = sessionsByDate[selectedDate] ?: emptyList()
|
||||
|
||||
item {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
"Sessions on ${selectedDate.format(DateTimeFormatter.ofPattern("MMMM d, yyyy"))}",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
items(sessionsOnSelectedDate) { session ->
|
||||
SessionCard(
|
||||
session = session,
|
||||
gymName = gyms.find { it.id == session.gymId }?.name ?: "Unknown Gym",
|
||||
onClick = { onNavigateToSessionDetail(session.id) },
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
item { Spacer(modifier = Modifier.height(16.dp)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CalendarDay(
|
||||
day: Int,
|
||||
hasSession: Boolean,
|
||||
isSelected: Boolean,
|
||||
isToday: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier.aspectRatio(1f)
|
||||
.padding(2.dp)
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
when {
|
||||
isSelected -> MaterialTheme.colorScheme.primaryContainer
|
||||
isToday -> MaterialTheme.colorScheme.secondaryContainer
|
||||
else -> Color.Transparent
|
||||
},
|
||||
)
|
||||
.clickable(enabled = hasSession, onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
text = day.toString(),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color =
|
||||
when {
|
||||
isSelected -> MaterialTheme.colorScheme.onPrimaryContainer
|
||||
isToday -> MaterialTheme.colorScheme.onSecondaryContainer
|
||||
!hasSession -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
else -> MaterialTheme.colorScheme.onSurface
|
||||
},
|
||||
fontWeight = if (hasSession || isToday) FontWeight.Bold else FontWeight.Normal,
|
||||
)
|
||||
|
||||
if (hasSession) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier.size(6.dp)
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
if (isSelected) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.primary.copy(
|
||||
alpha = 0.7f,
|
||||
)
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,972 @@
|
||||
package com.atridad.ascently.ui.screens
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.ascently.R
|
||||
import com.atridad.ascently.ui.components.SyncIndicator
|
||||
import com.atridad.ascently.ui.health.HealthConnectCard
|
||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(viewModel: ClimbViewModel) {
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
val context = LocalContext.current
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
|
||||
// Sync service state
|
||||
val syncService = viewModel.syncService
|
||||
val isSyncing by syncService.isSyncing.collectAsState()
|
||||
val isConnected by syncService.isConnected.collectAsState()
|
||||
val isConfigured by syncService.isConfiguredFlow.collectAsState()
|
||||
val isTesting by syncService.isTesting.collectAsState()
|
||||
val lastSyncTime by syncService.lastSyncTime.collectAsState()
|
||||
val syncError by syncService.syncError.collectAsState()
|
||||
val isAutoSyncEnabled by syncService.isAutoSyncEnabled.collectAsState()
|
||||
|
||||
// State for dialogs
|
||||
var showResetDialog by remember { mutableStateOf(false) }
|
||||
var showSyncConfigDialog by remember { mutableStateOf(false) }
|
||||
var showDisconnectDialog by remember { mutableStateOf(false) }
|
||||
|
||||
var showDeleteImagesDialog by remember { mutableStateOf(false) }
|
||||
|
||||
var isDeletingImages by remember { mutableStateOf(false) }
|
||||
|
||||
// Sync configuration state
|
||||
var serverUrl by remember { mutableStateOf(syncService.serverUrl) }
|
||||
var authToken by remember { mutableStateOf(syncService.authToken) }
|
||||
|
||||
val packageInfo = remember { context.packageManager.getPackageInfo(context.packageName, 0) }
|
||||
val appVersion = packageInfo.versionName
|
||||
|
||||
// Update local state when sync service configuration changes
|
||||
LaunchedEffect(syncService.serverUrl, syncService.authToken) {
|
||||
serverUrl = syncService.serverUrl
|
||||
authToken = syncService.authToken
|
||||
}
|
||||
|
||||
// File picker launcher for import - only accepts ZIP files
|
||||
val importLauncher =
|
||||
rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri,
|
||||
->
|
||||
uri?.let {
|
||||
try {
|
||||
val inputStream = context.contentResolver.openInputStream(uri)
|
||||
// Determine file extension from content resolver
|
||||
val fileName =
|
||||
context.contentResolver.query(uri, null, null, null, null)?.use {
|
||||
cursor ->
|
||||
val nameIndex =
|
||||
cursor.getColumnIndex(
|
||||
android.provider.OpenableColumns.DISPLAY_NAME,
|
||||
)
|
||||
if (nameIndex >= 0 && cursor.moveToFirst()) {
|
||||
cursor.getString(nameIndex)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
?: "import_file"
|
||||
|
||||
// Only allow ZIP files
|
||||
if (!fileName.lowercase().endsWith(".zip")) {
|
||||
viewModel.setError(
|
||||
"Only ZIP files are supported for import. Please use a ZIP file exported from Ascently.",
|
||||
)
|
||||
return@let
|
||||
}
|
||||
|
||||
val tempFile = File(context.cacheDir, "temp_import.zip")
|
||||
|
||||
inputStream?.use { input ->
|
||||
tempFile.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
viewModel.importData(tempFile)
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError("Failed to read file: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// File picker launcher for export - ZIP format with images
|
||||
val exportZipLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("application/zip"),
|
||||
) { uri ->
|
||||
uri?.let {
|
||||
try {
|
||||
viewModel.exportDataToZipUri(context, uri)
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError("Failed to save file: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
item {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "Ascently Logo",
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Text(
|
||||
text = "Settings",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
}
|
||||
|
||||
// Sync Section
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Sync",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
if (isConfigured) {
|
||||
// Connected state
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
if (isConnected) {
|
||||
MaterialTheme.colorScheme
|
||||
.primaryContainer.copy(
|
||||
alpha = 0.3f,
|
||||
)
|
||||
} else {
|
||||
MaterialTheme.colorScheme
|
||||
.surfaceVariant.copy(
|
||||
alpha = 0.3f,
|
||||
)
|
||||
},
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = {
|
||||
Text(
|
||||
if (isConnected) {
|
||||
"Connected to Server"
|
||||
} else {
|
||||
"Server Configured"
|
||||
},
|
||||
)
|
||||
},
|
||||
supportingContent = {
|
||||
Column {
|
||||
Text("Server: ${syncService.serverUrl}")
|
||||
lastSyncTime?.let { time ->
|
||||
Text(
|
||||
"Last sync: ${
|
||||
try {
|
||||
Instant.parse(time).toString()
|
||||
} catch (_: Exception) {
|
||||
time
|
||||
}
|
||||
}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (isConnected) {
|
||||
Icons.Default.CloudDone
|
||||
} else {
|
||||
Icons.Default.Cloud
|
||||
},
|
||||
contentDescription = null,
|
||||
tint =
|
||||
if (isConnected) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme
|
||||
.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// Manual Sync Button
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.performManualSync()
|
||||
},
|
||||
enabled = isConnected && !isSyncing,
|
||||
) {
|
||||
if (isSyncing) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text("Sync")
|
||||
}
|
||||
}
|
||||
|
||||
// Configure Button
|
||||
TextButton(onClick = { showSyncConfigDialog = true }) {
|
||||
Text("Configure")
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
// Auto-sync settings
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant
|
||||
.copy(alpha = 0.3f),
|
||||
),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Sync Mode",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Auto-sync")
|
||||
Text(
|
||||
text =
|
||||
"Sync automatically on app launch and data changes",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurface.copy(
|
||||
alpha = 0.7f,
|
||||
),
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
Switch(
|
||||
checked = isAutoSyncEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
syncService.setAutoSyncEnabled(enabled)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
// Disconnect option
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer
|
||||
.copy(alpha = 0.3f),
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Disconnect") },
|
||||
supportingContent = { Text("Clear sync configuration") },
|
||||
leadingContent = {
|
||||
Icon(
|
||||
Icons.Default.CloudOff,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(onClick = { showDisconnectDialog = true }) {
|
||||
Text(
|
||||
"Disconnect",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Not configured state
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant
|
||||
.copy(alpha = 0.3f),
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Setup Sync") },
|
||||
supportingContent = {
|
||||
Text("Connect to your Ascently sync server")
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.CloudSync, contentDescription = null)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(onClick = { showSyncConfigDialog = true }) {
|
||||
Text("Setup")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Show sync error if any
|
||||
syncError?.let { error ->
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item { HealthConnectCard() }
|
||||
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Data Management",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Export Data
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Export Data with Images") },
|
||||
supportingContent = {
|
||||
Text(
|
||||
"Export all your climbing data and images to ZIP file (recommended)",
|
||||
)
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.Share, contentDescription = null)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
val defaultFileName =
|
||||
"ascently_export_${
|
||||
java.time.LocalDateTime.now()
|
||||
.toString()
|
||||
.replace(":", "-")
|
||||
.replace(".", "-")
|
||||
}.zip"
|
||||
exportZipLauncher.launch(defaultFileName)
|
||||
},
|
||||
enabled = !uiState.isLoading,
|
||||
) {
|
||||
if (uiState.isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text("Export ZIP")
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Import Data") },
|
||||
supportingContent = {
|
||||
Text("Import climbing data from ZIP file (recommended format)")
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.Add, contentDescription = null)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = { importLauncher.launch("application/zip") },
|
||||
enabled = !uiState.isLoading,
|
||||
) {
|
||||
if (uiState.isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text("Import")
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.3f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Delete All Images") },
|
||||
supportingContent = {
|
||||
Text("Permanently delete all image files from device")
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(
|
||||
Icons.Default.Delete,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = { showDeleteImagesDialog = true },
|
||||
enabled = !isDeletingImages && !uiState.isLoading,
|
||||
) {
|
||||
if (isDeletingImages) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text("Delete", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.3f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Reset All Data") },
|
||||
supportingContent = {
|
||||
Text(
|
||||
"Permanently delete all gyms, problems, sessions, attempts, and images",
|
||||
)
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(
|
||||
Icons.Default.Delete,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = { showResetDialog = true },
|
||||
enabled = !uiState.isLoading,
|
||||
) {
|
||||
if (uiState.isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text("Reset", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// App Information Section
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "App Information",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f,
|
||||
),
|
||||
),
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Version") },
|
||||
supportingContent = { Text(appVersion ?: "Unknown") },
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.Info, contentDescription = null)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show loading/message states
|
||||
if (uiState.isLoading) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset confirmation dialog
|
||||
if (showResetDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showResetDialog = false },
|
||||
title = { Text("Reset All Data") },
|
||||
text = {
|
||||
Column {
|
||||
Text("Are you sure you want to reset all data?")
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "This will permanently delete:",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text =
|
||||
"• All gyms and their information\n• All problems and their images\n• All climbing sessions\n• All attempts and progress data",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text =
|
||||
"This action cannot be undone. Consider exporting your data first.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.resetAllData()
|
||||
showResetDialog = false
|
||||
},
|
||||
) { Text("Reset All Data", color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showResetDialog = false }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Sync Configuration Dialog
|
||||
if (showSyncConfigDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showSyncConfigDialog = false },
|
||||
title = { Text("Sync Configuration") },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = serverUrl,
|
||||
onValueChange = { serverUrl = it },
|
||||
label = { Text("Server URL") },
|
||||
placeholder = { Text("https://your-server.com") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = authToken,
|
||||
onValueChange = { authToken = it },
|
||||
label = { Text("Auth Token") },
|
||||
placeholder = { Text("your-secret-token") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Connection status indicator
|
||||
if (isTesting) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Testing connection...",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
} else if (isConnected && isConfigured) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.CheckCircle,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Connection successful",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
} else if (syncError != null && isConfigured) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Error,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Connection failed: $syncError",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
} else if (isConfigured) {
|
||||
Text(
|
||||
text = "Test connection before enabling sync features",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = "Enter your server URL and auth token to enable sync",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Row {
|
||||
// Primary action: Save & Test
|
||||
Button(
|
||||
onClick = {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
syncService.serverUrl = serverUrl.trim()
|
||||
syncService.authToken = authToken.trim()
|
||||
viewModel.testSyncConnection()
|
||||
while (syncService.isTesting.value) {
|
||||
kotlinx.coroutines.delay(100)
|
||||
}
|
||||
showSyncConfigDialog = false
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError(
|
||||
"Failed to save and test: ${e.message}",
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled =
|
||||
!isTesting &&
|
||||
serverUrl.isNotBlank() &&
|
||||
authToken.isNotBlank(),
|
||||
) {
|
||||
if (isTesting) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Save & Test")
|
||||
}
|
||||
} else {
|
||||
Text("Save & Test")
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
// Secondary action: Test only (when already configured)
|
||||
if (isConfigured) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
syncService.serverUrl = serverUrl.trim()
|
||||
syncService.authToken = authToken.trim()
|
||||
viewModel.testSyncConnection()
|
||||
while (syncService.isTesting.value) {
|
||||
kotlinx.coroutines.delay(100)
|
||||
}
|
||||
if (isConnected) {
|
||||
showSyncConfigDialog = false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError(
|
||||
"Connection test failed: ${e.message}",
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled =
|
||||
!isTesting &&
|
||||
serverUrl.isNotBlank() &&
|
||||
authToken.isNotBlank(),
|
||||
) { Text("Test Only") }
|
||||
}
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
serverUrl = syncService.serverUrl
|
||||
authToken = syncService.authToken
|
||||
showSyncConfigDialog = false
|
||||
},
|
||||
) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Disconnect Dialog
|
||||
if (showDisconnectDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showDisconnectDialog = false },
|
||||
title = { Text("Disconnect from Sync") },
|
||||
text = {
|
||||
Text(
|
||||
"Are you sure you want to disconnect from the sync server? This will clear your server configuration and disable auto-sync.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.syncService.clearConfiguration()
|
||||
showDisconnectDialog = false
|
||||
},
|
||||
) { Text("Disconnect") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDisconnectDialog = false }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Delete All Images dialog
|
||||
if (showDeleteImagesDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showDeleteImagesDialog = false },
|
||||
title = { Text("Delete All Images") },
|
||||
text = {
|
||||
Text(
|
||||
"This will permanently delete ALL image files from your device." +
|
||||
"\n\nProblems will keep their references but the actual image files " +
|
||||
"will be removed. This cannot be undone." +
|
||||
"\n\nConsider exporting your data first if you want to keep your images.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
isDeletingImages = true
|
||||
showDeleteImagesDialog = false
|
||||
coroutineScope.launch {
|
||||
viewModel.deleteAllImages()
|
||||
isDeletingImages = false
|
||||
viewModel.setMessage("All images deleted successfully!")
|
||||
}
|
||||
},
|
||||
) { Text("Delete", color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDeleteImagesDialog = false }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.theme
|
||||
package com.atridad.ascently.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
@@ -63,4 +63,4 @@ val ClimbNeutralVariant30 = Color(0xFF484848)
|
||||
val ClimbNeutralVariant50 = Color(0xFF797979)
|
||||
val ClimbNeutralVariant60 = Color(0xFF939393)
|
||||
val ClimbNeutralVariant80 = Color(0xFFC7C7C7)
|
||||
val ClimbNeutralVariant90 = Color(0xFFE3E3E3)
|
||||
val ClimbNeutralVariant90 = Color(0xFFE3E3E3)
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.theme
|
||||
package com.atridad.ascently.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
@@ -12,9 +12,9 @@ object CustomIcons {
|
||||
defaultWidth = 24.dp,
|
||||
defaultHeight = 24.dp,
|
||||
viewportWidth = 24f,
|
||||
viewportHeight = 24f
|
||||
viewportHeight = 24f,
|
||||
).path(
|
||||
fill = SolidColor(color)
|
||||
fill = SolidColor(color),
|
||||
) {
|
||||
moveTo(6f, 6f)
|
||||
horizontalLineTo(18f)
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.theme
|
||||
package com.atridad.ascently.ui.theme
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
@@ -47,7 +47,7 @@ private val DarkColorScheme = darkColorScheme(
|
||||
surfaceContainerLow = ClimbNeutral10,
|
||||
surfaceContainer = ClimbNeutral12,
|
||||
surfaceContainerHigh = ClimbNeutral17,
|
||||
surfaceContainerHighest = ClimbNeutral22
|
||||
surfaceContainerHighest = ClimbNeutral22,
|
||||
)
|
||||
|
||||
// Climbing-themed light color scheme with full Material You compatibility
|
||||
@@ -84,16 +84,16 @@ private val LightColorScheme = lightColorScheme(
|
||||
surfaceContainerLow = ClimbNeutral96,
|
||||
surfaceContainer = ClimbNeutral94,
|
||||
surfaceContainerHigh = ClimbNeutral92,
|
||||
surfaceContainerHighest = ClimbNeutral90
|
||||
surfaceContainerHighest = ClimbNeutral90,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun OpenClimbTheme(
|
||||
fun AscentlyTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
// Dynamic color is available on Android 12+ and provides full Material You theming
|
||||
// When enabled, it adapts to the user's system wallpaper colors
|
||||
dynamicColor: Boolean = true,
|
||||
content: @Composable () -> Unit
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colorScheme = when {
|
||||
dynamicColor && true -> {
|
||||
@@ -103,7 +103,7 @@ fun OpenClimbTheme(
|
||||
darkTheme -> DarkColorScheme
|
||||
else -> LightColorScheme
|
||||
}
|
||||
|
||||
|
||||
val view = LocalView.current
|
||||
if (!view.isInEditMode) {
|
||||
SideEffect {
|
||||
@@ -116,6 +116,6 @@ fun OpenClimbTheme(
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = Typography,
|
||||
content = content
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.ui.theme
|
||||
package com.atridad.ascently.ui.theme
|
||||
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
@@ -13,6 +13,6 @@ val Typography = Typography(
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
)
|
||||
)
|
||||
letterSpacing = 0.5.sp,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,493 @@
|
||||
package com.atridad.ascently.ui.viewmodel
|
||||
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.atridad.ascently.data.health.HealthConnectManager
|
||||
import com.atridad.ascently.data.model.*
|
||||
import com.atridad.ascently.data.repository.ClimbRepository
|
||||
import com.atridad.ascently.data.sync.SyncService
|
||||
import com.atridad.ascently.service.SessionTrackingService
|
||||
import com.atridad.ascently.utils.AppLogger
|
||||
import com.atridad.ascently.utils.ImageUtils
|
||||
import com.atridad.ascently.widget.ClimbStatsWidgetProvider
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
|
||||
class ClimbViewModel(
|
||||
private val repository: ClimbRepository,
|
||||
val syncService: SyncService,
|
||||
private val context: Context,
|
||||
) : ViewModel() {
|
||||
|
||||
// Health Connect manager
|
||||
private val healthConnectManager = HealthConnectManager(context)
|
||||
|
||||
// UI State flows
|
||||
private val _uiState = MutableStateFlow(ClimbUiState())
|
||||
val uiState: StateFlow<ClimbUiState> = _uiState.asStateFlow()
|
||||
|
||||
// Data flows
|
||||
val gyms =
|
||||
repository
|
||||
.getAllGyms()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList(),
|
||||
)
|
||||
|
||||
val problems =
|
||||
repository
|
||||
.getAllProblems()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList(),
|
||||
)
|
||||
|
||||
val sessions =
|
||||
repository
|
||||
.getAllSessions()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList(),
|
||||
)
|
||||
|
||||
val activeSession =
|
||||
repository
|
||||
.getActiveSessionFlow()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = null,
|
||||
)
|
||||
|
||||
val attempts =
|
||||
repository
|
||||
.getAllAttempts()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList(),
|
||||
)
|
||||
|
||||
// Gym operations
|
||||
fun addGym(gym: Gym, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.insertGym(gym)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateGym(gym: Gym, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.updateGym(gym)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteGym(gym: Gym, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.deleteGym(gym)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getGymById(id: String): Flow<Gym?> = flow { emit(repository.getGymById(id)) }
|
||||
|
||||
// Problem operations
|
||||
fun addProblem(problem: Problem, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
val finalProblem = renameTemporaryImages(problem)
|
||||
repository.insertProblem(finalProblem)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun renameTemporaryImages(problem: Problem): Problem {
|
||||
if (problem.imagePaths.isEmpty()) {
|
||||
return problem
|
||||
}
|
||||
|
||||
val finalImagePaths = mutableListOf<String>()
|
||||
|
||||
problem.imagePaths.forEachIndexed { index, tempPath ->
|
||||
if (tempPath.startsWith("temp_")) {
|
||||
val finalPath =
|
||||
ImageUtils.renameTemporaryImage(context, tempPath, problem.id, index)
|
||||
finalImagePaths.add(finalPath ?: tempPath)
|
||||
} else {
|
||||
finalImagePaths.add(tempPath)
|
||||
}
|
||||
}
|
||||
|
||||
return problem.copy(imagePaths = finalImagePaths)
|
||||
}
|
||||
|
||||
fun updateProblem(problem: Problem, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
val finalProblem = renameTemporaryImages(problem)
|
||||
repository.updateProblem(finalProblem)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteProblem(problem: Problem, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
problem.imagePaths.forEach { imagePath -> ImageUtils.deleteImage(context, imagePath) }
|
||||
repository.deleteProblem(problem)
|
||||
cleanupOrphanedImages()
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun cleanupOrphanedImages() {
|
||||
val allProblems = repository.getAllProblems().first()
|
||||
val referencedImagePaths = allProblems.flatMap { it.imagePaths }.toSet()
|
||||
ImageUtils.cleanupOrphanedImages(context, referencedImagePaths)
|
||||
}
|
||||
|
||||
fun deleteAllImages() {
|
||||
viewModelScope.launch {
|
||||
val imagesDir = ImageUtils.getImagesDirectory(context)
|
||||
var deletedCount = 0
|
||||
|
||||
imagesDir.listFiles()?.forEach { file ->
|
||||
if (file.isFile && file.extension.lowercase() == "jpg") {
|
||||
if (file.delete()) {
|
||||
deletedCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val allProblems = repository.getAllProblems().first()
|
||||
val updatedProblems =
|
||||
allProblems.map { problem ->
|
||||
if (problem.imagePaths.isNotEmpty()) {
|
||||
problem.copy(imagePaths = emptyList())
|
||||
} else {
|
||||
problem
|
||||
}
|
||||
}
|
||||
|
||||
for (updatedProblem in updatedProblems) {
|
||||
if (updatedProblem.imagePaths !=
|
||||
allProblems.find { it.id == updatedProblem.id }?.imagePaths
|
||||
) {
|
||||
repository.insertProblemWithoutSync(updatedProblem)
|
||||
}
|
||||
}
|
||||
|
||||
AppLogger.i("ClimbViewModel") { "Deleted $deletedCount image files and cleared image references" }
|
||||
}
|
||||
}
|
||||
|
||||
fun getProblemById(id: String): Flow<Problem?> = flow { emit(repository.getProblemById(id)) }
|
||||
|
||||
fun getProblemsByGym(gymId: String): Flow<List<Problem>> = repository.getProblemsByGym(gymId)
|
||||
|
||||
// Session operations
|
||||
|
||||
fun updateSession(session: ClimbSession, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.updateSession(session)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteSession(session: ClimbSession, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.deleteSession(session)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getSessionById(id: String): Flow<ClimbSession?> = flow {
|
||||
emit(repository.getSessionById(id))
|
||||
}
|
||||
|
||||
fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>> =
|
||||
repository.getSessionsByGym(gymId)
|
||||
|
||||
// Get last used gym for shortcut functionality
|
||||
suspend fun getLastUsedGym(): Gym? = repository.getLastUsedGym()
|
||||
|
||||
// Active session management
|
||||
fun startSession(context: Context, gymId: String, notes: String? = null) {
|
||||
viewModelScope.launch {
|
||||
AppLogger.d("ClimbViewModel") { "startSession called with gymId: $gymId" }
|
||||
|
||||
if (!com.atridad.ascently.utils.NotificationPermissionUtils
|
||||
.isNotificationPermissionGranted(context)
|
||||
) {
|
||||
AppLogger.d("ClimbViewModel") { "Notification permission not granted" }
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error =
|
||||
"Notification permission is required to track your climbing session. Please enable notifications in settings.",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val existingActive = repository.getActiveSession()
|
||||
if (existingActive != null) {
|
||||
AppLogger.d("ClimbViewModel") { "Active session already exists: ${existingActive.id}" }
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error = "There's already an active session. Please end it first.",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
AppLogger.d("ClimbViewModel") { "Creating new session" }
|
||||
val newSession = ClimbSession.create(gymId = gymId, notes = notes)
|
||||
repository.insertSession(newSession)
|
||||
|
||||
AppLogger.d("ClimbViewModel") { "Starting tracking service for session: ${newSession.id}" }
|
||||
// Start the tracking service
|
||||
val serviceIntent = SessionTrackingService.createStartIntent(context, newSession.id)
|
||||
context.startForegroundService(serviceIntent)
|
||||
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
|
||||
_uiState.value = _uiState.value.copy(message = "Session started successfully!")
|
||||
}
|
||||
}
|
||||
|
||||
fun endSession(context: Context, sessionId: String) {
|
||||
viewModelScope.launch {
|
||||
if (!com.atridad.ascently.utils.NotificationPermissionUtils
|
||||
.isNotificationPermissionGranted(context)
|
||||
) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error =
|
||||
"Notification permission is required to manage your climbing session. Please enable notifications in settings.",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val session = repository.getSessionById(sessionId)
|
||||
if (session != null && session.status == SessionStatus.ACTIVE) {
|
||||
val completedSession = with(ClimbSession) { session.complete() }
|
||||
repository.updateSession(completedSession)
|
||||
|
||||
val serviceIntent = SessionTrackingService.createStopIntent(context, sessionId)
|
||||
context.startService(serviceIntent)
|
||||
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
|
||||
syncToHealthConnect(completedSession)
|
||||
|
||||
_uiState.value = _uiState.value.copy(message = "Session completed!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun ensureSessionTrackingServiceRunning(context: Context) {
|
||||
viewModelScope.launch {
|
||||
val activeSession = repository.getActiveSession()
|
||||
if (activeSession != null && activeSession.status == SessionStatus.ACTIVE) {
|
||||
val serviceIntent =
|
||||
SessionTrackingService.createStartIntent(context, activeSession.id)
|
||||
context.startForegroundService(serviceIntent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attempt operations
|
||||
fun addAttempt(attempt: Attempt, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.insertAttempt(attempt)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAttempt(attempt: Attempt, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.deleteAttempt(attempt)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateAttempt(attempt: Attempt, updateWidgets: Boolean = true) {
|
||||
viewModelScope.launch {
|
||||
repository.updateAttempt(attempt)
|
||||
if (updateWidgets) {
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getAttemptsBySession(sessionId: String): Flow<List<Attempt>> =
|
||||
repository.getAttemptsBySession(sessionId)
|
||||
|
||||
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>> =
|
||||
repository.getAttemptsByProblem(problemId)
|
||||
|
||||
fun exportDataToZipUri(context: Context, uri: android.net.Uri) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = true,
|
||||
message = "Creating ZIP file with images...",
|
||||
)
|
||||
repository.exportAllDataToZipUri(context, uri)
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
message =
|
||||
"Export complete! Your climbing data and images have been saved.",
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
error = "Export failed: ${e.message}",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun importData(file: File) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
|
||||
if (!file.name.lowercase().endsWith(".zip")) {
|
||||
throw Exception(
|
||||
"Only ZIP files are supported for import. Please use a ZIP file exported from Ascently.",
|
||||
)
|
||||
}
|
||||
|
||||
repository.importDataFromZip(file)
|
||||
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
message = "Data imported successfully from ${file.name}",
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
error = "Import failed: ${e.message}",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UI state operations
|
||||
fun clearMessage() {
|
||||
_uiState.value = _uiState.value.copy(message = null)
|
||||
}
|
||||
|
||||
fun clearError() {
|
||||
_uiState.value = _uiState.value.copy(error = null)
|
||||
}
|
||||
|
||||
// Sync-related methods
|
||||
fun performManualSync() {
|
||||
viewModelScope.launch {
|
||||
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)
|
||||
}
|
||||
|
||||
fun setMessage(message: String) {
|
||||
_uiState.value = _uiState.value.copy(message = message)
|
||||
}
|
||||
|
||||
fun resetAllData() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
|
||||
repository.resetAllData()
|
||||
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
message = "All data has been reset successfully",
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(isLoading = false, error = "Reset failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun syncToHealthConnect(session: ClimbSession) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val gym = repository.getGymById(session.gymId)
|
||||
val gymName = gym?.name ?: "Unknown Gym"
|
||||
|
||||
val attempts = repository.getAttemptsBySession(session.id).first()
|
||||
val attemptCount = attempts.size
|
||||
|
||||
val result =
|
||||
healthConnectManager.autoSyncCompletedSession(
|
||||
session,
|
||||
gymName,
|
||||
attemptCount,
|
||||
)
|
||||
|
||||
result.onFailure { error ->
|
||||
if (healthConnectManager.isReadySync()) {
|
||||
AppLogger.w("ClimbViewModel") { "Health Connect sync failed: ${error.message}" }
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (healthConnectManager.isReadySync()) {
|
||||
AppLogger.w("ClimbViewModel") { "Health Connect sync error: ${e.message}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ClimbUiState(
|
||||
val isLoading: Boolean = false,
|
||||
val message: String? = null,
|
||||
val error: String? = null,
|
||||
)
|
||||
@@ -1,15 +1,15 @@
|
||||
package com.atridad.openclimb.ui.viewmodel
|
||||
package com.atridad.ascently.ui.viewmodel
|
||||
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import com.atridad.openclimb.data.repository.ClimbRepository
|
||||
import com.atridad.openclimb.data.sync.SyncService
|
||||
import com.atridad.ascently.data.repository.ClimbRepository
|
||||
import com.atridad.ascently.data.sync.SyncService
|
||||
|
||||
class ClimbViewModelFactory(
|
||||
private val repository: ClimbRepository,
|
||||
private val syncService: SyncService,
|
||||
private val context: Context
|
||||
private val repository: ClimbRepository,
|
||||
private val syncService: SyncService,
|
||||
private val context: Context,
|
||||
) : ViewModelProvider.Factory {
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import android.util.Log
|
||||
import com.atridad.ascently.BuildConfig
|
||||
|
||||
object AppLogger {
|
||||
|
||||
private const val DEFAULT_TAG = "Ascently"
|
||||
|
||||
enum class Level(val androidLevel: Int) {
|
||||
DEBUG(Log.DEBUG),
|
||||
INFO(Log.INFO),
|
||||
WARN(Log.WARN),
|
||||
ERROR(Log.ERROR),
|
||||
}
|
||||
|
||||
fun d(tag: String = DEFAULT_TAG, messageProvider: () -> String) {
|
||||
log(Level.DEBUG, tag, messageProvider)
|
||||
}
|
||||
|
||||
fun i(tag: String = DEFAULT_TAG, messageProvider: () -> String) {
|
||||
log(Level.INFO, tag, messageProvider)
|
||||
}
|
||||
|
||||
fun w(tag: String = DEFAULT_TAG, throwable: Throwable? = null, messageProvider: () -> String) {
|
||||
log(Level.WARN, tag, messageProvider, throwable)
|
||||
}
|
||||
|
||||
fun e(tag: String = DEFAULT_TAG, throwable: Throwable? = null, messageProvider: () -> String) {
|
||||
log(Level.ERROR, tag, messageProvider, throwable)
|
||||
}
|
||||
|
||||
private fun log(
|
||||
level: Level,
|
||||
tag: String,
|
||||
messageProvider: () -> String,
|
||||
throwable: Throwable? = null,
|
||||
) {
|
||||
if (!BuildConfig.DEBUG) return
|
||||
|
||||
val message = messageProvider()
|
||||
if (throwable != null) {
|
||||
Log.println(level.androidLevel, tag, "$message\n${Log.getStackTraceString(throwable)}")
|
||||
} else {
|
||||
Log.println(level.androidLevel, tag, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import java.time.Instant
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
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())
|
||||
}
|
||||
|
||||
/** 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 (_: Exception) {
|
||||
try {
|
||||
Instant.parse(dateString)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a UTC ISO 8601 date string for display in local timezone This fixes the timezone
|
||||
* display issue where UTC dates were shown as local dates
|
||||
*/
|
||||
fun formatDateForDisplay(dateString: String): String {
|
||||
val pattern = "MMM dd, yyyy"
|
||||
return try {
|
||||
val instant = parseISO8601(dateString)
|
||||
if (instant != null) {
|
||||
val localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
|
||||
localDateTime.format(DateTimeFormatter.ofPattern(pattern))
|
||||
} else {
|
||||
// Fallback for malformed dates
|
||||
dateString.take(10)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
dateString.take(10)
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse a UTC ISO 8601 date string to LocalDateTime in system timezone */
|
||||
fun parseToLocalDateTime(dateString: String): LocalDateTime? {
|
||||
return try {
|
||||
val instant = parseISO8601(dateString)
|
||||
instant?.let { LocalDateTime.ofInstant(it, ZoneId.systemDefault()) }
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* 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, imageIndex: Int): String {
|
||||
val input = "${problemId}_$imageIndex"
|
||||
val hash = createHash(input)
|
||||
|
||||
return "problem_${hash}_${imageIndex}${IMAGE_EXTENSION}"
|
||||
}
|
||||
|
||||
/** Legacy method for backward compatibility */
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
fun generateImageFilename(problemId: String, timestamp: String, imageIndex: Int): String {
|
||||
return generateImageFilename(problemId, 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)
|
||||
}
|
||||
|
||||
/** Creates a mapping of existing server filenames to canonical filenames */
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.ImageDecoder
|
||||
import android.net.Uri
|
||||
import androidx.core.graphics.scale
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.util.UUID
|
||||
|
||||
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
|
||||
fun getImagesDirectory(context: Context): File {
|
||||
val imagesDir = File(context.filesDir, IMAGES_DIR)
|
||||
if (!imagesDir.exists()) {
|
||||
imagesDir.mkdirs()
|
||||
}
|
||||
return imagesDir
|
||||
}
|
||||
|
||||
/** Saves an image from a URI while preserving EXIF orientation data */
|
||||
private fun saveImageWithExif(
|
||||
context: Context,
|
||||
imageUri: Uri,
|
||||
originalBitmap: Bitmap,
|
||||
outputFile: File,
|
||||
): Boolean {
|
||||
return try {
|
||||
// Get EXIF data from original image
|
||||
val originalExif =
|
||||
context.contentResolver.openInputStream(imageUri)?.use { input ->
|
||||
ExifInterface(input)
|
||||
}
|
||||
|
||||
// Compress and save the bitmap
|
||||
val compressedBitmap = compressImage(originalBitmap)
|
||||
FileOutputStream(outputFile).use { output ->
|
||||
compressedBitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, output)
|
||||
}
|
||||
|
||||
// Copy EXIF data to the saved file
|
||||
originalExif?.let { sourceExif ->
|
||||
val destExif = ExifInterface(outputFile.absolutePath)
|
||||
|
||||
// Copy orientation and other important EXIF attributes
|
||||
val orientationValue = sourceExif.getAttribute(ExifInterface.TAG_ORIENTATION)
|
||||
orientationValue?.let { destExif.setAttribute(ExifInterface.TAG_ORIENTATION, it) }
|
||||
|
||||
// Copy other useful EXIF data
|
||||
sourceExif.getAttribute(ExifInterface.TAG_DATETIME)?.let {
|
||||
destExif.setAttribute(ExifInterface.TAG_DATETIME, it)
|
||||
}
|
||||
sourceExif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)?.let {
|
||||
destExif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, it)
|
||||
}
|
||||
sourceExif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)?.let {
|
||||
destExif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, it)
|
||||
}
|
||||
|
||||
destExif.saveAttributes()
|
||||
}
|
||||
|
||||
compressedBitmap.recycle()
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e("ImageUtils", e) { "Error saving image with EXIF data" }
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
}
|
||||
|
||||
return if (scaleFactor < 1f) {
|
||||
val newWidth = (width * scaleFactor).toInt()
|
||||
val newHeight = (height * scaleFactor).toInt()
|
||||
original.scale(newWidth, newHeight)
|
||||
} else {
|
||||
original
|
||||
}
|
||||
}
|
||||
|
||||
/** Gets the full file path for an image */
|
||||
fun getImageFile(context: Context, relativePath: String): File {
|
||||
// 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 */
|
||||
fun deleteImage(context: Context, relativePath: String): Boolean {
|
||||
return try {
|
||||
val file = getImageFile(context, relativePath)
|
||||
file.delete()
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e("ImageUtils", e) { "Failed to delete image: $relativePath" }
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
AppLogger.e("ImageUtils", e) { "Failed to import image from source: ${sourceFile.name}" }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 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"
|
||||
)
|
||||
) {
|
||||
"$IMAGES_DIR/${file.name}"
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
?: emptyList()
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e("ImageUtils", e) { "Failed to enumerate images directory" }
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/** Temporarily saves an image during selection process */
|
||||
fun saveTemporaryImageFromUri(context: Context, imageUri: Uri): String? {
|
||||
return try {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, imageUri)
|
||||
val originalBitmap = ImageDecoder.decodeBitmap(source)
|
||||
|
||||
val tempFilename = "temp_${UUID.randomUUID()}.jpg"
|
||||
val imageFile = File(getImagesDirectory(context), tempFilename)
|
||||
|
||||
val success = saveImageWithExif(context, imageUri, originalBitmap, imageFile)
|
||||
originalBitmap.recycle()
|
||||
|
||||
if (!success) return null
|
||||
|
||||
tempFilename
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e("ImageUtils", e) { "Error saving temporary image from URI" }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** Renames a temporary image */
|
||||
fun renameTemporaryImage(
|
||||
context: Context,
|
||||
tempFilename: String,
|
||||
problemId: String,
|
||||
imageIndex: Int,
|
||||
): String? {
|
||||
return try {
|
||||
val tempFile = File(getImagesDirectory(context), tempFilename)
|
||||
if (!tempFile.exists()) {
|
||||
AppLogger.e("ImageUtils") { "Temporary file does not exist: $tempFilename" }
|
||||
return null
|
||||
}
|
||||
|
||||
val deterministicFilename =
|
||||
ImageNamingUtils.generateImageFilename(problemId, imageIndex)
|
||||
val finalFile = File(getImagesDirectory(context), deterministicFilename)
|
||||
|
||||
if (tempFile.renameTo(finalFile)) {
|
||||
AppLogger.d("ImageUtils") { "Renamed temporary image: $tempFilename -> $deterministicFilename" }
|
||||
deterministicFilename
|
||||
} else {
|
||||
AppLogger.e("ImageUtils") { "Failed to rename temporary image: $tempFilename" }
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e("ImageUtils", e) { "Error renaming temporary image" }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves image data with a specific filename */
|
||||
fun saveImageFromBytesWithFilename(
|
||||
context: Context,
|
||||
imageData: ByteArray,
|
||||
filename: String,
|
||||
): String? {
|
||||
return try {
|
||||
val imageFile = File(getImagesDirectory(context), filename)
|
||||
|
||||
// Check if image is too large and needs compression
|
||||
if (imageData.size > 5 * 1024 * 1024) { // 5MB threshold
|
||||
// For large images, decode, compress, and try to preserve EXIF
|
||||
val bitmap =
|
||||
BitmapFactory.decodeByteArray(imageData, 0, imageData.size) ?: return null
|
||||
val compressedBitmap = compressImage(bitmap)
|
||||
|
||||
// Save compressed image
|
||||
FileOutputStream(imageFile).use { output ->
|
||||
compressedBitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, output)
|
||||
}
|
||||
|
||||
// Try to preserve EXIF orientation from original data
|
||||
try {
|
||||
val originalExif = ExifInterface(java.io.ByteArrayInputStream(imageData))
|
||||
val destExif = ExifInterface(imageFile.absolutePath)
|
||||
val orientationValue = originalExif.getAttribute(ExifInterface.TAG_ORIENTATION)
|
||||
orientationValue?.let {
|
||||
destExif.setAttribute(ExifInterface.TAG_ORIENTATION, it)
|
||||
}
|
||||
destExif.saveAttributes()
|
||||
} catch (e: Exception) {
|
||||
// If EXIF preservation fails, continue without it
|
||||
AppLogger.w("ImageUtils") { "Failed to preserve EXIF data: ${e.message}" }
|
||||
}
|
||||
|
||||
bitmap.recycle()
|
||||
compressedBitmap.recycle()
|
||||
} else {
|
||||
// For smaller images, save raw data to preserve all EXIF information
|
||||
FileOutputStream(imageFile).use { output -> output.write(imageData) }
|
||||
}
|
||||
|
||||
// Return relative path
|
||||
"$IMAGES_DIR/$filename"
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e("ImageUtils", e) { "Failed to save image from bytes: $filename" }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) }
|
||||
} catch (e: Exception) {
|
||||
AppLogger.e("ImageUtils", e) { "Failed to clean up orphaned images" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.core.content.edit
|
||||
|
||||
class MigrationManager(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MigrationManager"
|
||||
private const val MIGRATION_PREFS = "ascently_migration_state"
|
||||
private const val MIGRATION_COMPLETED_KEY = "openclimb_to_ascently_completed"
|
||||
}
|
||||
|
||||
private val migrationPrefs: SharedPreferences =
|
||||
context.getSharedPreferences(MIGRATION_PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
/**
|
||||
* Perform migration from OpenClimb to Ascently if needed This should be called early in app
|
||||
* startup
|
||||
*/
|
||||
fun migrateIfNeeded() {
|
||||
if (migrationPrefs.getBoolean(MIGRATION_COMPLETED_KEY, false)) {
|
||||
AppLogger.d(TAG) { "Migration already completed, skipping" }
|
||||
return
|
||||
}
|
||||
|
||||
AppLogger.i(TAG) { "🔄 Starting migration from OpenClimb to Ascently..." }
|
||||
var migrationCount = 0
|
||||
|
||||
// Migrate SharedPreferences
|
||||
migrationCount += migrateSharedPreferences()
|
||||
|
||||
// Mark migration as completed
|
||||
migrationPrefs.edit { putBoolean(MIGRATION_COMPLETED_KEY, true) }
|
||||
|
||||
if (migrationCount > 0) {
|
||||
AppLogger.i(TAG) { "🎉 Migration completed! Migrated $migrationCount items from OpenClimb to Ascently" }
|
||||
} else {
|
||||
AppLogger.i(TAG) { "ℹ️ No OpenClimb data found to migrate" }
|
||||
}
|
||||
}
|
||||
|
||||
/** Migrate SharedPreferences from OpenClimb naming to Ascently naming */
|
||||
private fun migrateSharedPreferences(): Int {
|
||||
var count = 0
|
||||
|
||||
// Define preference file migrations
|
||||
val preferenceFileMigrations =
|
||||
listOf(
|
||||
"openclimb_data_state" to "ascently_data_state",
|
||||
"health_connect_prefs" to "health_connect_prefs", // Keep same name
|
||||
"deleted_items" to "deleted_items", // Keep same name
|
||||
"sync_preferences" to "sync_preferences", // Keep same name
|
||||
)
|
||||
|
||||
for ((oldFileName, newFileName) in preferenceFileMigrations) {
|
||||
if (oldFileName != newFileName) {
|
||||
count += migratePreferenceFile(oldFileName, newFileName)
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate specific keys within preference files
|
||||
count += migratePreferenceKeys()
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/** Migrate an entire SharedPreferences file */
|
||||
private fun migratePreferenceFile(oldFileName: String, newFileName: String): Int {
|
||||
val oldPrefs = context.getSharedPreferences(oldFileName, Context.MODE_PRIVATE)
|
||||
val newPrefs = context.getSharedPreferences(newFileName, Context.MODE_PRIVATE)
|
||||
|
||||
// If old prefs exist and new prefs are empty, migrate
|
||||
if (oldPrefs.all.isNotEmpty() && newPrefs.all.isEmpty()) {
|
||||
newPrefs.edit {
|
||||
oldPrefs.all.forEach { (key, value) ->
|
||||
when (value) {
|
||||
is String -> putString(key, value)
|
||||
is Int -> putInt(key, value)
|
||||
is Long -> putLong(key, value)
|
||||
is Float -> putFloat(key, value)
|
||||
is Boolean -> putBoolean(key, value)
|
||||
is Set<*> -> {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
putStringSet(key, value as Set<String>)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clear old preferences
|
||||
oldPrefs.edit { clear() }
|
||||
|
||||
AppLogger.d(TAG) { "Migrated preference file: $oldFileName → $newFileName (${oldPrefs.all.size} keys)" }
|
||||
return oldPrefs.all.size
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
/** Migrate specific keys within preference files that might contain openclimb references */
|
||||
private fun migratePreferenceKeys(): Int {
|
||||
var count = 0
|
||||
|
||||
// Check for any openclimb-prefixed keys across all preference files
|
||||
val preferencesToCheck =
|
||||
listOf(
|
||||
"ascently_data_state",
|
||||
"health_connect_prefs",
|
||||
"deleted_items",
|
||||
"sync_preferences",
|
||||
)
|
||||
|
||||
for (prefFileName in preferencesToCheck) {
|
||||
val prefs = context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE)
|
||||
val keysToMigrate = mutableListOf<Pair<String, String>>()
|
||||
|
||||
// Find keys that start with openclimb_ and should be ascently_
|
||||
prefs.all.keys.forEach { key ->
|
||||
if (key.startsWith("openclimb_")) {
|
||||
val newKey = key.replace("openclimb_", "ascently_")
|
||||
keysToMigrate.add(key to newKey)
|
||||
}
|
||||
}
|
||||
|
||||
// Perform the key migrations
|
||||
if (keysToMigrate.isNotEmpty()) {
|
||||
prefs.edit {
|
||||
keysToMigrate.forEach { (oldKey, newKey) ->
|
||||
val value = prefs.all[oldKey]
|
||||
when (value) {
|
||||
is String -> putString(newKey, value)
|
||||
is Int -> putInt(newKey, value)
|
||||
is Long -> putLong(newKey, value)
|
||||
is Float -> putFloat(newKey, value)
|
||||
is Boolean -> putBoolean(newKey, value)
|
||||
is Set<*> -> {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
putStringSet(newKey, value as Set<String>)
|
||||
}
|
||||
}
|
||||
remove(oldKey)
|
||||
}
|
||||
}
|
||||
|
||||
AppLogger.d(TAG) { "Migrated ${keysToMigrate.size} keys in $prefFileName" }
|
||||
count += keysToMigrate.size
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/** Check if migration has been completed */
|
||||
fun isMigrationCompleted(): Boolean {
|
||||
return migrationPrefs.getBoolean(MIGRATION_COMPLETED_KEY, false)
|
||||
}
|
||||
|
||||
/** Reset migration state (for testing purposes) */
|
||||
fun resetMigrationState() {
|
||||
migrationPrefs.edit { putBoolean(MIGRATION_COMPLETED_KEY, false) }
|
||||
AppLogger.d(TAG) { "Migration state reset" }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.utils
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
@@ -6,24 +6,24 @@ import android.content.pm.PackageManager
|
||||
import androidx.core.content.ContextCompat
|
||||
|
||||
object NotificationPermissionUtils {
|
||||
|
||||
|
||||
/**
|
||||
* Check if notification permission is granted
|
||||
*/
|
||||
fun isNotificationPermissionGranted(context: Context): Boolean {
|
||||
return ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.POST_NOTIFICATIONS
|
||||
Manifest.permission.POST_NOTIFICATIONS,
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if notification permission should be requested
|
||||
*/
|
||||
fun shouldRequestNotificationPermission(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the notification permission string
|
||||
*/
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.atridad.openclimb.utils
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -7,23 +7,23 @@ import android.content.pm.ShortcutManager
|
||||
import android.graphics.drawable.Icon
|
||||
import android.os.Build
|
||||
import androidx.annotation.RequiresApi
|
||||
import com.atridad.openclimb.MainActivity
|
||||
import com.atridad.openclimb.R
|
||||
import com.atridad.ascently.MainActivity
|
||||
import com.atridad.ascently.R
|
||||
|
||||
object AppShortcutManager {
|
||||
|
||||
const val SHORTCUT_START_SESSION = "start_session"
|
||||
const val SHORTCUT_END_SESSION = "end_session"
|
||||
|
||||
const val ACTION_START_SESSION = "com.atridad.openclimb.action.START_SESSION"
|
||||
const val ACTION_END_SESSION = "com.atridad.openclimb.action.END_SESSION"
|
||||
const val ACTION_START_SESSION = "com.atridad.ascently.action.START_SESSION"
|
||||
const val ACTION_END_SESSION = "com.atridad.ascently.action.END_SESSION"
|
||||
|
||||
/** Updates the app shortcuts based on current session state */
|
||||
fun updateShortcuts(
|
||||
context: Context,
|
||||
hasActiveSession: Boolean,
|
||||
hasGyms: Boolean,
|
||||
lastUsedGym: com.atridad.openclimb.data.model.Gym? = null
|
||||
context: Context,
|
||||
hasActiveSession: Boolean,
|
||||
hasGyms: Boolean,
|
||||
lastUsedGym: com.atridad.ascently.data.model.Gym? = null,
|
||||
) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
|
||||
val shortcutManager = context.getSystemService(ShortcutManager::class.java)
|
||||
@@ -44,52 +44,52 @@ object AppShortcutManager {
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.N_MR1)
|
||||
private fun createStartSessionShortcut(
|
||||
context: Context,
|
||||
lastUsedGym: com.atridad.openclimb.data.model.Gym? = null
|
||||
context: Context,
|
||||
lastUsedGym: com.atridad.ascently.data.model.Gym? = null,
|
||||
): ShortcutInfo {
|
||||
val startIntent =
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
action = ACTION_START_SESSION
|
||||
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||
lastUsedGym?.let { gym -> putExtra("LAST_USED_GYM_ID", gym.id) }
|
||||
}
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
action = ACTION_START_SESSION
|
||||
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||
lastUsedGym?.let { gym -> putExtra("LAST_USED_GYM_ID", gym.id) }
|
||||
}
|
||||
|
||||
val shortLabel =
|
||||
if (lastUsedGym != null) {
|
||||
"Start at ${lastUsedGym.name}"
|
||||
} else {
|
||||
context.getString(R.string.shortcut_start_session_short)
|
||||
}
|
||||
if (lastUsedGym != null) {
|
||||
"Start at ${lastUsedGym.name}"
|
||||
} else {
|
||||
context.getString(R.string.shortcut_start_session_short)
|
||||
}
|
||||
|
||||
val longLabel =
|
||||
if (lastUsedGym != null) {
|
||||
"Start a new climbing session at ${lastUsedGym.name}"
|
||||
} else {
|
||||
context.getString(R.string.shortcut_start_session_long)
|
||||
}
|
||||
if (lastUsedGym != null) {
|
||||
"Start a new climbing session at ${lastUsedGym.name}"
|
||||
} else {
|
||||
context.getString(R.string.shortcut_start_session_long)
|
||||
}
|
||||
|
||||
return ShortcutInfo.Builder(context, SHORTCUT_START_SESSION)
|
||||
.setShortLabel(shortLabel)
|
||||
.setLongLabel(longLabel)
|
||||
.setIcon(Icon.createWithResource(context, R.drawable.ic_play_arrow_24))
|
||||
.setIntent(startIntent)
|
||||
.build()
|
||||
.setShortLabel(shortLabel)
|
||||
.setLongLabel(longLabel)
|
||||
.setIcon(Icon.createWithResource(context, R.drawable.ic_play_arrow_24))
|
||||
.setIntent(startIntent)
|
||||
.build()
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.N_MR1)
|
||||
private fun createEndSessionShortcut(context: Context): ShortcutInfo {
|
||||
val endIntent =
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
action = ACTION_END_SESSION
|
||||
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||
}
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
action = ACTION_END_SESSION
|
||||
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||
}
|
||||
|
||||
return ShortcutInfo.Builder(context, SHORTCUT_END_SESSION)
|
||||
.setShortLabel(context.getString(R.string.shortcut_end_session_short))
|
||||
.setLongLabel(context.getString(R.string.shortcut_end_session_long))
|
||||
.setIcon(Icon.createWithResource(context, R.drawable.ic_stop_24))
|
||||
.setIntent(endIntent)
|
||||
.build()
|
||||
.setShortLabel(context.getString(R.string.shortcut_end_session_short))
|
||||
.setLongLabel(context.getString(R.string.shortcut_end_session_long))
|
||||
.setIcon(Icon.createWithResource(context, R.drawable.ic_stop_24))
|
||||
.setIntent(endIntent)
|
||||
.build()
|
||||
}
|
||||
|
||||
/** Removes all dynamic shortcuts */
|
||||
@@ -1,8 +1,10 @@
|
||||
package com.atridad.openclimb.utils
|
||||
package com.atridad.ascently.utils
|
||||
|
||||
import android.content.Context
|
||||
import com.atridad.openclimb.data.format.BackupProblem
|
||||
import com.atridad.openclimb.data.format.ClimbDataBackup
|
||||
import com.atridad.ascently.data.format.BackupProblem
|
||||
import com.atridad.ascently.data.format.ClimbDataBackup
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
@@ -11,8 +13,6 @@ import java.time.LocalDateTime
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipInputStream
|
||||
import java.util.zip.ZipOutputStream
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
object ZipExportImportUtils {
|
||||
|
||||
@@ -22,25 +22,25 @@ object ZipExportImportUtils {
|
||||
|
||||
/** Creates a ZIP file containing the JSON data and all referenced images */
|
||||
fun createExportZip(
|
||||
context: Context,
|
||||
exportData: ClimbDataBackup,
|
||||
referencedImagePaths: Set<String>,
|
||||
directory: File? = null
|
||||
context: Context,
|
||||
exportData: ClimbDataBackup,
|
||||
referencedImagePaths: Set<String>,
|
||||
directory: File? = null,
|
||||
): File {
|
||||
val exportDir =
|
||||
directory
|
||||
?: File(
|
||||
context.getExternalFilesDir(
|
||||
android.os.Environment.DIRECTORY_DOCUMENTS
|
||||
),
|
||||
"OpenClimb"
|
||||
)
|
||||
directory
|
||||
?: File(
|
||||
context.getExternalFilesDir(
|
||||
android.os.Environment.DIRECTORY_DOCUMENTS,
|
||||
),
|
||||
"Ascently",
|
||||
)
|
||||
if (!exportDir.exists()) {
|
||||
exportDir.mkdirs()
|
||||
}
|
||||
|
||||
val timestamp = LocalDateTime.now().toString().replace(":", "-").replace(".", "-")
|
||||
val zipFile = File(exportDir, "openclimb_export_$timestamp.zip")
|
||||
val zipFile = File(exportDir, "ascently_export_$timestamp.zip")
|
||||
|
||||
try {
|
||||
ZipOutputStream(FileOutputStream(zipFile)).use { zipOut ->
|
||||
@@ -52,10 +52,11 @@ object ZipExportImportUtils {
|
||||
zipOut.closeEntry()
|
||||
|
||||
// Add JSON data file
|
||||
val json = Json {
|
||||
prettyPrint = true
|
||||
ignoreUnknownKeys = true
|
||||
}
|
||||
val json =
|
||||
Json {
|
||||
prettyPrint = true
|
||||
ignoreUnknownKeys = true
|
||||
}
|
||||
val jsonString = json.encodeToString(exportData)
|
||||
|
||||
val jsonEntry = ZipEntry(DATA_JSON_FILENAME)
|
||||
@@ -78,24 +79,21 @@ object ZipExportImportUtils {
|
||||
zipOut.closeEntry()
|
||||
successfulImages++
|
||||
} else {
|
||||
android.util.Log.w(
|
||||
"ZipExportImportUtils",
|
||||
"Image file not found or empty: $imagePath"
|
||||
)
|
||||
AppLogger.w("ZipExportImportUtils") {
|
||||
"Image file not found or empty: $imagePath"
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e(
|
||||
"ZipExportImportUtils",
|
||||
"Failed to add image $imagePath: ${e.message}"
|
||||
)
|
||||
AppLogger.e("ZipExportImportUtils", e) {
|
||||
"Failed to add image $imagePath: ${e.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Log export summary
|
||||
android.util.Log.i(
|
||||
"ZipExportImportUtils",
|
||||
"Export completed: ${successfulImages}/${referencedImagePaths.size} images included"
|
||||
)
|
||||
AppLogger.i("ZipExportImportUtils") {
|
||||
"Export completed: $successfulImages/${referencedImagePaths.size} images included"
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the created ZIP file
|
||||
@@ -115,10 +113,10 @@ object ZipExportImportUtils {
|
||||
|
||||
/** Creates a ZIP file and writes it to a provided URI */
|
||||
fun createExportZipToUri(
|
||||
context: Context,
|
||||
uri: android.net.Uri,
|
||||
exportData: ClimbDataBackup,
|
||||
referencedImagePaths: Set<String>
|
||||
context: Context,
|
||||
uri: android.net.Uri,
|
||||
exportData: ClimbDataBackup,
|
||||
referencedImagePaths: Set<String>,
|
||||
) {
|
||||
try {
|
||||
context.contentResolver.openOutputStream(uri)?.use { outputStream ->
|
||||
@@ -131,10 +129,11 @@ object ZipExportImportUtils {
|
||||
zipOut.closeEntry()
|
||||
|
||||
// Add JSON data file
|
||||
val json = Json {
|
||||
prettyPrint = true
|
||||
ignoreUnknownKeys = true
|
||||
}
|
||||
val json =
|
||||
Json {
|
||||
prettyPrint = true
|
||||
ignoreUnknownKeys = true
|
||||
}
|
||||
val jsonString = json.encodeToString(exportData)
|
||||
|
||||
val jsonEntry = ZipEntry(DATA_JSON_FILENAME)
|
||||
@@ -158,32 +157,30 @@ object ZipExportImportUtils {
|
||||
successfulImages++
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e(
|
||||
"ZipExportImportUtils",
|
||||
"Failed to add image $imagePath: ${e.message}"
|
||||
)
|
||||
AppLogger.e("ZipExportImportUtils", e) {
|
||||
"Failed to add image $imagePath: ${e.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
android.util.Log.i(
|
||||
"ZipExportImportUtils",
|
||||
"Export to URI completed: ${successfulImages}/${referencedImagePaths.size} images included"
|
||||
)
|
||||
AppLogger.i("ZipExportImportUtils") {
|
||||
"Export to URI completed: $successfulImages/${referencedImagePaths.size} images included"
|
||||
}
|
||||
}
|
||||
}
|
||||
?: throw IOException("Could not open output stream")
|
||||
?: throw IOException("Could not open output stream")
|
||||
} catch (e: Exception) {
|
||||
throw IOException("Failed to create export ZIP to URI: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun createMetadata(
|
||||
exportData: ClimbDataBackup,
|
||||
referencedImagePaths: Set<String>
|
||||
exportData: ClimbDataBackup,
|
||||
referencedImagePaths: Set<String>,
|
||||
): String {
|
||||
return buildString {
|
||||
appendLine("OpenClimb Export Metadata")
|
||||
appendLine("=======================")
|
||||
appendLine("Ascently Export Metadata")
|
||||
appendLine("========================")
|
||||
appendLine("Export Date: ${exportData.exportedAt}")
|
||||
appendLine("Version: ${exportData.version}")
|
||||
appendLine("Gyms: ${exportData.gyms.size}")
|
||||
@@ -197,8 +194,8 @@ object ZipExportImportUtils {
|
||||
|
||||
/** Data class to hold extraction results */
|
||||
data class ImportResult(
|
||||
val jsonContent: String,
|
||||
val importedImagePaths: Map<String, String> // original filename -> new relative path
|
||||
val jsonContent: String,
|
||||
val importedImagePaths: Map<String, String>, // original filename -> new relative path
|
||||
)
|
||||
|
||||
/** Extracts a ZIP file and returns the JSON content and imported image paths */
|
||||
@@ -217,16 +214,17 @@ object ZipExportImportUtils {
|
||||
// Read metadata for validation
|
||||
val metadataContent = zipIn.readBytes().toString(Charsets.UTF_8)
|
||||
foundRequiredFiles.add("metadata")
|
||||
android.util.Log.i(
|
||||
"ZipExportImportUtils",
|
||||
"Found metadata: ${metadataContent.lines().take(3).joinToString()}"
|
||||
)
|
||||
AppLogger.i("ZipExportImportUtils") {
|
||||
"Found metadata: ${metadataContent.lines().take(3).joinToString()}"
|
||||
}
|
||||
}
|
||||
|
||||
entry.name == DATA_JSON_FILENAME -> {
|
||||
// Read JSON data
|
||||
jsonContent = zipIn.readBytes().toString(Charsets.UTF_8)
|
||||
foundRequiredFiles.add("data")
|
||||
}
|
||||
|
||||
entry.name.startsWith("$IMAGES_DIR_NAME/") && !entry.isDirectory -> {
|
||||
// Extract image file
|
||||
val originalFilename = entry.name.substringAfter("$IMAGES_DIR_NAME/")
|
||||
@@ -234,11 +232,11 @@ object ZipExportImportUtils {
|
||||
try {
|
||||
// Create temporary file to hold the extracted image
|
||||
val tempFile =
|
||||
File.createTempFile(
|
||||
"import_image_",
|
||||
"_$originalFilename",
|
||||
context.cacheDir
|
||||
)
|
||||
File.createTempFile(
|
||||
"import_image_",
|
||||
"_$originalFilename",
|
||||
context.cacheDir,
|
||||
)
|
||||
|
||||
FileOutputStream(tempFile).use { output -> zipIn.copyTo(output) }
|
||||
|
||||
@@ -248,37 +246,33 @@ object ZipExportImportUtils {
|
||||
val newPath = ImageUtils.importImageFile(context, tempFile)
|
||||
if (newPath != null) {
|
||||
importedImagePaths[originalFilename] = newPath
|
||||
android.util.Log.d(
|
||||
"ZipExportImportUtils",
|
||||
"Successfully imported image: $originalFilename -> $newPath"
|
||||
)
|
||||
AppLogger.d("ZipExportImportUtils") {
|
||||
"Successfully imported image: $originalFilename -> $newPath"
|
||||
}
|
||||
} else {
|
||||
android.util.Log.w(
|
||||
"ZipExportImportUtils",
|
||||
"Failed to import image: $originalFilename"
|
||||
)
|
||||
AppLogger.w("ZipExportImportUtils") {
|
||||
"Failed to import image: $originalFilename"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
android.util.Log.w(
|
||||
"ZipExportImportUtils",
|
||||
"Extracted image is empty: $originalFilename"
|
||||
)
|
||||
AppLogger.w("ZipExportImportUtils") {
|
||||
"Extracted image is empty: $originalFilename"
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up temp file
|
||||
tempFile.delete()
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e(
|
||||
"ZipExportImportUtils",
|
||||
"Failed to process image $originalFilename: ${e.message}"
|
||||
)
|
||||
AppLogger.e("ZipExportImportUtils", e) {
|
||||
"Failed to process image $originalFilename: ${e.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
android.util.Log.d(
|
||||
"ZipExportImportUtils",
|
||||
"Skipping ZIP entry: ${entry.name}"
|
||||
)
|
||||
AppLogger.d("ZipExportImportUtils") {
|
||||
"Skipping ZIP entry: ${entry.name}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,10 +290,9 @@ object ZipExportImportUtils {
|
||||
throw IOException("Invalid ZIP file: data.json is empty")
|
||||
}
|
||||
|
||||
android.util.Log.i(
|
||||
"ZipExportImportUtils",
|
||||
"Import extraction completed: ${importedImagePaths.size} images processed"
|
||||
)
|
||||
AppLogger.i("ZipExportImportUtils") {
|
||||
"Import extraction completed: ${importedImagePaths.size} images processed"
|
||||
}
|
||||
|
||||
return ImportResult(jsonContent, importedImagePaths)
|
||||
} catch (e: Exception) {
|
||||
@@ -312,16 +305,16 @@ object ZipExportImportUtils {
|
||||
* the new ones after import
|
||||
*/
|
||||
fun updateProblemImagePaths(
|
||||
problems: List<BackupProblem>,
|
||||
imagePathMapping: Map<String, String>
|
||||
problems: List<BackupProblem>,
|
||||
imagePathMapping: Map<String, String>,
|
||||
): List<BackupProblem> {
|
||||
return problems.map { problem ->
|
||||
val updatedImagePaths =
|
||||
(problem.imagePaths ?: emptyList()).mapNotNull { oldPath ->
|
||||
// Extract filename from the old path
|
||||
val filename = oldPath.substringAfterLast("/")
|
||||
imagePathMapping[filename]
|
||||
}
|
||||
(problem.imagePaths ?: emptyList()).mapNotNull { oldPath ->
|
||||
// Extract filename from the old path
|
||||
val filename = oldPath.substringAfterLast("/")
|
||||
imagePathMapping[filename]
|
||||
}
|
||||
problem.withUpdatedImagePaths(updatedImagePaths)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.atridad.ascently.widget
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.widget.RemoteViews
|
||||
import com.atridad.ascently.MainActivity
|
||||
import com.atridad.ascently.R
|
||||
import com.atridad.ascently.data.database.AscentlyDatabase
|
||||
import com.atridad.ascently.data.repository.ClimbRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.LocalDate
|
||||
|
||||
class ClimbStatsWidgetProvider : AppWidgetProvider() {
|
||||
|
||||
private val job = SupervisorJob()
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.IO + job)
|
||||
|
||||
override fun onUpdate(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
appWidgetIds: IntArray,
|
||||
) {
|
||||
for (appWidgetId in appWidgetIds) {
|
||||
updateAppWidget(context, appWidgetManager, appWidgetId)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onEnabled(context: Context) {}
|
||||
|
||||
override fun onDisabled(context: Context) {
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
private fun updateAppWidget(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
appWidgetId: Int,
|
||||
) {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
val database = AscentlyDatabase.getDatabase(context)
|
||||
val repository = ClimbRepository(database, context)
|
||||
|
||||
// Get last 7 days date range (rolling period)
|
||||
val today = LocalDate.now()
|
||||
val sevenDaysAgo = today.minusDays(6) // Today + 6 days ago = 7 days total
|
||||
|
||||
// Fetch all sessions and attempts
|
||||
val sessions = repository.getAllSessions().first()
|
||||
val attempts = repository.getAllAttempts().first()
|
||||
|
||||
// Filter for last 7 days across all gyms
|
||||
val weekSessions =
|
||||
sessions.filter { session ->
|
||||
try {
|
||||
val sessionDate = LocalDate.parse(session.date.substring(0, 10))
|
||||
!sessionDate.isBefore(sevenDaysAgo) && !sessionDate.isAfter(today)
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
val weekSessionIds = weekSessions.map { it.id }.toSet()
|
||||
|
||||
// Count total attempts this week
|
||||
val totalAttempts =
|
||||
attempts.count { attempt -> weekSessionIds.contains(attempt.sessionId) }
|
||||
|
||||
// Count sessions this week
|
||||
val totalSessions = weekSessions.size
|
||||
|
||||
launch(Dispatchers.Main) {
|
||||
val views = RemoteViews(context.packageName, R.layout.widget_climb_stats)
|
||||
|
||||
// Set weekly stats
|
||||
views.setTextViewText(R.id.widget_attempts_value, totalAttempts.toString())
|
||||
views.setTextViewText(R.id.widget_sessions_value, totalSessions.toString())
|
||||
|
||||
val intent =
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
flags =
|
||||
Intent.FLAG_ACTIVITY_NEW_TASK or
|
||||
Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
}
|
||||
val pendingIntent =
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
views.setOnClickPendingIntent(R.id.widget_container, pendingIntent)
|
||||
|
||||
appWidgetManager.updateAppWidget(appWidgetId, views)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
launch(Dispatchers.Main) {
|
||||
val views = RemoteViews(context.packageName, R.layout.widget_climb_stats)
|
||||
views.setTextViewText(R.id.widget_attempts_value, "0")
|
||||
views.setTextViewText(R.id.widget_sessions_value, "0")
|
||||
|
||||
val intent = Intent(context, MainActivity::class.java)
|
||||
val pendingIntent =
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
views.setOnClickPendingIntent(R.id.widget_container, pendingIntent)
|
||||
|
||||
appWidgetManager.updateAppWidget(appWidgetId, views)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun updateAllWidgets(context: Context) {
|
||||
val appWidgetManager = AppWidgetManager.getInstance(context)
|
||||
val componentName = ComponentName(context, ClimbStatsWidgetProvider::class.java)
|
||||
val appWidgetIds = appWidgetManager.getAppWidgetIds(componentName)
|
||||
|
||||
val intent =
|
||||
Intent(context, ClimbStatsWidgetProvider::class.java).apply {
|
||||
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
|
||||
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds)
|
||||
}
|
||||
context.sendBroadcast(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.atridad.openclimb.data.database
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.atridad.openclimb.data.database.dao.*
|
||||
import com.atridad.openclimb.data.model.*
|
||||
|
||||
@Database(
|
||||
entities = [Gym::class, Problem::class, ClimbSession::class, Attempt::class],
|
||||
version = 6,
|
||||
exportSchema = false
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class OpenClimbDatabase : RoomDatabase() {
|
||||
|
||||
abstract fun gymDao(): GymDao
|
||||
abstract fun problemDao(): ProblemDao
|
||||
abstract fun climbSessionDao(): ClimbSessionDao
|
||||
abstract fun attemptDao(): AttemptDao
|
||||
|
||||
companion object {
|
||||
@Volatile private var INSTANCE: OpenClimbDatabase? = null
|
||||
|
||||
val MIGRATION_4_5 =
|
||||
object : Migration(4, 5) {
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
val cursor = database.query("PRAGMA table_info(climb_sessions)")
|
||||
val existingColumns = mutableSetOf<String>()
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
val columnName = cursor.getString(cursor.getColumnIndexOrThrow("name"))
|
||||
existingColumns.add(columnName)
|
||||
}
|
||||
cursor.close()
|
||||
|
||||
if (!existingColumns.contains("startTime")) {
|
||||
database.execSQL("ALTER TABLE climb_sessions ADD COLUMN startTime TEXT")
|
||||
}
|
||||
if (!existingColumns.contains("endTime")) {
|
||||
database.execSQL("ALTER TABLE climb_sessions ADD COLUMN endTime TEXT")
|
||||
}
|
||||
if (!existingColumns.contains("status")) {
|
||||
database.execSQL(
|
||||
"ALTER TABLE climb_sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'COMPLETED'"
|
||||
)
|
||||
}
|
||||
|
||||
database.execSQL(
|
||||
"UPDATE climb_sessions SET startTime = createdAt WHERE startTime IS NULL"
|
||||
)
|
||||
database.execSQL(
|
||||
"UPDATE climb_sessions SET status = 'COMPLETED' WHERE status IS NULL OR status = ''"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val MIGRATION_5_6 =
|
||||
object : Migration(5, 6) {
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
// Add updatedAt column to attempts table
|
||||
val cursor = database.query("PRAGMA table_info(attempts)")
|
||||
val existingColumns = mutableSetOf<String>()
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
val columnName = cursor.getString(cursor.getColumnIndexOrThrow("name"))
|
||||
existingColumns.add(columnName)
|
||||
}
|
||||
cursor.close()
|
||||
|
||||
if (!existingColumns.contains("updatedAt")) {
|
||||
database.execSQL(
|
||||
"ALTER TABLE attempts ADD COLUMN updatedAt TEXT NOT NULL DEFAULT ''"
|
||||
)
|
||||
// Set updatedAt to createdAt for existing records
|
||||
database.execSQL(
|
||||
"UPDATE attempts SET updatedAt = createdAt WHERE updatedAt = ''"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getDatabase(context: Context): OpenClimbDatabase {
|
||||
return INSTANCE
|
||||
?: synchronized(this) {
|
||||
val instance =
|
||||
Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
OpenClimbDatabase::class.java,
|
||||
"openclimb_database"
|
||||
)
|
||||
.addMigrations(MIGRATION_4_5, MIGRATION_5_6)
|
||||
.enableMultiInstanceInvalidation()
|
||||
.fallbackToDestructiveMigration()
|
||||
.build()
|
||||
INSTANCE = instance
|
||||
instance
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
package com.atridad.openclimb.data.format
|
||||
|
||||
import com.atridad.openclimb.data.model.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// Root structure for OpenClimb backup data
|
||||
@Serializable
|
||||
data class ClimbDataBackup(
|
||||
val exportedAt: String,
|
||||
val version: String = "2.0",
|
||||
val formatVersion: String = "2.0",
|
||||
val gyms: List<BackupGym>,
|
||||
val problems: List<BackupProblem>,
|
||||
val sessions: List<BackupClimbSession>,
|
||||
val attempts: List<BackupAttempt>,
|
||||
val deletedItems: List<DeletedItem> = emptyList()
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DeletedItem(
|
||||
val id: String,
|
||||
val type: String, // "gym", "problem", "session", "attempt"
|
||||
val deletedAt: String
|
||||
)
|
||||
|
||||
// Platform-neutral gym representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupGym(
|
||||
val id: String,
|
||||
val name: String,
|
||||
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,
|
||||
val updatedAt: String
|
||||
) {
|
||||
companion object {
|
||||
/** Create BackupGym from native Android Gym model */
|
||||
fun fromGym(gym: Gym): BackupGym {
|
||||
return 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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Convert to native Android Gym model */
|
||||
fun toGym(): Gym {
|
||||
return Gym(
|
||||
id = id,
|
||||
name = name,
|
||||
location = location,
|
||||
supportedClimbTypes = supportedClimbTypes,
|
||||
difficultySystems = difficultySystems,
|
||||
customDifficultyGrades = customDifficultyGrades,
|
||||
notes = notes,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-neutral problem representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupProblem(
|
||||
val id: String,
|
||||
val gymId: String,
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val climbType: ClimbType,
|
||||
val difficulty: DifficultyGrade,
|
||||
val tags: List<String> = emptyList(),
|
||||
val location: String? = null,
|
||||
val imagePaths: List<String>? = null,
|
||||
val isActive: Boolean = true,
|
||||
val dateSet: String? = null,
|
||||
val notes: String? = null,
|
||||
val createdAt: String,
|
||||
val updatedAt: String
|
||||
) {
|
||||
companion object {
|
||||
/** Create BackupProblem from native Android Problem model */
|
||||
fun fromProblem(problem: Problem): BackupProblem {
|
||||
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 =
|
||||
if (problem.imagePaths.isEmpty()) null
|
||||
else problem.imagePaths.map { path -> path.substringAfterLast('/') },
|
||||
isActive = problem.isActive,
|
||||
dateSet = problem.dateSet,
|
||||
notes = problem.notes,
|
||||
createdAt = problem.createdAt,
|
||||
updatedAt = problem.updatedAt
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Convert to native Android Problem model */
|
||||
fun toProblem(): Problem {
|
||||
return Problem(
|
||||
id = id,
|
||||
gymId = gymId,
|
||||
name = name,
|
||||
description = description,
|
||||
climbType = climbType,
|
||||
difficulty = difficulty,
|
||||
tags = tags,
|
||||
location = location,
|
||||
imagePaths = imagePaths ?: emptyList(),
|
||||
isActive = isActive,
|
||||
dateSet = dateSet,
|
||||
notes = notes,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt
|
||||
)
|
||||
}
|
||||
|
||||
/** Create a copy with updated image paths for import processing */
|
||||
fun withUpdatedImagePaths(newImagePaths: List<String>): BackupProblem {
|
||||
return copy(imagePaths = newImagePaths.ifEmpty { null })
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-neutral climb session representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupClimbSession(
|
||||
val id: String,
|
||||
val gymId: String,
|
||||
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,
|
||||
val updatedAt: String
|
||||
) {
|
||||
companion object {
|
||||
/** Create BackupClimbSession from native Android ClimbSession model */
|
||||
fun fromClimbSession(session: ClimbSession): BackupClimbSession {
|
||||
return 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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Convert to native Android ClimbSession model */
|
||||
fun toClimbSession(): ClimbSession {
|
||||
return ClimbSession(
|
||||
id = id,
|
||||
gymId = gymId,
|
||||
date = date,
|
||||
startTime = startTime,
|
||||
endTime = endTime,
|
||||
duration = duration,
|
||||
status = status,
|
||||
notes = notes,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-neutral attempt representation for backup/restore
|
||||
@Serializable
|
||||
data class BackupAttempt(
|
||||
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,
|
||||
val updatedAt: String? = null
|
||||
) {
|
||||
companion object {
|
||||
/** Create BackupAttempt from native Android Attempt model */
|
||||
fun fromAttempt(attempt: Attempt): BackupAttempt {
|
||||
return 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,
|
||||
updatedAt = attempt.updatedAt
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Convert to native Android Attempt model */
|
||||
fun toAttempt(): Attempt {
|
||||
return Attempt(
|
||||
id = id,
|
||||
sessionId = sessionId,
|
||||
problemId = problemId,
|
||||
result = result,
|
||||
highestHold = highestHold,
|
||||
notes = notes,
|
||||
duration = duration,
|
||||
restTime = restTime,
|
||||
timestamp = timestamp,
|
||||
createdAt = createdAt,
|
||||
updatedAt = updatedAt ?: createdAt
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,426 +0,0 @@
|
||||
package com.atridad.openclimb.data.health
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import androidx.activity.result.contract.ActivityResultContract
|
||||
import androidx.health.connect.client.HealthConnectClient
|
||||
import androidx.health.connect.client.PermissionController
|
||||
import androidx.health.connect.client.permission.HealthPermission
|
||||
import androidx.health.connect.client.records.ExerciseSessionRecord
|
||||
import androidx.health.connect.client.records.HeartRateRecord
|
||||
import androidx.health.connect.client.records.TotalCaloriesBurnedRecord
|
||||
import androidx.health.connect.client.units.Energy
|
||||
import com.atridad.openclimb.data.model.ClimbSession
|
||||
import com.atridad.openclimb.data.model.SessionStatus
|
||||
import com.atridad.openclimb.utils.DateFormatUtils
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import java.time.ZoneOffset
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
/**
|
||||
* Health Connect manager for OpenClimb that syncs climbing sessions to Samsung Health, Google Fit,
|
||||
* and other health apps.
|
||||
*/
|
||||
@SuppressLint("RestrictedApi")
|
||||
class HealthConnectManager(private val context: Context) {
|
||||
|
||||
private val preferences: SharedPreferences =
|
||||
context.getSharedPreferences("health_connect_prefs", Context.MODE_PRIVATE)
|
||||
|
||||
private val _isEnabled = MutableStateFlow(preferences.getBoolean("enabled", false))
|
||||
private val _hasPermissions = MutableStateFlow(preferences.getBoolean("permissions", false))
|
||||
private val _autoSync = MutableStateFlow(preferences.getBoolean("auto_sync", true))
|
||||
private val _isCompatible = MutableStateFlow(true)
|
||||
|
||||
val isEnabled: Flow<Boolean> = _isEnabled.asStateFlow()
|
||||
val hasPermissions: Flow<Boolean> = _hasPermissions.asStateFlow()
|
||||
val autoSyncEnabled: Flow<Boolean> = _autoSync.asStateFlow()
|
||||
val isCompatible: Flow<Boolean> = _isCompatible.asStateFlow()
|
||||
|
||||
companion object {
|
||||
private const val TAG = "HealthConnectManager"
|
||||
|
||||
val REQUIRED_PERMISSIONS =
|
||||
setOf(
|
||||
HealthPermission.getReadPermission(ExerciseSessionRecord::class),
|
||||
HealthPermission.getWritePermission(ExerciseSessionRecord::class),
|
||||
HealthPermission.getReadPermission(HeartRateRecord::class),
|
||||
HealthPermission.getWritePermission(HeartRateRecord::class),
|
||||
HealthPermission.getReadPermission(TotalCaloriesBurnedRecord::class),
|
||||
HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class)
|
||||
)
|
||||
}
|
||||
|
||||
private val healthConnectClient by lazy {
|
||||
try {
|
||||
HealthConnectClient.getOrCreate(context)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to create Health Connect client", e)
|
||||
_isCompatible.value = false
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** Check if Health Connect is available on this device */
|
||||
fun isHealthConnectAvailable(): Flow<Boolean> = flow {
|
||||
try {
|
||||
if (!_isCompatible.value) {
|
||||
emit(false)
|
||||
return@flow
|
||||
}
|
||||
val status = HealthConnectClient.getSdkStatus(context)
|
||||
emit(status == HealthConnectClient.SDK_AVAILABLE)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error checking Health Connect availability", e)
|
||||
_isCompatible.value = false
|
||||
emit(false)
|
||||
}
|
||||
}
|
||||
|
||||
/** Enable or disable Health Connect integration */
|
||||
fun setEnabled(enabled: Boolean) {
|
||||
preferences.edit().putBoolean("enabled", enabled).apply()
|
||||
_isEnabled.value = enabled
|
||||
|
||||
if (!enabled) {
|
||||
setPermissionsGranted(false)
|
||||
}
|
||||
}
|
||||
|
||||
/** Update the permissions granted state */
|
||||
fun setPermissionsGranted(granted: Boolean) {
|
||||
preferences.edit().putBoolean("permissions", granted).apply()
|
||||
_hasPermissions.value = granted
|
||||
}
|
||||
|
||||
/** Enable or disable auto-sync */
|
||||
fun setAutoSyncEnabled(enabled: Boolean) {
|
||||
preferences.edit().putBoolean("auto_sync", enabled).apply()
|
||||
_autoSync.value = enabled
|
||||
}
|
||||
|
||||
/** Check if all required permissions are granted */
|
||||
suspend fun hasAllPermissions(): Boolean {
|
||||
return try {
|
||||
if (!_isCompatible.value || healthConnectClient == null) {
|
||||
return false
|
||||
}
|
||||
val grantedPermissions =
|
||||
healthConnectClient!!.permissionController.getGrantedPermissions()
|
||||
val hasAll =
|
||||
REQUIRED_PERMISSIONS.all { permission ->
|
||||
grantedPermissions.contains(permission)
|
||||
}
|
||||
setPermissionsGranted(hasAll)
|
||||
hasAll
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error checking permissions", e)
|
||||
setPermissionsGranted(false)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Check if Health Connect is ready for use */
|
||||
suspend fun isReady(): Boolean {
|
||||
return try {
|
||||
if (!_isEnabled.value || !_isCompatible.value || healthConnectClient == null)
|
||||
return false
|
||||
|
||||
val isAvailable =
|
||||
HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE
|
||||
val hasPerms = if (isAvailable) hasAllPermissions() else false
|
||||
isAvailable && hasPerms
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error checking Health Connect readiness", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Get permission request contract */
|
||||
fun getPermissionRequestContract(): ActivityResultContract<Set<String>, Set<String>> {
|
||||
return PermissionController.createRequestPermissionResultContract()
|
||||
}
|
||||
|
||||
/** Test Health Connect functionality */
|
||||
fun testHealthConnectSync(): String {
|
||||
val results = mutableListOf<String>()
|
||||
|
||||
results.add("=== Health Connect Debug Test ===")
|
||||
|
||||
try {
|
||||
// Check availability synchronously
|
||||
val packageManager = context.packageManager
|
||||
val healthConnectPackages =
|
||||
listOf(
|
||||
"com.google.android.apps.healthdata",
|
||||
"com.android.health.connect",
|
||||
"androidx.health.connect"
|
||||
)
|
||||
|
||||
val available =
|
||||
healthConnectPackages.any { packageName ->
|
||||
try {
|
||||
packageManager.getPackageInfo(packageName, 0)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
results.add("Available: $available")
|
||||
|
||||
// Check enabled state
|
||||
results.add("Enabled in settings: ${_isEnabled.value}")
|
||||
|
||||
// Check permissions (simplified)
|
||||
val hasPerms = _hasPermissions.value
|
||||
results.add("Has permissions: $hasPerms")
|
||||
|
||||
// Check compatibility
|
||||
results.add("API Compatible: ${_isCompatible.value}")
|
||||
|
||||
val ready = _isEnabled.value && _isCompatible.value && available && hasPerms
|
||||
results.add("Ready to sync: $ready")
|
||||
|
||||
if (ready) {
|
||||
results.add("Health Connect is connected!")
|
||||
} else {
|
||||
results.add("❌ Health Connect not ready")
|
||||
if (!available) results.add("- Health Connect not available on device")
|
||||
if (!_isEnabled.value) results.add("- Not enabled in OpenClimb settings")
|
||||
if (!hasPerms) results.add("- Permissions not granted")
|
||||
if (!_isCompatible.value) results.add("- API compatibility issues")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
results.add("Test failed with error: ${e.message}")
|
||||
Log.e(TAG, "Health Connect test failed", e)
|
||||
}
|
||||
|
||||
return results.joinToString("\n")
|
||||
}
|
||||
|
||||
/** Get required permissions as strings */
|
||||
fun getRequiredPermissions(): Set<String> {
|
||||
return try {
|
||||
REQUIRED_PERMISSIONS.map { it.toString() }.toSet()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error getting required permissions", e)
|
||||
emptySet()
|
||||
}
|
||||
}
|
||||
|
||||
/** Sync a completed climbing session to Health Connect */
|
||||
@SuppressLint("RestrictedApi")
|
||||
suspend fun syncClimbingSession(
|
||||
session: ClimbSession,
|
||||
gymName: String,
|
||||
attemptCount: Int = 0
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
if (!isReady()) {
|
||||
return Result.failure(IllegalStateException("Health Connect not ready"))
|
||||
}
|
||||
|
||||
if (session.status != SessionStatus.COMPLETED) {
|
||||
return Result.failure(
|
||||
IllegalArgumentException("Only completed sessions can be synced")
|
||||
)
|
||||
}
|
||||
|
||||
val startTime = session.startTime?.let { DateFormatUtils.parseISO8601(it) }
|
||||
val endTime = session.endTime?.let { DateFormatUtils.parseISO8601(it) }
|
||||
|
||||
if (startTime == null || endTime == null) {
|
||||
return Result.failure(
|
||||
IllegalArgumentException("Session must have valid start and end times")
|
||||
)
|
||||
}
|
||||
|
||||
Log.d(TAG, "Attempting to sync session '${session.id}' to Health Connect...")
|
||||
|
||||
val records = mutableListOf<androidx.health.connect.client.records.Record>()
|
||||
|
||||
try {
|
||||
val exerciseSession =
|
||||
ExerciseSessionRecord(
|
||||
startTime = startTime,
|
||||
startZoneOffset =
|
||||
ZoneOffset.systemDefault().rules.getOffset(startTime),
|
||||
endTime = endTime,
|
||||
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||
exerciseType =
|
||||
ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING,
|
||||
title = "Rock Climbing at $gymName"
|
||||
)
|
||||
records.add(exerciseSession)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to create exercise session record", e)
|
||||
}
|
||||
|
||||
try {
|
||||
val durationMinutes = Duration.between(startTime, endTime).toMinutes()
|
||||
val estimatedCalories = estimateCaloriesForClimbing(durationMinutes, attemptCount)
|
||||
|
||||
if (estimatedCalories > 0) {
|
||||
val caloriesRecord =
|
||||
TotalCaloriesBurnedRecord(
|
||||
startTime = startTime,
|
||||
startZoneOffset =
|
||||
ZoneOffset.systemDefault().rules.getOffset(startTime),
|
||||
endTime = endTime,
|
||||
endZoneOffset =
|
||||
ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||
energy = Energy.calories(estimatedCalories)
|
||||
)
|
||||
records.add(caloriesRecord)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to create calories record", e)
|
||||
}
|
||||
|
||||
try {
|
||||
val heartRateRecord = createHeartRateRecord(startTime, endTime, attemptCount)
|
||||
heartRateRecord?.let { records.add(it) }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to create heart rate record", e)
|
||||
}
|
||||
|
||||
if (records.isNotEmpty() && healthConnectClient != null) {
|
||||
Log.d(TAG, "Writing ${records.size} records to Health Connect...")
|
||||
healthConnectClient!!.insertRecords(records)
|
||||
Log.i(
|
||||
TAG,
|
||||
"Successfully synced ${records.size} records for session '${session.id}' to Health Connect"
|
||||
)
|
||||
|
||||
preferences
|
||||
.edit()
|
||||
.putString("last_sync_success", DateFormatUtils.nowISO8601())
|
||||
.apply()
|
||||
} else {
|
||||
val reason =
|
||||
when {
|
||||
records.isEmpty() -> "No records created"
|
||||
healthConnectClient == null -> "Health Connect client unavailable"
|
||||
else -> "Unknown reason"
|
||||
}
|
||||
Log.w(TAG, "Sync failed for session '${session.id}': $reason")
|
||||
return Result.failure(Exception("Sync failed: $reason"))
|
||||
}
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error syncing climbing session to Health Connect", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Auto-sync a session if enabled */
|
||||
suspend fun autoSyncSession(
|
||||
session: ClimbSession,
|
||||
gymName: String,
|
||||
attemptCount: Int = 0
|
||||
): Result<Unit> {
|
||||
return if (_autoSync.value && isReady()) {
|
||||
Log.d(TAG, "Auto-syncing session '${session.id}' to Health Connect...")
|
||||
syncClimbingSession(session, gymName, attemptCount)
|
||||
} else {
|
||||
val reason =
|
||||
when {
|
||||
!_autoSync.value -> "auto-sync disabled"
|
||||
!isReady() -> "Health Connect not ready"
|
||||
else -> "unknown reason"
|
||||
}
|
||||
Log.d(TAG, "Auto-sync skipped for session '${session.id}': $reason")
|
||||
Result.success(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
/** Estimate calories burned during climbing */
|
||||
private fun estimateCaloriesForClimbing(durationMinutes: Long, attemptCount: Int): Double {
|
||||
val baseCaloriesPerMinute = 8.0
|
||||
val intensityMultiplier =
|
||||
when {
|
||||
attemptCount >= 20 -> 1.3
|
||||
attemptCount >= 10 -> 1.1
|
||||
else -> 0.9
|
||||
}
|
||||
return durationMinutes * baseCaloriesPerMinute * intensityMultiplier
|
||||
}
|
||||
|
||||
/** Create heart rate data */
|
||||
@SuppressLint("RestrictedApi")
|
||||
private fun createHeartRateRecord(
|
||||
startTime: Instant,
|
||||
endTime: Instant,
|
||||
attemptCount: Int
|
||||
): HeartRateRecord? {
|
||||
return try {
|
||||
val samples = mutableListOf<HeartRateRecord.Sample>()
|
||||
val intervalMinutes = 5L
|
||||
|
||||
val baseHeartRate =
|
||||
when {
|
||||
attemptCount >= 20 -> 155L
|
||||
attemptCount >= 10 -> 145L
|
||||
else -> 135L
|
||||
}
|
||||
|
||||
var currentTime = startTime
|
||||
while (currentTime.isBefore(endTime)) {
|
||||
val variation = (-15..15).random()
|
||||
val heartRate = (baseHeartRate + variation).coerceIn(110L, 180L)
|
||||
|
||||
samples.add(HeartRateRecord.Sample(time = currentTime, beatsPerMinute = heartRate))
|
||||
currentTime = currentTime.plusSeconds(intervalMinutes * 60)
|
||||
}
|
||||
|
||||
if (samples.isEmpty()) return null
|
||||
|
||||
HeartRateRecord(
|
||||
startTime = startTime,
|
||||
startZoneOffset = ZoneOffset.systemDefault().rules.getOffset(startTime),
|
||||
endTime = endTime,
|
||||
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||
samples = samples
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error creating heart rate record", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** Reset all preferences */
|
||||
fun reset() {
|
||||
preferences.edit().clear().apply()
|
||||
_isEnabled.value = false
|
||||
_hasPermissions.value = false
|
||||
_autoSync.value = true
|
||||
}
|
||||
|
||||
/** Check if ready for use */
|
||||
fun isReadySync(): Boolean {
|
||||
return _isEnabled.value && _hasPermissions.value
|
||||
}
|
||||
|
||||
/** Get last successful sync timestamp */
|
||||
fun getLastSyncSuccess(): String? {
|
||||
return preferences.getString("last_sync_success", null)
|
||||
}
|
||||
|
||||
/** Get detailed status */
|
||||
fun getDetailedStatus(): Map<String, String> {
|
||||
return mapOf(
|
||||
"enabled" to _isEnabled.value.toString(),
|
||||
"hasPermissions" to _hasPermissions.value.toString(),
|
||||
"autoSync" to _autoSync.value.toString(),
|
||||
"compatible" to _isCompatible.value.toString(),
|
||||
"lastSyncSuccess" to (getLastSyncSuccess() ?: "never")
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package com.atridad.openclimb.data.model
|
||||
|
||||
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
|
||||
|
||||
@Serializable
|
||||
enum class AttemptResult {
|
||||
SUCCESS,
|
||||
FALL,
|
||||
NO_PROGRESS,
|
||||
FLASH,
|
||||
}
|
||||
|
||||
@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"])]
|
||||
)
|
||||
@Serializable
|
||||
data class Attempt(
|
||||
@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,
|
||||
val updatedAt: 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 = DateFormatUtils.nowISO8601()
|
||||
): Attempt {
|
||||
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,
|
||||
updatedAt = now
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package com.atridad.openclimb.data.model
|
||||
|
||||
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
|
||||
|
||||
@Serializable
|
||||
enum class SessionStatus {
|
||||
ACTIVE,
|
||||
COMPLETED,
|
||||
PAUSED
|
||||
}
|
||||
|
||||
@Entity(
|
||||
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
|
||||
) {
|
||||
companion object {
|
||||
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
|
||||
)
|
||||
}
|
||||
|
||||
fun ClimbSession.complete(): ClimbSession {
|
||||
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 = DateFormatUtils.nowISO8601()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.atridad.openclimb.data.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class ClimbType {
|
||||
ROPE,
|
||||
BOULDER;
|
||||
|
||||
/**
|
||||
* Get the display name
|
||||
*/
|
||||
fun getDisplayName(): String = when (this) {
|
||||
ROPE -> "Rope"
|
||||
BOULDER -> "Bouldering"
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
package com.atridad.openclimb.data.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class DifficultySystem {
|
||||
// Bouldering
|
||||
V_SCALE,
|
||||
FONT,
|
||||
|
||||
// Rope
|
||||
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
|
||||
}
|
||||
|
||||
/** 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() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
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
|
||||
*/
|
||||
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)
|
||||
DifficultySystem.YDS -> compareYDSGrades(grade, other.grade)
|
||||
DifficultySystem.CUSTOM -> grade.compareTo(other.grade)
|
||||
}
|
||||
}
|
||||
|
||||
private fun compareVScaleGrades(grade1: String, grade2: String): Int {
|
||||
if (grade1 == "VB" && grade2 != "VB") return -1
|
||||
if (grade2 == "VB" && grade1 != "VB") return 1
|
||||
if (grade1 == "VB") return 0
|
||||
|
||||
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 {
|
||||
return grade1.compareTo(grade2)
|
||||
}
|
||||
|
||||
private fun compareYDSGrades(grade1: String, grade2: String): Int {
|
||||
return grade1.compareTo(grade2)
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.atridad.openclimb.data.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import com.atridad.openclimb.utils.DateFormatUtils
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@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
|
||||
) {
|
||||
companion object {
|
||||
fun create(
|
||||
name: String,
|
||||
location: String? = null,
|
||||
supportedClimbTypes: List<ClimbType>,
|
||||
difficultySystems: List<DifficultySystem>,
|
||||
customDifficultyGrades: List<String> = emptyList(),
|
||||
notes: String? = null
|
||||
): Gym {
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package com.atridad.openclimb.data.model
|
||||
|
||||
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
|
||||
|
||||
@Entity(
|
||||
tableName = "problems",
|
||||
foreignKeys =
|
||||
[
|
||||
ForeignKey(
|
||||
entity = Gym::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["gymId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)],
|
||||
indices = [Index(value = ["gymId"])]
|
||||
)
|
||||
@Serializable
|
||||
data class Problem(
|
||||
@PrimaryKey val id: String,
|
||||
val gymId: String,
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val climbType: ClimbType,
|
||||
val difficulty: DifficultyGrade,
|
||||
val tags: List<String> = emptyList(),
|
||||
val location: String? = null,
|
||||
val imagePaths: List<String> = emptyList(),
|
||||
val isActive: Boolean = true,
|
||||
val dateSet: String? = null,
|
||||
val notes: String? = null,
|
||||
val createdAt: String,
|
||||
val updatedAt: String
|
||||
) {
|
||||
companion object {
|
||||
fun create(
|
||||
gymId: String,
|
||||
name: String? = null,
|
||||
description: String? = null,
|
||||
climbType: ClimbType,
|
||||
difficulty: DifficultyGrade,
|
||||
tags: List<String> = emptyList(),
|
||||
location: String? = null,
|
||||
imagePaths: List<String> = emptyList(),
|
||||
dateSet: String? = null,
|
||||
notes: String? = null
|
||||
): Problem {
|
||||
val now = DateFormatUtils.nowISO8601()
|
||||
return Problem(
|
||||
id = java.util.UUID.randomUUID().toString(),
|
||||
gymId = gymId,
|
||||
name = name,
|
||||
description = description,
|
||||
climbType = climbType,
|
||||
difficulty = difficulty,
|
||||
tags = tags,
|
||||
location = location,
|
||||
imagePaths = imagePaths,
|
||||
isActive = true,
|
||||
dateSet = dateSet,
|
||||
notes = notes,
|
||||
createdAt = now,
|
||||
updatedAt = now
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,569 +0,0 @@
|
||||
package com.atridad.openclimb.data.sync
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.util.Log
|
||||
import androidx.annotation.RequiresPermission
|
||||
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.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.io.Serializable
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
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 dataStateManager = DataStateManager(context)
|
||||
private val syncMutex = Mutex()
|
||||
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SyncService"
|
||||
}
|
||||
|
||||
private val sharedPreferences: SharedPreferences =
|
||||
context.getSharedPreferences("sync_preferences", Context.MODE_PRIVATE)
|
||||
|
||||
private val httpClient =
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(45, TimeUnit.SECONDS)
|
||||
.readTimeout(90, TimeUnit.SECONDS)
|
||||
.writeTimeout(90, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
private val json = Json {
|
||||
prettyPrint = true
|
||||
ignoreUnknownKeys = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
// 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 _isConfigured = MutableStateFlow(false)
|
||||
val isConfiguredFlow: StateFlow<Boolean> = _isConfigured.asStateFlow()
|
||||
|
||||
private val _isTesting = MutableStateFlow(false)
|
||||
val isTesting: StateFlow<Boolean> = _isTesting.asStateFlow()
|
||||
|
||||
private val _isAutoSyncEnabled = MutableStateFlow(true)
|
||||
val isAutoSyncEnabled: StateFlow<Boolean> = _isAutoSyncEnabled.asStateFlow()
|
||||
|
||||
private var isOfflineMode = false
|
||||
|
||||
// Debounced sync properties
|
||||
private var syncJob: Job? = null
|
||||
private var pendingChanges = false
|
||||
private val syncDebounceDelay = 2000L // 2 seconds
|
||||
|
||||
// Configuration keys
|
||||
private object Keys {
|
||||
const val SERVER_URL = "server_url"
|
||||
const val AUTH_TOKEN = "auth_token"
|
||||
const val IS_CONNECTED = "is_connected"
|
||||
const val LAST_SYNC_TIME = "last_sync_time"
|
||||
const val AUTO_SYNC_ENABLED = "auto_sync_enabled"
|
||||
const val OFFLINE_MODE = "offline_mode"
|
||||
}
|
||||
|
||||
init {
|
||||
loadInitialState()
|
||||
updateConfiguredState()
|
||||
repository.setAutoSyncCallback { serviceScope.launch { triggerAutoSync() } }
|
||||
}
|
||||
|
||||
private fun loadInitialState() {
|
||||
_lastSyncTime.value = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
||||
_isConnected.value = sharedPreferences.getBoolean(Keys.IS_CONNECTED, false)
|
||||
_isAutoSyncEnabled.value = sharedPreferences.getBoolean(Keys.AUTO_SYNC_ENABLED, true)
|
||||
isOfflineMode = sharedPreferences.getBoolean(Keys.OFFLINE_MODE, false)
|
||||
}
|
||||
|
||||
private fun updateConfiguredState() {
|
||||
_isConfigured.value = serverUrl.isNotBlank() && authToken.isNotBlank()
|
||||
}
|
||||
|
||||
var serverUrl: String
|
||||
get() = sharedPreferences.getString(Keys.SERVER_URL, "") ?: ""
|
||||
set(value) {
|
||||
sharedPreferences.edit { putString(Keys.SERVER_URL, value) }
|
||||
updateConfiguredState()
|
||||
_isConnected.value = false
|
||||
sharedPreferences.edit { putBoolean(Keys.IS_CONNECTED, false) }
|
||||
}
|
||||
|
||||
// Legacy accessor expected by some UI code (kept for compatibility)
|
||||
@Deprecated(
|
||||
message = "Use serverUrl (kebab case) instead",
|
||||
replaceWith = ReplaceWith("serverUrl")
|
||||
)
|
||||
var serverURL: String
|
||||
get() = serverUrl
|
||||
set(value) {
|
||||
serverUrl = value
|
||||
}
|
||||
|
||||
var authToken: String
|
||||
get() = sharedPreferences.getString(Keys.AUTH_TOKEN, "") ?: ""
|
||||
set(value) {
|
||||
sharedPreferences.edit { putString(Keys.AUTH_TOKEN, value) }
|
||||
updateConfiguredState()
|
||||
_isConnected.value = false
|
||||
sharedPreferences.edit { putBoolean(Keys.IS_CONNECTED, false) }
|
||||
}
|
||||
|
||||
fun setAutoSyncEnabled(enabled: Boolean) {
|
||||
_isAutoSyncEnabled.value = enabled
|
||||
sharedPreferences.edit { putBoolean(Keys.AUTO_SYNC_ENABLED, enabled) }
|
||||
}
|
||||
|
||||
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
|
||||
private fun isNetworkAvailable(): Boolean {
|
||||
val connectivityManager =
|
||||
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val network = connectivityManager.activeNetwork ?: return false
|
||||
val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
|
||||
return when {
|
||||
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
|
||||
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
|
||||
suspend fun syncWithServer() {
|
||||
if (isOfflineMode) {
|
||||
Log.d(TAG, "Sync skipped: Offline mode is enabled.")
|
||||
return
|
||||
}
|
||||
if (!isNetworkAvailable()) {
|
||||
_syncError.value = "No internet connection."
|
||||
Log.d(TAG, "Sync skipped: No internet connection.")
|
||||
return
|
||||
}
|
||||
if (!_isConfigured.value) {
|
||||
throw SyncException.NotConfigured
|
||||
}
|
||||
if (!_isConnected.value) {
|
||||
throw SyncException.NotConnected
|
||||
}
|
||||
|
||||
syncMutex.withLock {
|
||||
_isSyncing.value = true
|
||||
_syncError.value = null
|
||||
|
||||
try {
|
||||
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 -> {
|
||||
Log.d(TAG, "Both local and server data exist, merging (server wins)")
|
||||
mergeDataSafely(serverBackup)
|
||||
Log.d(TAG, "Merge completed")
|
||||
}
|
||||
else -> {
|
||||
Log.d(TAG, "No data to sync")
|
||||
}
|
||||
}
|
||||
|
||||
val now = DateFormatUtils.nowISO8601()
|
||||
_lastSyncTime.value = now
|
||||
sharedPreferences.edit { putString(Keys.LAST_SYNC_TIME, now) }
|
||||
} catch (e: Exception) {
|
||||
_syncError.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
_isSyncing.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun downloadData(): ClimbDataBackup {
|
||||
val request =
|
||||
Request.Builder()
|
||||
.url("$serverUrl/sync")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body?.string()
|
||||
if (!body.isNullOrEmpty()) {
|
||||
json.decodeFromString(body)
|
||||
} else {
|
||||
ClimbDataBackup(
|
||||
exportedAt = DateFormatUtils.nowISO8601(),
|
||||
gyms = emptyList(),
|
||||
problems = emptyList(),
|
||||
sessions = emptyList(),
|
||||
attempts = emptyList()
|
||||
)
|
||||
}
|
||||
} else {
|
||||
handleHttpError(response.code)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
throw SyncException.NetworkError(e.message ?: "Network error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun uploadData(backup: ClimbDataBackup) {
|
||||
val requestBody =
|
||||
json.encodeToString(ClimbDataBackup.serializer(), backup)
|
||||
.toRequestBody("application/json".toMediaType())
|
||||
|
||||
val request =
|
||||
Request.Builder()
|
||||
.url("$serverUrl/sync")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.post(requestBody)
|
||||
.build()
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
handleHttpError(response.code)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
throw SyncException.NetworkError(e.message ?: "Network error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun syncImagesFromServer(backup: ClimbDataBackup): Map<String, String> {
|
||||
val imagePathMapping = mutableMapOf<String, String>()
|
||||
val totalImages = backup.problems.sumOf { it.imagePaths?.size ?: 0 }
|
||||
Log.d(TAG, "Starting image download from server for $totalImages images")
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
backup.problems.forEach { problem ->
|
||||
problem.imagePaths?.forEach { imagePath ->
|
||||
val serverFilename = imagePath.substringAfterLast('/')
|
||||
try {
|
||||
val localImagePath = downloadImage(serverFilename)
|
||||
if (localImagePath != null) {
|
||||
imagePathMapping[imagePath] = localImagePath
|
||||
}
|
||||
} catch (_: SyncException.ImageNotFound) {
|
||||
Log.w(TAG, "Image not found on server: $imagePath")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to download image $imagePath: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return imagePathMapping
|
||||
}
|
||||
|
||||
private suspend fun downloadImage(serverFilename: String): String? {
|
||||
val request =
|
||||
Request.Builder()
|
||||
.url("$serverUrl/images/download?filename=$serverFilename")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.build()
|
||||
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (response.isSuccessful) {
|
||||
response.body?.bytes()?.let {
|
||||
ImageUtils.saveImageFromBytesWithFilename(context, it, serverFilename)
|
||||
}
|
||||
} else {
|
||||
if (response.code == 404) throw SyncException.ImageNotFound
|
||||
null
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "Network error downloading image $serverFilename", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun syncImagesForBackup(backup: ClimbDataBackup) {
|
||||
Log.d(TAG, "Starting image sync for backup with ${backup.problems.size} problems")
|
||||
withContext(Dispatchers.IO) {
|
||||
backup.problems.forEach { problem ->
|
||||
problem.imagePaths?.forEach { localPath ->
|
||||
val filename = localPath.substringAfterLast('/')
|
||||
uploadImage(localPath, filename)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun uploadImage(localPath: String, filename: String) {
|
||||
val file = ImageUtils.getImageFile(context, localPath)
|
||||
if (!file.exists()) {
|
||||
Log.w(TAG, "Local image file not found, cannot upload: $localPath")
|
||||
return
|
||||
}
|
||||
|
||||
val requestBody = file.readBytes().toRequestBody("application/octet-stream".toMediaType())
|
||||
|
||||
val request =
|
||||
Request.Builder()
|
||||
.url("$serverUrl/images/upload?filename=$filename")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.post(requestBody)
|
||||
.build()
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
if (response.isSuccessful) {
|
||||
Log.d(TAG, "Successfully uploaded image: $filename")
|
||||
} else {
|
||||
Log.w(
|
||||
TAG,
|
||||
"Failed to upload image $filename. Server responded with ${response.code}"
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "Network error uploading image $filename", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun createBackupFromRepository(): ClimbDataBackup {
|
||||
return withContext(Dispatchers.Default) {
|
||||
ClimbDataBackup(
|
||||
exportedAt = dataStateManager.getLastModified(),
|
||||
gyms = repository.getAllGyms().first().map { BackupGym.fromGym(it) },
|
||||
problems =
|
||||
repository.getAllProblems().first().map { problem ->
|
||||
val backupProblem = BackupProblem.fromProblem(problem)
|
||||
val normalizedImagePaths =
|
||||
problem.imagePaths.mapIndexed { index, _ ->
|
||||
ImageNamingUtils.generateImageFilename(
|
||||
problem.id,
|
||||
index
|
||||
)
|
||||
}
|
||||
if (normalizedImagePaths.isNotEmpty()) {
|
||||
backupProblem.copy(imagePaths = normalizedImagePaths)
|
||||
} else {
|
||||
backupProblem
|
||||
}
|
||||
},
|
||||
sessions =
|
||||
repository.getAllSessions().first().map {
|
||||
BackupClimbSession.fromClimbSession(it)
|
||||
},
|
||||
attempts =
|
||||
repository.getAllAttempts().first().map {
|
||||
BackupAttempt.fromAttempt(it)
|
||||
},
|
||||
deletedItems = repository.getDeletedItems()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun importBackupToRepository(
|
||||
backup: ClimbDataBackup,
|
||||
imagePathMapping: Map<String, String>
|
||||
) {
|
||||
val gyms = backup.gyms.map { it.toGym() }
|
||||
val problems =
|
||||
backup.problems.map { backupProblem ->
|
||||
val imagePaths = backupProblem.imagePaths
|
||||
val updatedImagePaths =
|
||||
imagePaths?.map { oldPath ->
|
||||
imagePathMapping[oldPath] ?: oldPath
|
||||
}
|
||||
backupProblem.copy(imagePaths = updatedImagePaths).toProblem()
|
||||
}
|
||||
val sessions = backup.sessions.map { it.toClimbSession() }
|
||||
val attempts = backup.attempts.map { it.toAttempt() }
|
||||
|
||||
repository.resetAllData()
|
||||
|
||||
gyms.forEach { repository.insertGymWithoutSync(it) }
|
||||
problems.forEach { repository.insertProblemWithoutSync(it) }
|
||||
sessions.forEach { repository.insertSessionWithoutSync(it) }
|
||||
attempts.forEach { repository.insertAttemptWithoutSync(it) }
|
||||
|
||||
repository.clearDeletedItems()
|
||||
}
|
||||
|
||||
private suspend fun mergeDataSafely(serverBackup: ClimbDataBackup) {
|
||||
Log.d(TAG, "Server data will overwrite local data. Performing full restore.")
|
||||
val imagePathMapping = syncImagesFromServer(serverBackup)
|
||||
importBackupToRepository(serverBackup, imagePathMapping)
|
||||
}
|
||||
|
||||
private fun handleHttpError(code: Int): Nothing {
|
||||
when (code) {
|
||||
401 -> throw SyncException.Unauthorized
|
||||
in 500..599 -> throw SyncException.ServerError(code)
|
||||
else -> throw SyncException.InvalidResponse("HTTP error code: $code")
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun testConnection() {
|
||||
if (!_isConfigured.value) {
|
||||
_isConnected.value = false
|
||||
_syncError.value = "Server URL or Auth Token is not set."
|
||||
return
|
||||
}
|
||||
_isTesting.value = true
|
||||
_syncError.value = null
|
||||
|
||||
val request =
|
||||
Request.Builder()
|
||||
.url("$serverUrl/sync")
|
||||
.header("Authorization", "Bearer $authToken")
|
||||
.head()
|
||||
.build()
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
_isConnected.value = response.isSuccessful || response.code == 405
|
||||
}
|
||||
}
|
||||
if (!_isConnected.value) {
|
||||
_syncError.value = "Connection failed. Check URL and token."
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_isConnected.value = false
|
||||
_syncError.value = "Connection error: ${e.message}"
|
||||
} finally {
|
||||
sharedPreferences.edit { putBoolean(Keys.IS_CONNECTED, _isConnected.value) }
|
||||
_isTesting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
fun triggerAutoSync() {
|
||||
if (!_isConfigured.value || !_isConnected.value || !_isAutoSyncEnabled.value) {
|
||||
return
|
||||
}
|
||||
if (_isSyncing.value) {
|
||||
pendingChanges = true
|
||||
return
|
||||
}
|
||||
syncJob?.cancel()
|
||||
syncJob =
|
||||
serviceScope.launch {
|
||||
delay(syncDebounceDelay)
|
||||
try {
|
||||
syncWithServer()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Auto-sync failed", e)
|
||||
}
|
||||
if (pendingChanges) {
|
||||
pendingChanges = false
|
||||
triggerAutoSync()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearConfiguration() {
|
||||
syncJob?.cancel()
|
||||
serverUrl = ""
|
||||
authToken = ""
|
||||
setAutoSyncEnabled(true)
|
||||
_lastSyncTime.value = null
|
||||
_isConnected.value = false
|
||||
_syncError.value = null
|
||||
sharedPreferences.edit { clear() }
|
||||
updateConfiguredState()
|
||||
}
|
||||
}
|
||||
|
||||
sealed class SyncException(message: String) : IOException(message), Serializable {
|
||||
object NotConfigured :
|
||||
SyncException("Sync is not configured. Please set server URL and auth token.") {
|
||||
@JvmStatic private fun readResolve(): Any = NotConfigured
|
||||
}
|
||||
|
||||
object NotConnected : SyncException("Not connected to server. Please test connection first.") {
|
||||
@JvmStatic private fun readResolve(): Any = NotConnected
|
||||
}
|
||||
|
||||
object Unauthorized : SyncException("Unauthorized. Please check your auth token.") {
|
||||
@JvmStatic private fun readResolve(): Any = Unauthorized
|
||||
}
|
||||
|
||||
object ImageNotFound : SyncException("Image not found on server") {
|
||||
@JvmStatic private fun readResolve(): Any = ImageNotFound
|
||||
}
|
||||
|
||||
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 NetworkError(val details: String) : SyncException("Network error: $details")
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.atridad.openclimb.navigation
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
|
||||
data class BottomNavigationItem(val screen: Screen, val icon: ImageVector, val label: String)
|
||||
|
||||
val bottomNavigationItems =
|
||||
listOf(
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Sessions,
|
||||
icon = Icons.Default.PlayArrow,
|
||||
label = "Sessions"
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Problems,
|
||||
icon = Icons.Default.Star,
|
||||
label = "Problems"
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Analytics,
|
||||
icon = Icons.Default.Info,
|
||||
label = "Analytics"
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Gyms,
|
||||
icon = Icons.Default.LocationOn,
|
||||
label = "Gyms"
|
||||
),
|
||||
BottomNavigationItem(
|
||||
screen = Screen.Settings,
|
||||
icon = Icons.Default.Settings,
|
||||
label = "Settings"
|
||||
)
|
||||
)
|
||||
@@ -1,288 +0,0 @@
|
||||
package com.atridad.openclimb.service
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.atridad.openclimb.MainActivity
|
||||
import com.atridad.openclimb.R
|
||||
import com.atridad.openclimb.data.database.OpenClimbDatabase
|
||||
import com.atridad.openclimb.data.repository.ClimbRepository
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.firstOrNull
|
||||
import java.time.LocalDateTime
|
||||
import java.time.temporal.ChronoUnit
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
class SessionTrackingService : Service() {
|
||||
|
||||
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
private var notificationJob: Job? = null
|
||||
private var monitoringJob: Job? = null
|
||||
|
||||
private lateinit var repository: ClimbRepository
|
||||
private lateinit var notificationManager: NotificationManager
|
||||
|
||||
companion object {
|
||||
const val NOTIFICATION_ID = 1001
|
||||
const val CHANNEL_ID = "session_tracking_channel"
|
||||
const val ACTION_START_SESSION = "start_session"
|
||||
const val ACTION_STOP_SESSION = "stop_session"
|
||||
const val EXTRA_SESSION_ID = "session_id"
|
||||
|
||||
fun createStartIntent(context: Context, sessionId: String): Intent {
|
||||
return Intent(context, SessionTrackingService::class.java).apply {
|
||||
action = ACTION_START_SESSION
|
||||
putExtra(EXTRA_SESSION_ID, sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
fun createStopIntent(context: Context, sessionId: String): Intent {
|
||||
return Intent(context, SessionTrackingService::class.java).apply {
|
||||
action = ACTION_STOP_SESSION
|
||||
putExtra(EXTRA_SESSION_ID, sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
val database = OpenClimbDatabase.getDatabase(this)
|
||||
repository = ClimbRepository(database, this)
|
||||
notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_START_SESSION -> {
|
||||
val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)
|
||||
if (sessionId != null) {
|
||||
startSessionTracking(sessionId)
|
||||
}
|
||||
}
|
||||
ACTION_STOP_SESSION -> {
|
||||
val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)
|
||||
serviceScope.launch {
|
||||
try {
|
||||
val targetSession = when {
|
||||
sessionId != null -> repository.getSessionById(sessionId)
|
||||
else -> repository.getActiveSession()
|
||||
}
|
||||
if (targetSession != null && targetSession.status == com.atridad.openclimb.data.model.SessionStatus.ACTIVE) {
|
||||
val completed = with(com.atridad.openclimb.data.model.ClimbSession) { targetSession.complete() }
|
||||
repository.updateSession(completed)
|
||||
}
|
||||
} finally {
|
||||
stopSessionTracking()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return START_REDELIVER_INTENT
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun startSessionTracking(sessionId: String) {
|
||||
notificationJob?.cancel()
|
||||
monitoringJob?.cancel()
|
||||
|
||||
try {
|
||||
createAndShowNotification(sessionId)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
|
||||
notificationJob = serviceScope.launch {
|
||||
try {
|
||||
if (!isNotificationActive()) {
|
||||
delay(1000L)
|
||||
createAndShowNotification(sessionId)
|
||||
}
|
||||
|
||||
while (isActive) {
|
||||
delay(5000L)
|
||||
updateNotification(sessionId)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
monitoringJob = serviceScope.launch {
|
||||
try {
|
||||
while (isActive) {
|
||||
delay(10000L)
|
||||
|
||||
if (!isNotificationActive()) {
|
||||
updateNotification(sessionId)
|
||||
}
|
||||
|
||||
val session = repository.getSessionById(sessionId)
|
||||
if (session == null || session.status != com.atridad.openclimb.data.model.SessionStatus.ACTIVE) {
|
||||
stopSessionTracking()
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopSessionTracking() {
|
||||
notificationJob?.cancel()
|
||||
monitoringJob?.cancel()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun isNotificationActive(): Boolean {
|
||||
return try {
|
||||
val activeNotifications = notificationManager.activeNotifications
|
||||
activeNotifications.any { it.id == NOTIFICATION_ID }
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun updateNotification(sessionId: String) {
|
||||
try {
|
||||
createAndShowNotification(sessionId)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
|
||||
try {
|
||||
delay(10000L)
|
||||
createAndShowNotification(sessionId)
|
||||
} catch (retryException: Exception) {
|
||||
retryException.printStackTrace()
|
||||
stopSessionTracking()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createAndShowNotification(sessionId: String) {
|
||||
try {
|
||||
val session = runBlocking {
|
||||
repository.getSessionById(sessionId)
|
||||
}
|
||||
if (session == null || session.status != com.atridad.openclimb.data.model.SessionStatus.ACTIVE) {
|
||||
stopSessionTracking()
|
||||
return
|
||||
}
|
||||
|
||||
val gym = runBlocking {
|
||||
repository.getGymById(session.gymId)
|
||||
}
|
||||
|
||||
val attempts = runBlocking {
|
||||
repository.getAttemptsBySession(sessionId).firstOrNull() ?: emptyList()
|
||||
}
|
||||
|
||||
val duration = session.startTime?.let { startTime ->
|
||||
try {
|
||||
val start = LocalDateTime.parse(startTime)
|
||||
val now = LocalDateTime.now()
|
||||
val totalSeconds = ChronoUnit.SECONDS.between(start, now)
|
||||
val hours = totalSeconds / 3600
|
||||
val minutes = (totalSeconds % 3600) / 60
|
||||
val seconds = totalSeconds % 60
|
||||
|
||||
when {
|
||||
hours > 0 -> "${hours}h ${minutes}m ${seconds}s"
|
||||
minutes > 0 -> "${minutes}m ${seconds}s"
|
||||
else -> "${totalSeconds}s"
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
"Active"
|
||||
}
|
||||
} ?: "Active"
|
||||
|
||||
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("Climbing Session Active")
|
||||
.setContentText("${gym?.name ?: "Gym"} • $duration • ${attempts.size} attempts")
|
||||
.setSmallIcon(R.drawable.ic_mountains)
|
||||
.setOngoing(true)
|
||||
.setAutoCancel(false)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setCategory(NotificationCompat.CATEGORY_SERVICE)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(createOpenAppIntent())
|
||||
.addAction(
|
||||
R.drawable.ic_mountains,
|
||||
"Open Session",
|
||||
createOpenAppIntent()
|
||||
)
|
||||
.addAction(
|
||||
android.R.drawable.ic_menu_close_clear_cancel,
|
||||
"End Session",
|
||||
createStopPendingIntent(sessionId)
|
||||
)
|
||||
.build()
|
||||
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
|
||||
notificationManager.notify(NOTIFICATION_ID, notification)
|
||||
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun createOpenAppIntent(): PendingIntent {
|
||||
val intent = Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
action = "OPEN_SESSION"
|
||||
}
|
||||
return PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
}
|
||||
|
||||
private fun createStopPendingIntent(sessionId: String): PendingIntent {
|
||||
val intent = createStopIntent(this, sessionId)
|
||||
return PendingIntent.getService(
|
||||
this,
|
||||
1,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
}
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Session Tracking",
|
||||
NotificationManager.IMPORTANCE_DEFAULT
|
||||
).apply {
|
||||
description = "Shows active climbing session information"
|
||||
setShowBadge(false)
|
||||
lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
|
||||
enableLights(false)
|
||||
enableVibration(false)
|
||||
setSound(null, null)
|
||||
}
|
||||
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
notificationJob?.cancel()
|
||||
monitoringJob?.cancel()
|
||||
serviceScope.cancel()
|
||||
}
|
||||
}
|
||||
@@ -1,403 +0,0 @@
|
||||
package com.atridad.openclimb.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.NavHostController
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
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
|
||||
import com.atridad.openclimb.ui.screens.*
|
||||
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
|
||||
import com.atridad.openclimb.ui.viewmodel.ClimbViewModelFactory
|
||||
import com.atridad.openclimb.utils.AppShortcutManager
|
||||
import com.atridad.openclimb.utils.NotificationPermissionUtils
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun OpenClimbApp(
|
||||
shortcutAction: String? = null,
|
||||
lastUsedGymId: String? = null,
|
||||
onShortcutActionProcessed: () -> Unit = {}
|
||||
) {
|
||||
val navController = rememberNavController()
|
||||
val context = LocalContext.current
|
||||
|
||||
var lastUsedGym by remember { mutableStateOf<com.atridad.openclimb.data.model.Gym?>(null) }
|
||||
|
||||
val database = remember { OpenClimbDatabase.getDatabase(context) }
|
||||
val repository = remember { ClimbRepository(database, context) }
|
||||
val syncService = remember { SyncService(context, repository) }
|
||||
val viewModel: ClimbViewModel =
|
||||
viewModel(factory = ClimbViewModelFactory(repository, syncService, context))
|
||||
|
||||
var showNotificationPermissionDialog by remember { mutableStateOf(false) }
|
||||
var hasCheckedNotificationPermission by remember { mutableStateOf(false) }
|
||||
|
||||
val permissionLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { isGranted: Boolean ->
|
||||
if (!isGranted) {
|
||||
showNotificationPermissionDialog = false
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (!hasCheckedNotificationPermission) {
|
||||
hasCheckedNotificationPermission = true
|
||||
|
||||
if (NotificationPermissionUtils.shouldRequestNotificationPermission() &&
|
||||
!NotificationPermissionUtils.isNotificationPermissionGranted(context)
|
||||
) {
|
||||
showNotificationPermissionDialog = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) { viewModel.ensureSessionTrackingServiceRunning(context) }
|
||||
|
||||
LaunchedEffect(Unit) { syncService.triggerAutoSync() }
|
||||
|
||||
val activeSession by viewModel.activeSession.collectAsState()
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
|
||||
LaunchedEffect(gyms) {
|
||||
if (gyms.isNotEmpty() && lastUsedGym == null) {
|
||||
lastUsedGym = viewModel.getLastUsedGym()
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(activeSession, gyms, lastUsedGym) {
|
||||
AppShortcutManager.updateShortcuts(
|
||||
context = context,
|
||||
hasActiveSession = activeSession != null,
|
||||
hasGyms = gyms.isNotEmpty(),
|
||||
lastUsedGym = if (activeSession == null && gyms.size > 1) lastUsedGym else null
|
||||
)
|
||||
}
|
||||
|
||||
LaunchedEffect(shortcutAction) {
|
||||
when (shortcutAction) {
|
||||
AppShortcutManager.ACTION_START_SESSION -> {
|
||||
navController.navigate(Screen.Sessions) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
AppShortcutManager.ACTION_END_SESSION -> {
|
||||
navController.navigate(Screen.Sessions) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
}
|
||||
|
||||
activeSession?.let { session -> viewModel.endSession(context, session.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(shortcutAction, activeSession, gyms, lastUsedGym) {
|
||||
if (shortcutAction == AppShortcutManager.ACTION_START_SESSION && gyms.isNotEmpty()) {
|
||||
android.util.Log.d(
|
||||
"OpenClimbApp",
|
||||
"Processing shortcut action: activeSession=$activeSession, gyms.size=${gyms.size}, lastUsedGymId=$lastUsedGymId, lastUsedGym=${lastUsedGym?.name}"
|
||||
)
|
||||
|
||||
if (activeSession == null) {
|
||||
if (NotificationPermissionUtils.shouldRequestNotificationPermission() &&
|
||||
!NotificationPermissionUtils.isNotificationPermissionGranted(
|
||||
context
|
||||
)
|
||||
) {
|
||||
android.util.Log.d("OpenClimbApp", "Showing notification permission dialog")
|
||||
showNotificationPermissionDialog = true
|
||||
} else {
|
||||
if (gyms.size == 1) {
|
||||
android.util.Log.d(
|
||||
"OpenClimbApp",
|
||||
"Starting session with single gym: ${gyms.first().name}"
|
||||
)
|
||||
viewModel.startSession(context, gyms.first().id)
|
||||
} else {
|
||||
val targetGym =
|
||||
lastUsedGymId?.let { gymId -> gyms.find { it.id == gymId } }
|
||||
?: lastUsedGym
|
||||
|
||||
if (targetGym != null) {
|
||||
android.util.Log.d(
|
||||
"OpenClimbApp",
|
||||
"Starting session with target gym: ${targetGym.name}"
|
||||
)
|
||||
viewModel.startSession(context, targetGym.id)
|
||||
} else {
|
||||
android.util.Log.d(
|
||||
"OpenClimbApp",
|
||||
"No target gym found, navigating to selection"
|
||||
)
|
||||
navController.navigate(Screen.AddEditSession())
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
android.util.Log.d(
|
||||
"OpenClimbApp",
|
||||
"Active session already exists: ${activeSession?.id}"
|
||||
)
|
||||
}
|
||||
|
||||
onShortcutActionProcessed()
|
||||
}
|
||||
}
|
||||
|
||||
var fabConfig by remember { mutableStateOf<FabConfig?>(null) }
|
||||
|
||||
Scaffold(
|
||||
bottomBar = { OpenClimbBottomNavigation(navController = navController) },
|
||||
floatingActionButton = {
|
||||
fabConfig?.let { config ->
|
||||
FloatingActionButton(
|
||||
onClick = config.onClick,
|
||||
containerColor = MaterialTheme.colorScheme.primary
|
||||
) {
|
||||
Icon(
|
||||
imageVector = config.icon,
|
||||
contentDescription = config.contentDescription
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
) { innerPadding ->
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = Screen.Sessions,
|
||||
modifier = Modifier.padding(innerPadding)
|
||||
) {
|
||||
composable<Screen.Sessions> {
|
||||
LaunchedEffect(gyms, activeSession) {
|
||||
fabConfig =
|
||||
if (gyms.isNotEmpty() && activeSession == null) {
|
||||
FabConfig(
|
||||
icon = Icons.Default.PlayArrow,
|
||||
contentDescription = "Start Session",
|
||||
onClick = {
|
||||
if (NotificationPermissionUtils
|
||||
.shouldRequestNotificationPermission() &&
|
||||
!NotificationPermissionUtils
|
||||
.isNotificationPermissionGranted(
|
||||
context
|
||||
)
|
||||
) {
|
||||
showNotificationPermissionDialog = true
|
||||
} else {
|
||||
navController.navigate(Screen.AddEditSession())
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
SessionsScreen(
|
||||
viewModel = viewModel,
|
||||
onNavigateToSessionDetail = { sessionId ->
|
||||
navController.navigate(Screen.SessionDetail(sessionId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.Problems> {
|
||||
LaunchedEffect(gyms) {
|
||||
fabConfig =
|
||||
if (gyms.isNotEmpty()) {
|
||||
FabConfig(
|
||||
icon = Icons.Default.Add,
|
||||
contentDescription = "Add Problem",
|
||||
onClick = {
|
||||
navController.navigate(Screen.AddEditProblem())
|
||||
}
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
ProblemsScreen(
|
||||
viewModel = viewModel,
|
||||
onNavigateToProblemDetail = { problemId ->
|
||||
navController.navigate(Screen.ProblemDetail(problemId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.Analytics> {
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AnalyticsScreen(viewModel = viewModel)
|
||||
}
|
||||
|
||||
composable<Screen.Gyms> {
|
||||
LaunchedEffect(Unit) {
|
||||
fabConfig =
|
||||
FabConfig(
|
||||
icon = Icons.Default.Add,
|
||||
contentDescription = "Add Gym",
|
||||
onClick = { navController.navigate(Screen.AddEditGym()) }
|
||||
)
|
||||
}
|
||||
GymsScreen(
|
||||
viewModel = viewModel,
|
||||
onNavigateToGymDetail = { gymId ->
|
||||
navController.navigate(Screen.GymDetail(gymId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.Settings> {
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
SettingsScreen(viewModel = viewModel)
|
||||
}
|
||||
|
||||
composable<Screen.SessionDetail> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.SessionDetail>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
SessionDetailScreen(
|
||||
sessionId = args.sessionId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
onNavigateToProblemDetail = { problemId ->
|
||||
navController.navigate(Screen.ProblemDetail(problemId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.ProblemDetail> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.ProblemDetail>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
ProblemDetailScreen(
|
||||
problemId = args.problemId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
onNavigateToEdit = { problemId ->
|
||||
navController.navigate(Screen.AddEditProblem(problemId = problemId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.GymDetail> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.GymDetail>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
GymDetailScreen(
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() },
|
||||
onNavigateToEdit = { gymId ->
|
||||
navController.navigate(Screen.AddEditGym(gymId = gymId))
|
||||
},
|
||||
onNavigateToSessionDetail = { sessionId ->
|
||||
navController.navigate(Screen.SessionDetail(sessionId))
|
||||
},
|
||||
onNavigateToProblemDetail = { problemId ->
|
||||
navController.navigate(Screen.ProblemDetail(problemId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.AddEditGym> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.AddEditGym>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AddEditGymScreen(
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.AddEditProblem> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.AddEditProblem>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AddEditProblemScreen(
|
||||
problemId = args.problemId,
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable<Screen.AddEditSession> { backStackEntry ->
|
||||
val args = backStackEntry.toRoute<Screen.AddEditSession>()
|
||||
LaunchedEffect(Unit) { fabConfig = null }
|
||||
AddEditSessionScreen(
|
||||
sessionId = args.sessionId,
|
||||
gymId = args.gymId,
|
||||
viewModel = viewModel,
|
||||
onNavigateBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showNotificationPermissionDialog) {
|
||||
NotificationPermissionDialog(
|
||||
onDismiss = { showNotificationPermissionDialog = false },
|
||||
onRequestPermission = {
|
||||
permissionLauncher.launch(
|
||||
NotificationPermissionUtils.getNotificationPermissionString()
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun OpenClimbBottomNavigation(navController: NavHostController) {
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
|
||||
NavigationBar {
|
||||
bottomNavigationItems.forEach { item ->
|
||||
val isSelected =
|
||||
when (item.screen) {
|
||||
is Screen.Sessions -> currentRoute?.contains("Session") == true
|
||||
is Screen.Problems -> currentRoute?.contains("Problem") == true
|
||||
is Screen.Gyms -> currentRoute?.contains("Gym") == true
|
||||
is Screen.Analytics -> currentRoute?.contains("Analytics") == true
|
||||
is Screen.Settings -> currentRoute?.contains("Settings") == true
|
||||
else -> currentRoute?.contains(item.screen::class.simpleName ?: "") == true
|
||||
}
|
||||
|
||||
NavigationBarItem(
|
||||
icon = { Icon(item.icon, contentDescription = item.label) },
|
||||
label = { Text(item.label) },
|
||||
selected = isSelected,
|
||||
onClick = {
|
||||
navController.navigate(item.screen) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
// Don't restore state - always start fresh when switching tabs
|
||||
restoreState = false
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class FabConfig(
|
||||
val icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
val contentDescription: String,
|
||||
val onClick: () -> Unit
|
||||
)
|
||||
@@ -1,123 +0,0 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.openclimb.data.model.ClimbSession
|
||||
import com.atridad.openclimb.data.model.Gym
|
||||
import com.atridad.openclimb.ui.theme.CustomIcons
|
||||
import kotlinx.coroutines.delay
|
||||
import java.time.LocalDateTime
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
@Composable
|
||||
fun ActiveSessionBanner(
|
||||
activeSession: ClimbSession?,
|
||||
gym: Gym?,
|
||||
onSessionClick: () -> Unit,
|
||||
onEndSession: () -> Unit
|
||||
) {
|
||||
if (activeSession != null) {
|
||||
// Add a timer that updates every second for real-time duration counting
|
||||
var currentTime by remember { mutableStateOf(LocalDateTime.now()) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
delay(1000) // Update every second
|
||||
currentTime = LocalDateTime.now()
|
||||
}
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onSessionClick() },
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.primaryContainer
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.PlayArrow,
|
||||
contentDescription = "Active session",
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Active Session",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
|
||||
Text(
|
||||
text = gym?.name ?: "Unknown Gym",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
|
||||
activeSession.startTime?.let { startTime ->
|
||||
val duration = calculateDuration(startTime, currentTime)
|
||||
Text(
|
||||
text = duration,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
IconButton(
|
||||
onClick = onEndSession,
|
||||
colors = IconButtonDefaults.iconButtonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error,
|
||||
contentColor = MaterialTheme.colorScheme.onError
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = CustomIcons.Stop(MaterialTheme.colorScheme.onError),
|
||||
contentDescription = "End session"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateDuration(startTimeString: String, currentTime: LocalDateTime): String {
|
||||
return try {
|
||||
val startTime = LocalDateTime.parse(startTimeString)
|
||||
val totalSeconds = ChronoUnit.SECONDS.between(startTime, currentTime)
|
||||
val hours = totalSeconds / 3600
|
||||
val minutes = (totalSeconds % 3600) / 60
|
||||
val seconds = totalSeconds % 60
|
||||
|
||||
when {
|
||||
hours > 0 -> "${hours}h ${minutes}m ${seconds}s"
|
||||
minutes > 0 -> "${minutes}m ${seconds}s"
|
||||
else -> "${totalSeconds}s"
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
"Active"
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.pager.HorizontalPager
|
||||
import androidx.compose.foundation.pager.rememberPagerState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val pagerState = rememberPagerState(initialPage = initialIndex, pageCount = { imagePaths.size })
|
||||
val thumbnailListState = rememberLazyListState()
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
|
||||
// Auto-scroll thumbnail list to center current image
|
||||
LaunchedEffect(pagerState.currentPage) {
|
||||
thumbnailListState.animateScrollToItem(index = pagerState.currentPage, scrollOffset = -200)
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties =
|
||||
DialogProperties(
|
||||
usePlatformDefaultWidth = false,
|
||||
decorFitsSystemWindows = false
|
||||
)
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {
|
||||
// Main image pager
|
||||
HorizontalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { page ->
|
||||
OrientationAwareImage(
|
||||
imagePath = imagePaths[page],
|
||||
contentDescription = "Full screen image",
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit
|
||||
)
|
||||
}
|
||||
|
||||
// Close button
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier =
|
||||
Modifier.align(Alignment.TopEnd)
|
||||
.padding(16.dp)
|
||||
.background(Color.Black.copy(alpha = 0.5f), CircleShape)
|
||||
) { Icon(Icons.Default.Close, contentDescription = "Close", tint = Color.White) }
|
||||
|
||||
// Image counter
|
||||
if (imagePaths.size > 1) {
|
||||
Card(
|
||||
modifier = Modifier.align(Alignment.TopCenter).padding(16.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = Color.Black.copy(alpha = 0.7f)
|
||||
)
|
||||
) {
|
||||
Text(
|
||||
text = "${pagerState.currentPage + 1} / ${imagePaths.size}",
|
||||
color = Color.White,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Thumbnail strip (if multiple images)
|
||||
if (imagePaths.size > 1) {
|
||||
Card(
|
||||
modifier =
|
||||
Modifier.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = Color.Black.copy(alpha = 0.7f)
|
||||
)
|
||||
) {
|
||||
LazyRow(
|
||||
state = thumbnailListState,
|
||||
modifier = Modifier.padding(8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
contentPadding = PaddingValues(horizontal = 8.dp)
|
||||
) {
|
||||
itemsIndexed(imagePaths) { index, imagePath ->
|
||||
val isSelected = index == pagerState.currentPage
|
||||
|
||||
OrientationAwareImage(
|
||||
imagePath = imagePath,
|
||||
contentDescription = "Thumbnail ${index + 1}",
|
||||
modifier =
|
||||
Modifier.size(60.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable {
|
||||
coroutineScope.launch {
|
||||
pagerState.animateScrollToPage(index)
|
||||
}
|
||||
}
|
||||
.then(
|
||||
if (isSelected) {
|
||||
Modifier.background(
|
||||
Color.White.copy(
|
||||
alpha = 0.3f
|
||||
),
|
||||
RoundedCornerShape(8.dp)
|
||||
)
|
||||
} else Modifier
|
||||
),
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
package com.atridad.openclimb.ui.components
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.CameraAlt
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PhotoLibrary
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.FileProvider
|
||||
import com.atridad.openclimb.utils.ImageUtils
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
@Composable
|
||||
fun ImagePicker(
|
||||
imageUris: List<String>,
|
||||
onImagesChanged: (List<String>) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
maxImages: Int = 5
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var tempImageUris by remember { mutableStateOf(imageUris) }
|
||||
var showImageSourceDialog by remember { mutableStateOf(false) }
|
||||
var cameraImageUri by remember { mutableStateOf<Uri?>(null) }
|
||||
|
||||
// Image picker launcher
|
||||
val imagePickerLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.GetMultipleContents()
|
||||
) { uris ->
|
||||
if (uris.isNotEmpty()) {
|
||||
val currentCount = tempImageUris.size
|
||||
val remainingSlots = maxImages - currentCount
|
||||
val urisToProcess = uris.take(remainingSlots)
|
||||
|
||||
// Process images
|
||||
val newImagePaths = mutableListOf<String>()
|
||||
urisToProcess.forEach { uri ->
|
||||
val imagePath = ImageUtils.saveTemporaryImageFromUri(context, uri)
|
||||
if (imagePath != null) {
|
||||
newImagePaths.add(imagePath)
|
||||
}
|
||||
}
|
||||
|
||||
if (newImagePaths.isNotEmpty()) {
|
||||
val updatedUris = tempImageUris + newImagePaths
|
||||
tempImageUris = updatedUris
|
||||
onImagesChanged(updatedUris)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Camera launcher
|
||||
val cameraLauncher =
|
||||
rememberLauncherForActivityResult(contract = ActivityResultContracts.TakePicture()) {
|
||||
success ->
|
||||
if (success) {
|
||||
cameraImageUri?.let { uri ->
|
||||
val imagePath = ImageUtils.saveTemporaryImageFromUri(context, uri)
|
||||
if (imagePath != null) {
|
||||
val updatedUris = tempImageUris + imagePath
|
||||
tempImageUris = updatedUris
|
||||
onImagesChanged(updatedUris)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Camera permission launcher
|
||||
val cameraPermissionLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { isGranted ->
|
||||
if (isGranted) {
|
||||
// Create image file for camera
|
||||
val imageFile = createImageFile(context)
|
||||
val uri =
|
||||
FileProvider.getUriForFile(
|
||||
context,
|
||||
"${context.packageName}.fileprovider",
|
||||
imageFile
|
||||
)
|
||||
cameraImageUri = uri
|
||||
cameraLauncher.launch(uri)
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = modifier) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = "Photos (${tempImageUris.size}/$maxImages)",
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
|
||||
if (tempImageUris.size < maxImages) {
|
||||
TextButton(onClick = { showImageSourceDialog = true }) {
|
||||
Icon(
|
||||
Icons.Default.Add,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Add Photos")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (tempImageUris.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(tempImageUris) { imagePath ->
|
||||
ImageItem(
|
||||
imagePath = imagePath,
|
||||
onRemove = {
|
||||
val updatedUris = tempImageUris.filter { it != imagePath }
|
||||
tempImageUris = updatedUris
|
||||
onImagesChanged(updatedUris)
|
||||
|
||||
// Delete the image file
|
||||
ImageUtils.deleteImage(context, imagePath)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().height(100.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
Icons.Default.Add,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Add photos of this problem",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Image Source Selection Dialog
|
||||
if (showImageSourceDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showImageSourceDialog = false },
|
||||
title = { Text("Add Photo") },
|
||||
text = { Text("Choose how you'd like to add a photo") },
|
||||
confirmButton = {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
showImageSourceDialog = false
|
||||
imagePickerLauncher.launch("image/*")
|
||||
}
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.PhotoLibrary,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Gallery")
|
||||
}
|
||||
|
||||
TextButton(
|
||||
onClick = {
|
||||
showImageSourceDialog = false
|
||||
when (ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.CAMERA
|
||||
)
|
||||
) {
|
||||
PackageManager.PERMISSION_GRANTED -> {
|
||||
// Create image file for camera
|
||||
val imageFile = createImageFile(context)
|
||||
val uri =
|
||||
FileProvider.getUriForFile(
|
||||
context,
|
||||
"${context.packageName}.fileprovider",
|
||||
imageFile
|
||||
)
|
||||
cameraImageUri = uri
|
||||
cameraLauncher.launch(uri)
|
||||
}
|
||||
else -> {
|
||||
cameraPermissionLauncher.launch(
|
||||
Manifest.permission.CAMERA
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.CameraAlt,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Camera")
|
||||
}
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showImageSourceDialog = false }) { Text("Cancel") }
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createImageFile(context: android.content.Context): File {
|
||||
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
|
||||
val imageFileName = "JPEG_${timeStamp}_"
|
||||
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
|
||||
return File.createTempFile(imageFileName, ".jpg", storageDir)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ImageItem(imagePath: String, onRemove: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
val imageFile = ImageUtils.getImageFile(context, imagePath)
|
||||
|
||||
Box(modifier = modifier.size(80.dp)) {
|
||||
OrientationAwareImage(
|
||||
imagePath = imagePath,
|
||||
contentDescription = "Problem photo",
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
|
||||
IconButton(onClick = onRemove, modifier = Modifier.align(Alignment.TopEnd).size(24.dp)) {
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = "Remove photo",
|
||||
modifier = Modifier.fillMaxSize().padding(2.dp),
|
||||
tint = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,440 +0,0 @@
|
||||
package com.atridad.openclimb.ui.health
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.openclimb.data.health.HealthConnectManager
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HealthConnectCard(modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
val healthConnectManager = remember { HealthConnectManager(context) }
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
|
||||
// State tracking
|
||||
var isHealthConnectAvailable by remember { mutableStateOf(false) }
|
||||
var isLoading by remember { mutableStateOf(true) }
|
||||
var errorMessage by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
// Collect flows
|
||||
val isEnabled by healthConnectManager.isEnabled.collectAsState(initial = false)
|
||||
val hasPermissions by healthConnectManager.hasPermissions.collectAsState(initial = false)
|
||||
val autoSyncEnabled by healthConnectManager.autoSyncEnabled.collectAsState(initial = true)
|
||||
val isCompatible by healthConnectManager.isCompatible.collectAsState(initial = true)
|
||||
|
||||
// Permission launcher
|
||||
val permissionLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = healthConnectManager.getPermissionRequestContract()
|
||||
) { grantedPermissions ->
|
||||
coroutineScope.launch {
|
||||
val allGranted = healthConnectManager.hasAllPermissions()
|
||||
if (!allGranted) {
|
||||
errorMessage =
|
||||
"Some Health Connect permissions were not granted. Please grant all permissions to enable syncing."
|
||||
} else {
|
||||
errorMessage = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check Health Connect availability on first load
|
||||
LaunchedEffect(Unit) {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
healthConnectManager.isHealthConnectAvailable().collect { available ->
|
||||
isHealthConnectAvailable = available
|
||||
isLoading = false
|
||||
|
||||
if (!available && isCompatible) {
|
||||
errorMessage = "Health Connect is not available on this device"
|
||||
} else if (!isCompatible) {
|
||||
errorMessage =
|
||||
"Health Connect API compatibility issue. Please update your device or the app."
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
isLoading = false
|
||||
errorMessage = "Error checking Health Connect availability: ${e.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
// Header with icon and title
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.HealthAndSafety,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint =
|
||||
if (isHealthConnectAvailable && isEnabled && hasPermissions) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Health Connect",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Text(
|
||||
text =
|
||||
when {
|
||||
isLoading -> "Checking availability..."
|
||||
!isCompatible -> "API Issue"
|
||||
!isHealthConnectAvailable -> "Not available"
|
||||
isEnabled && hasPermissions -> "Connected"
|
||||
isEnabled && !hasPermissions -> "Needs permissions"
|
||||
else -> "Disabled"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color =
|
||||
when {
|
||||
isLoading ->
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = 0.7f
|
||||
)
|
||||
!isCompatible -> MaterialTheme.colorScheme.error
|
||||
!isHealthConnectAvailable -> MaterialTheme.colorScheme.error
|
||||
isEnabled && hasPermissions ->
|
||||
MaterialTheme.colorScheme.primary
|
||||
isEnabled && !hasPermissions ->
|
||||
MaterialTheme.colorScheme.tertiary
|
||||
else ->
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = 0.7f
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Main toggle switch
|
||||
Switch(
|
||||
checked = isEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
if (enabled && isHealthConnectAvailable) {
|
||||
healthConnectManager.setEnabled(true)
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
val permissionSet =
|
||||
healthConnectManager.getRequiredPermissions()
|
||||
if (permissionSet.isNotEmpty()) {
|
||||
permissionLauncher.launch(permissionSet)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
errorMessage = "Error requesting permissions: ${e.message}"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
healthConnectManager.setEnabled(false)
|
||||
errorMessage = null
|
||||
}
|
||||
},
|
||||
enabled = isHealthConnectAvailable && !isLoading && isCompatible
|
||||
)
|
||||
}
|
||||
|
||||
if (isEnabled) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
if (hasPermissions) {
|
||||
MaterialTheme.colorScheme.primaryContainer.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
}
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector =
|
||||
if (hasPermissions) Icons.Default.CheckCircle
|
||||
else Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
tint =
|
||||
if (hasPermissions) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.error
|
||||
}
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
if (hasPermissions) "Ready to sync"
|
||||
else "Permissions needed",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
if (!hasPermissions) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
"Grant Health Connect permissions to sync your climbing sessions",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = 0.8f
|
||||
)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
val permissionSet =
|
||||
healthConnectManager
|
||||
.getRequiredPermissions()
|
||||
if (permissionSet.isNotEmpty()) {
|
||||
permissionLauncher.launch(permissionSet)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
errorMessage =
|
||||
"Error requesting permissions: ${e.message}"
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) { Text("Grant Permissions") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPermissions) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Auto-sync sessions",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Text(
|
||||
text = "Automatically sync completed climbing sessions",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = 0.7f
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
Switch(
|
||||
checked = autoSyncEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
healthConnectManager.setAutoSyncEnabled(enabled)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text(
|
||||
text =
|
||||
"Sync your climbing sessions to Samsung Health, Google Fit, and other fitness apps through Health Connect.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
|
||||
)
|
||||
}
|
||||
errorMessage?.let { error ->
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.5f
|
||||
)
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isEnabled) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
var testResult by remember { mutableStateOf<String?>(null) }
|
||||
var isTestRunning by remember { mutableStateOf(false) }
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
isTestRunning = true
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
testResult = healthConnectManager.testHealthConnectSync()
|
||||
} catch (e: Exception) {
|
||||
testResult = "Test failed: ${e.message}"
|
||||
} finally {
|
||||
isTestRunning = false
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = !isTestRunning,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
if (isTestRunning) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
}
|
||||
Text(if (isTestRunning) "Testing..." else "Test Connection")
|
||||
}
|
||||
testResult?.let { result ->
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Card(
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.5f
|
||||
)
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(12.dp)) {
|
||||
Text(
|
||||
text = "Debug Results:",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = result,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun HealthConnectStatusBanner(isConnected: Boolean, modifier: Modifier = Modifier) {
|
||||
if (isConnected) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.primaryContainer.copy(
|
||||
alpha = 0.5f
|
||||
)
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CloudDone,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
Text(
|
||||
text = "Health Connect active - sessions will sync automatically",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,870 +0,0 @@
|
||||
package com.atridad.openclimb.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.openclimb.data.model.*
|
||||
import com.atridad.openclimb.ui.components.ImagePicker
|
||||
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
|
||||
import java.time.LocalDateTime
|
||||
import kotlinx.coroutines.flow.first
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack: () -> Unit) {
|
||||
var name by remember { mutableStateOf("") }
|
||||
var location by remember { mutableStateOf("") }
|
||||
var notes by remember { mutableStateOf("") }
|
||||
var selectedClimbTypes by remember { mutableStateOf(setOf<ClimbType>()) }
|
||||
var selectedDifficultySystems by remember { mutableStateOf(setOf<DifficultySystem>()) }
|
||||
|
||||
val isEditing = gymId != null
|
||||
|
||||
// Calculate available difficulty systems based on selected climb types
|
||||
val availableDifficultySystems =
|
||||
if (selectedClimbTypes.isEmpty()) {
|
||||
emptyList()
|
||||
} else {
|
||||
selectedClimbTypes
|
||||
.flatMap { climbType -> DifficultySystem.getSystemsForClimbType(climbType) }
|
||||
.distinct()
|
||||
}
|
||||
|
||||
// Reset selected difficulty systems when available systems change
|
||||
LaunchedEffect(availableDifficultySystems) {
|
||||
selectedDifficultySystems =
|
||||
selectedDifficultySystems.filter { it in availableDifficultySystems }.toSet()
|
||||
}
|
||||
|
||||
// Load existing gym data for editing
|
||||
LaunchedEffect(gymId) {
|
||||
if (gymId != null) {
|
||||
val existingGym = viewModel.getGymById(gymId).first()
|
||||
existingGym?.let { gym ->
|
||||
name = gym.name
|
||||
location = gym.location ?: ""
|
||||
notes = gym.notes ?: ""
|
||||
selectedClimbTypes = gym.supportedClimbTypes.toSet()
|
||||
selectedDifficultySystems = gym.difficultySystems.toSet()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(if (isEditing) "Edit Gym" else "Add Gym") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = "Back"
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
val gym =
|
||||
Gym.create(
|
||||
name,
|
||||
location,
|
||||
selectedClimbTypes.toList(),
|
||||
selectedDifficultySystems.toList(),
|
||||
notes = notes
|
||||
)
|
||||
|
||||
if (isEditing) {
|
||||
viewModel.updateGym(gym.copy(id = gymId!!))
|
||||
} else {
|
||||
viewModel.addGym(gym)
|
||||
}
|
||||
onNavigateBack()
|
||||
},
|
||||
enabled =
|
||||
name.isNotBlank() &&
|
||||
selectedClimbTypes.isNotEmpty() &&
|
||||
selectedDifficultySystems.isNotEmpty()
|
||||
) { Text("Save") }
|
||||
}
|
||||
)
|
||||
}
|
||||
) { paddingValues ->
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
// Name field
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("Gym Name") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
// Location field
|
||||
OutlinedTextField(
|
||||
value = location,
|
||||
onValueChange = { location = it },
|
||||
label = { Text("Location (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
// Climb Types
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Supported Climb Types",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
ClimbType.entries.forEach { climbType ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.selectable(
|
||||
selected = climbType in selectedClimbTypes,
|
||||
onClick = {
|
||||
selectedClimbTypes =
|
||||
if (climbType in
|
||||
selectedClimbTypes
|
||||
) {
|
||||
selectedClimbTypes -
|
||||
climbType
|
||||
} else {
|
||||
selectedClimbTypes +
|
||||
climbType
|
||||
}
|
||||
},
|
||||
role = Role.Checkbox
|
||||
)
|
||||
) {
|
||||
Checkbox(
|
||||
checked = climbType in selectedClimbTypes,
|
||||
onCheckedChange = null
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(climbType.getDisplayName())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Difficulty Systems
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Difficulty Systems",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (selectedClimbTypes.isEmpty()) {
|
||||
Text(
|
||||
text =
|
||||
"Select climb types first to see available difficulty systems",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(vertical = 8.dp)
|
||||
)
|
||||
} else {
|
||||
availableDifficultySystems.forEach { system ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.selectable(
|
||||
selected =
|
||||
system in
|
||||
selectedDifficultySystems,
|
||||
onClick = {
|
||||
selectedDifficultySystems =
|
||||
if (system in
|
||||
selectedDifficultySystems
|
||||
) {
|
||||
selectedDifficultySystems -
|
||||
system
|
||||
} else {
|
||||
selectedDifficultySystems +
|
||||
system
|
||||
}
|
||||
},
|
||||
role = Role.Checkbox
|
||||
)
|
||||
) {
|
||||
Checkbox(
|
||||
checked = system in selectedDifficultySystems,
|
||||
onCheckedChange = null
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(system.getDisplayName())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notes field
|
||||
OutlinedTextField(
|
||||
value = notes,
|
||||
onValueChange = { notes = it },
|
||||
label = { Text("Notes (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 3
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddEditProblemScreen(
|
||||
problemId: String?,
|
||||
gymId: String?,
|
||||
viewModel: ClimbViewModel,
|
||||
onNavigateBack: () -> Unit
|
||||
) {
|
||||
val isEditing = problemId != null
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
val context = LocalContext.current
|
||||
|
||||
// Problem form state
|
||||
var selectedGym by remember {
|
||||
mutableStateOf<Gym?>(gymId?.let { id -> gyms.find { it.id == id } })
|
||||
}
|
||||
var problemName by remember { mutableStateOf("") }
|
||||
var description by remember { mutableStateOf("") }
|
||||
var selectedClimbType by remember { mutableStateOf(ClimbType.BOULDER) }
|
||||
var selectedDifficultySystem by remember { mutableStateOf(DifficultySystem.V_SCALE) }
|
||||
var difficultyGrade by remember { mutableStateOf("") }
|
||||
|
||||
var location by remember { mutableStateOf("") }
|
||||
var tags by remember { mutableStateOf("") }
|
||||
var notes by remember { mutableStateOf("") }
|
||||
var isActive by remember { mutableStateOf(true) }
|
||||
var imagePaths by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||
|
||||
// Load existing problem data for editing
|
||||
LaunchedEffect(problemId) {
|
||||
if (problemId != null) {
|
||||
val existingProblem = viewModel.getProblemById(problemId).first()
|
||||
existingProblem?.let { p ->
|
||||
problemName = p.name ?: ""
|
||||
description = p.description ?: ""
|
||||
selectedClimbType = p.climbType
|
||||
selectedDifficultySystem = p.difficulty.system
|
||||
difficultyGrade = p.difficulty.grade
|
||||
|
||||
location = p.location ?: ""
|
||||
tags = p.tags.joinToString(", ")
|
||||
notes = p.notes ?: ""
|
||||
isActive = p.isActive
|
||||
imagePaths = p.imagePaths
|
||||
selectedGym = gyms.find { it.id == p.gymId }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(gymId, gyms) {
|
||||
if (gymId != null && selectedGym == null) {
|
||||
selectedGym = gyms.find { it.id == gymId }
|
||||
}
|
||||
}
|
||||
|
||||
val availableClimbTypes = selectedGym?.supportedClimbTypes ?: ClimbType.entries.toList()
|
||||
val availableDifficultySystems =
|
||||
DifficultySystem.getSystemsForClimbType(selectedClimbType).filter { system ->
|
||||
selectedGym?.difficultySystems?.contains(system) != false
|
||||
}
|
||||
|
||||
// Auto-select climb type if there's only one available
|
||||
LaunchedEffect(availableClimbTypes) {
|
||||
if (availableClimbTypes.size == 1 && selectedClimbType != availableClimbTypes.first()) {
|
||||
selectedClimbType = availableClimbTypes.first()
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-select or reset difficulty system based on climb type
|
||||
LaunchedEffect(selectedClimbType, availableDifficultySystems) {
|
||||
when {
|
||||
// If current system is not compatible, select the first available one
|
||||
selectedDifficultySystem !in availableDifficultySystems -> {
|
||||
selectedDifficultySystem =
|
||||
availableDifficultySystems.firstOrNull() ?: DifficultySystem.CUSTOM
|
||||
}
|
||||
// If there's only one available system and nothing is selected, auto-select it
|
||||
availableDifficultySystems.size == 1 &&
|
||||
selectedDifficultySystem != availableDifficultySystems.first() -> {
|
||||
selectedDifficultySystem = availableDifficultySystems.first()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset grade when difficulty system changes (unless it's a valid grade for the new system)
|
||||
LaunchedEffect(selectedDifficultySystem) {
|
||||
val availableGrades = selectedDifficultySystem.getAvailableGrades()
|
||||
if (availableGrades.isNotEmpty() && difficultyGrade !in availableGrades) {
|
||||
difficultyGrade = ""
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(if (isEditing) "Edit Problem" else "Add Problem") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = "Back"
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
selectedGym?.let { gym ->
|
||||
val difficulty =
|
||||
DifficultyGrade(
|
||||
system = selectedDifficultySystem,
|
||||
grade = difficultyGrade,
|
||||
numericValue =
|
||||
when (selectedDifficultySystem
|
||||
) {
|
||||
DifficultySystem.V_SCALE ->
|
||||
difficultyGrade
|
||||
.removePrefix(
|
||||
"V"
|
||||
)
|
||||
.toIntOrNull()
|
||||
?: 0
|
||||
else ->
|
||||
difficultyGrade
|
||||
.hashCode() %
|
||||
100 // Simple mapping for other systems
|
||||
}
|
||||
)
|
||||
|
||||
val problem =
|
||||
Problem.create(
|
||||
gymId = gym.id,
|
||||
name = problemName.ifBlank { null },
|
||||
description =
|
||||
description.ifBlank { null },
|
||||
climbType = selectedClimbType,
|
||||
difficulty = difficulty,
|
||||
tags =
|
||||
tags.split(",")
|
||||
.map { it.trim() }
|
||||
.filter {
|
||||
it.isNotBlank()
|
||||
},
|
||||
location = location.ifBlank { null },
|
||||
imagePaths = imagePaths,
|
||||
notes = notes.ifBlank { null }
|
||||
)
|
||||
|
||||
if (isEditing) {
|
||||
viewModel.updateProblem(
|
||||
problem.copy(id = problemId),
|
||||
context
|
||||
)
|
||||
} else {
|
||||
viewModel.addProblem(problem, context)
|
||||
}
|
||||
onNavigateBack()
|
||||
}
|
||||
},
|
||||
enabled = selectedGym != null && difficultyGrade.isNotBlank()
|
||||
) { Text("Save") }
|
||||
}
|
||||
)
|
||||
}
|
||||
) { paddingValues ->
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
// Gym Selection
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Select Gym",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (gyms.isEmpty()) {
|
||||
Text(
|
||||
text = "No gyms available. Add a gym first.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
} else {
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(gyms) { gym ->
|
||||
FilterChip(
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Basic Problem Info
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Problem Details",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = problemName,
|
||||
onValueChange = { problemName = it },
|
||||
label = { Text("Problem Name (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = { Text("e.g., 'The Overhang Monster', 'Yellow V4'") }
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = description,
|
||||
onValueChange = { description = it },
|
||||
label = { Text("Description (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 2,
|
||||
placeholder = { Text("Describe the problem, holds, style, etc.") }
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = location,
|
||||
onValueChange = { location = it },
|
||||
label = { Text("Location (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = { Text("e.g., 'Cave area', 'Wall 3', 'Right side'") }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Climb Type
|
||||
if (selectedGym != null) {
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Climb Type",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
availableClimbTypes.forEach { climbType ->
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = climbType },
|
||||
label = { Text(climbType.getDisplayName()) },
|
||||
selected = selectedClimbType == climbType
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Difficulty
|
||||
if (selectedGym != null) {
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Difficulty",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = "Difficulty System",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(availableDifficultySystems) { system ->
|
||||
FilterChip(
|
||||
onClick = { selectedDifficultySystem = system },
|
||||
label = { Text(system.getDisplayName()) },
|
||||
selected = selectedDifficultySystem == system
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (selectedDifficultySystem == DifficultySystem.CUSTOM) {
|
||||
OutlinedTextField(
|
||||
value = difficultyGrade,
|
||||
onValueChange = { newValue ->
|
||||
// Only allow integers for custom scales
|
||||
if (newValue.isEmpty() || newValue.all { it.isDigit() }
|
||||
) {
|
||||
difficultyGrade = newValue
|
||||
}
|
||||
},
|
||||
label = { Text("Grade *") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = {
|
||||
Text("Enter numeric grade (e.g. 5, 10, 15)")
|
||||
},
|
||||
supportingText = {
|
||||
Text("Custom grades must be whole numbers")
|
||||
},
|
||||
keyboardOptions =
|
||||
KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
} else {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
val availableGrades = selectedDifficultySystem.getAvailableGrades()
|
||||
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = !expanded },
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = difficultyGrade,
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text("Grade *") },
|
||||
trailingIcon = {
|
||||
ExposedDropdownMenuDefaults.TrailingIcon(
|
||||
expanded = expanded
|
||||
)
|
||||
},
|
||||
colors =
|
||||
ExposedDropdownMenuDefaults
|
||||
.outlinedTextFieldColors(),
|
||||
modifier =
|
||||
Modifier.menuAnchor(
|
||||
androidx.compose.material3
|
||||
.MenuAnchorType
|
||||
.PrimaryNotEditable,
|
||||
enabled = true
|
||||
)
|
||||
.fillMaxWidth()
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false }
|
||||
) {
|
||||
availableGrades.forEach { grade ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(grade) },
|
||||
onClick = {
|
||||
difficultyGrade = grade
|
||||
expanded = false
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Images Section
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Photos",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
ImagePicker(
|
||||
imageUris = imagePaths,
|
||||
onImagesChanged = { imagePaths = it },
|
||||
maxImages = 5
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Additional Info",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = tags,
|
||||
onValueChange = { tags = it },
|
||||
label = { Text("Tags (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
placeholder = { Text("e.g., crimpy, dynamic (comma-separated)") }
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = notes,
|
||||
onValueChange = { notes = it },
|
||||
label = { Text("Notes (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 3,
|
||||
placeholder = { Text("Any additional notes about this problem") }
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.selectable(
|
||||
selected = isActive,
|
||||
onClick = { isActive = !isActive },
|
||||
role = Role.Checkbox
|
||||
)
|
||||
) {
|
||||
Checkbox(checked = isActive, onCheckedChange = null)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Problem is currently active",
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddEditSessionScreen(
|
||||
sessionId: String?,
|
||||
gymId: String?,
|
||||
viewModel: ClimbViewModel,
|
||||
onNavigateBack: () -> Unit
|
||||
) {
|
||||
val isEditing = sessionId != null
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
val context = LocalContext.current
|
||||
|
||||
// Session form state
|
||||
var selectedGym by remember {
|
||||
mutableStateOf<Gym?>(gymId?.let { id -> gyms.find { it.id == id } })
|
||||
}
|
||||
var sessionDate by remember { mutableStateOf(LocalDateTime.now().toLocalDate().toString()) }
|
||||
var duration by remember { mutableStateOf("") }
|
||||
var sessionNotes by remember { mutableStateOf("") }
|
||||
|
||||
// Load existing session data for editing
|
||||
LaunchedEffect(sessionId) {
|
||||
if (sessionId != null) {
|
||||
val existingSession = viewModel.getSessionById(sessionId).first()
|
||||
existingSession?.let { session ->
|
||||
selectedGym = gyms.find { it.id == session.gymId }
|
||||
sessionDate = session.date.split("T")[0] // Extract date part
|
||||
duration = session.duration?.toString() ?: ""
|
||||
sessionNotes = session.notes ?: ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(gymId, gyms) {
|
||||
if (gymId != null && selectedGym == null) {
|
||||
selectedGym = gyms.find { it.id == gymId }
|
||||
} else if (gymId == null && selectedGym == null && gyms.size == 1) {
|
||||
// Auto-select the gym if there's only one available
|
||||
selectedGym = gyms.first()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(if (isEditing) "Edit Session" else "Add Session") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = "Back"
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
selectedGym?.let { gym ->
|
||||
if (isEditing) {
|
||||
val session =
|
||||
ClimbSession.create(
|
||||
gymId = gym.id,
|
||||
notes =
|
||||
sessionNotes.ifBlank {
|
||||
null
|
||||
}
|
||||
)
|
||||
viewModel.updateSession(
|
||||
session.copy(id = sessionId!!)
|
||||
)
|
||||
} else {
|
||||
viewModel.startSession(
|
||||
context,
|
||||
gym.id,
|
||||
sessionNotes.ifBlank { null }
|
||||
)
|
||||
}
|
||||
onNavigateBack()
|
||||
}
|
||||
},
|
||||
enabled = selectedGym != null
|
||||
) { Text("Save") }
|
||||
}
|
||||
)
|
||||
}
|
||||
) { paddingValues ->
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
// Gym Selection
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Select Gym",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (gyms.isEmpty()) {
|
||||
Text(
|
||||
text = "No gyms available. Add a gym first.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
} else {
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(gyms) { gym ->
|
||||
FilterChip(
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Session Details
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Session Details",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = sessionDate,
|
||||
onValueChange = { sessionDate = it },
|
||||
label = { Text("Date (YYYY-MM-DD)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = duration,
|
||||
onValueChange = { duration = it },
|
||||
label = { Text("Duration (minutes)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions =
|
||||
KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = sessionNotes,
|
||||
onValueChange = { sessionNotes = it },
|
||||
label = { Text("Session Notes (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 3
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,531 +0,0 @@
|
||||
package com.atridad.openclimb.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.openclimb.R
|
||||
import com.atridad.openclimb.data.model.AttemptResult
|
||||
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
|
||||
|
||||
@Composable
|
||||
fun AnalyticsScreen(viewModel: ClimbViewModel) {
|
||||
val sessions by viewModel.sessions.collectAsState()
|
||||
val problems by viewModel.problems.collectAsState()
|
||||
val attempts by viewModel.attempts.collectAsState()
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
item {
|
||||
Row(
|
||||
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
|
||||
)
|
||||
Text(
|
||||
text = "Analytics",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
}
|
||||
|
||||
// Overall Stats
|
||||
item {
|
||||
OverallStatsCard(
|
||||
totalSessions = sessions.size,
|
||||
totalProblems = problems.size,
|
||||
totalAttempts = attempts.size,
|
||||
totalGyms = gyms.size
|
||||
)
|
||||
}
|
||||
|
||||
// Grade Distribution Chart
|
||||
item {
|
||||
val gradeDistributionData = calculateGradeDistribution(sessions, problems, attempts)
|
||||
GradeDistributionChartCard(gradeDistributionData = gradeDistributionData)
|
||||
}
|
||||
|
||||
// Favorite Gym
|
||||
item {
|
||||
val favoriteGym =
|
||||
sessions.groupBy { it.gymId }.maxByOrNull { it.value.size }?.let {
|
||||
(gymId, sessions) ->
|
||||
gyms.find { it.id == gymId }?.name to sessions.size
|
||||
}
|
||||
|
||||
FavoriteGymCard(
|
||||
gymName = favoriteGym?.first ?: "No sessions yet",
|
||||
sessionCount = favoriteGym?.second ?: 0
|
||||
)
|
||||
}
|
||||
|
||||
// Recent Activity
|
||||
item {
|
||||
val recentSessions = sessions.take(5)
|
||||
RecentActivityCard(recentSessions = recentSessions.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun OverallStatsCard(totalSessions: Int, totalProblems: Int, totalAttempts: Int, totalGyms: Int) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Overall Stats",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceEvenly
|
||||
) {
|
||||
StatItem(label = "Sessions", value = totalSessions.toString())
|
||||
StatItem(label = "Problems", value = totalProblems.toString())
|
||||
StatItem(label = "Attempts", value = totalAttempts.toString())
|
||||
StatItem(label = "Gyms", value = totalGyms.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionDataPoint>) {
|
||||
// Find all grading systems that have been used in the data
|
||||
val usedSystems =
|
||||
remember(gradeDistributionData) {
|
||||
gradeDistributionData.map { it.difficultySystem }.distinct()
|
||||
}
|
||||
|
||||
var selectedSystem by
|
||||
remember(usedSystems) {
|
||||
mutableStateOf(usedSystems.firstOrNull() ?: DifficultySystem.V_SCALE)
|
||||
}
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var showAllTime by remember { mutableStateOf(true) }
|
||||
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Grade Distribution",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Toggles section
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
// Time period toggle
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// All Time button
|
||||
FilterChip(
|
||||
onClick = { showAllTime = true },
|
||||
label = {
|
||||
Text("All Time", style = MaterialTheme.typography.bodySmall)
|
||||
},
|
||||
selected = showAllTime,
|
||||
colors =
|
||||
FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor =
|
||||
MaterialTheme.colorScheme.primary,
|
||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
)
|
||||
|
||||
// 7 Days button
|
||||
FilterChip(
|
||||
onClick = { showAllTime = false },
|
||||
label = { Text("7 Days", style = MaterialTheme.typography.bodySmall) },
|
||||
selected = !showAllTime,
|
||||
colors =
|
||||
FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor =
|
||||
MaterialTheme.colorScheme.primary,
|
||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// Scale selector dropdown
|
||||
if (usedSystems.size > 1) {
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = !expanded }
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value =
|
||||
when (selectedSystem) {
|
||||
DifficultySystem.V_SCALE -> "V-Scale"
|
||||
DifficultySystem.FONT -> "Font"
|
||||
DifficultySystem.YDS -> "YDS"
|
||||
DifficultySystem.CUSTOM -> "Custom"
|
||||
},
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
trailingIcon = {
|
||||
ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
|
||||
},
|
||||
modifier =
|
||||
Modifier.menuAnchor(
|
||||
type = ExposedDropdownMenuAnchorType.PrimaryNotEditable,
|
||||
enabled = true
|
||||
)
|
||||
.width(120.dp),
|
||||
textStyle = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false }
|
||||
) {
|
||||
usedSystems.forEach { system ->
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
when (system) {
|
||||
DifficultySystem.V_SCALE -> "V-Scale"
|
||||
DifficultySystem.FONT -> "Font"
|
||||
DifficultySystem.YDS -> "YDS"
|
||||
DifficultySystem.CUSTOM -> "Custom"
|
||||
}
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
selectedSystem = system
|
||||
expanded = false
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Filter grade distribution data by selected scale and time period
|
||||
val filteredGradeData =
|
||||
remember(gradeDistributionData, selectedSystem, showAllTime) {
|
||||
val systemFiltered =
|
||||
gradeDistributionData.filter {
|
||||
it.difficultySystem == selectedSystem
|
||||
}
|
||||
|
||||
if (showAllTime) {
|
||||
systemFiltered
|
||||
} else {
|
||||
// Filter for last 7 days
|
||||
val sevenDaysAgo = LocalDateTime.now().minusDays(7)
|
||||
systemFiltered.filter { dataPoint ->
|
||||
try {
|
||||
val attemptDate =
|
||||
LocalDateTime.parse(
|
||||
dataPoint.date,
|
||||
DateTimeFormatter.ISO_LOCAL_DATE_TIME
|
||||
)
|
||||
attemptDate.isAfter(sevenDaysAgo)
|
||||
} catch (_: Exception) {
|
||||
// If date parsing fails, include the data point
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filteredGradeData.isNotEmpty()) {
|
||||
// Group by grade and sum counts
|
||||
val gradeGroups =
|
||||
filteredGradeData
|
||||
.groupBy { it.grade }
|
||||
.mapValues { (_, dataPoints) -> dataPoints.sumOf { it.count } }
|
||||
.map { (grade, count) ->
|
||||
val firstDataPoint =
|
||||
filteredGradeData.first { it.grade == grade }
|
||||
BarChartDataPoint(
|
||||
label = grade,
|
||||
value = count,
|
||||
gradeNumeric = firstDataPoint.gradeNumeric
|
||||
)
|
||||
}
|
||||
|
||||
BarChart(data = gradeGroups, modifier = Modifier.fillMaxWidth().height(220.dp))
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
"Successful climbs by ${when(selectedSystem) {
|
||||
DifficultySystem.V_SCALE -> "V-grade"
|
||||
DifficultySystem.FONT -> "Font grade"
|
||||
DifficultySystem.YDS -> "YDS grade"
|
||||
DifficultySystem.CUSTOM -> "custom grade"
|
||||
}}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().height(220.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "No data",
|
||||
modifier = Modifier.size(48.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = "No data available.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Text(
|
||||
text =
|
||||
if (showAllTime)
|
||||
"Complete some climbs to see your grade distribution!"
|
||||
else "No climbs in the last 7 days",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FavoriteGymCard(gymName: String, sessionCount: Int) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Favorite Gym",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
if (sessionCount > 0) {
|
||||
Text(
|
||||
text = "$sessionCount sessions",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RecentActivityCard(recentSessions: Int) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Recent Activity",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text =
|
||||
if (recentSessions > 0) {
|
||||
"You've had $recentSessions recent sessions"
|
||||
} else {
|
||||
"No recent activity"
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class GradeDistributionDataPoint(
|
||||
val date: String,
|
||||
val grade: String,
|
||||
val gradeNumeric: Int,
|
||||
val count: Int,
|
||||
val climbType: ClimbType,
|
||||
val difficultySystem: DifficultySystem
|
||||
)
|
||||
|
||||
fun calculateGradeDistribution(
|
||||
sessions: List<com.atridad.openclimb.data.model.ClimbSession>,
|
||||
problems: List<com.atridad.openclimb.data.model.Problem>,
|
||||
attempts: List<com.atridad.openclimb.data.model.Attempt>
|
||||
): List<GradeDistributionDataPoint> {
|
||||
if (sessions.isEmpty() || problems.isEmpty() || attempts.isEmpty()) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
// Get all successful attempts
|
||||
val successfulAttempts =
|
||||
attempts.filter {
|
||||
it.result == AttemptResult.SUCCESS || it.result == AttemptResult.FLASH
|
||||
}
|
||||
|
||||
if (successfulAttempts.isEmpty()) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
// Map attempts to problems and create grade distribution data
|
||||
val gradeDistribution = mutableMapOf<String, GradeDistributionDataPoint>()
|
||||
|
||||
successfulAttempts.forEach { attempt ->
|
||||
val problem = problems.find { it.id == attempt.problemId }
|
||||
val session = sessions.find { it.id == attempt.sessionId }
|
||||
|
||||
if (problem != null && session != null) {
|
||||
val key = "${problem.difficulty.system.name}-${problem.difficulty.grade}"
|
||||
|
||||
val existing = gradeDistribution[key]
|
||||
if (existing != null) {
|
||||
gradeDistribution[key] = existing.copy(count = existing.count + 1)
|
||||
} else {
|
||||
gradeDistribution[key] =
|
||||
GradeDistributionDataPoint(
|
||||
date = attempt.timestamp,
|
||||
grade = problem.difficulty.grade,
|
||||
gradeNumeric =
|
||||
gradeToNumeric(
|
||||
problem.difficulty.system,
|
||||
problem.difficulty.grade
|
||||
),
|
||||
count = 1,
|
||||
climbType = problem.climbType,
|
||||
difficultySystem = problem.difficulty.system
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return gradeDistribution.values.toList()
|
||||
}
|
||||
|
||||
fun gradeToNumeric(system: DifficultySystem, grade: String): Int {
|
||||
return when (system) {
|
||||
DifficultySystem.V_SCALE -> {
|
||||
when (grade) {
|
||||
"VB" -> 0
|
||||
else -> grade.removePrefix("V").toIntOrNull() ?: 0
|
||||
}
|
||||
}
|
||||
DifficultySystem.FONT -> {
|
||||
when (grade) {
|
||||
"3" -> 3
|
||||
"4A" -> 4
|
||||
"4B" -> 5
|
||||
"4C" -> 6
|
||||
"5A" -> 7
|
||||
"5B" -> 8
|
||||
"5C" -> 9
|
||||
"6A" -> 10
|
||||
"6A+" -> 11
|
||||
"6B" -> 12
|
||||
"6B+" -> 13
|
||||
"6C" -> 14
|
||||
"6C+" -> 15
|
||||
"7A" -> 16
|
||||
"7A+" -> 17
|
||||
"7B" -> 18
|
||||
"7B+" -> 19
|
||||
"7C" -> 20
|
||||
"7C+" -> 21
|
||||
"8A" -> 22
|
||||
"8A+" -> 23
|
||||
"8B" -> 24
|
||||
"8B+" -> 25
|
||||
"8C" -> 26
|
||||
"8C+" -> 27
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
DifficultySystem.YDS -> {
|
||||
when (grade) {
|
||||
"5.0" -> 50
|
||||
"5.1" -> 51
|
||||
"5.2" -> 52
|
||||
"5.3" -> 53
|
||||
"5.4" -> 54
|
||||
"5.5" -> 55
|
||||
"5.6" -> 56
|
||||
"5.7" -> 57
|
||||
"5.8" -> 58
|
||||
"5.9" -> 59
|
||||
"5.10a" -> 60
|
||||
"5.10b" -> 61
|
||||
"5.10c" -> 62
|
||||
"5.10d" -> 63
|
||||
"5.11a" -> 64
|
||||
"5.11b" -> 65
|
||||
"5.11c" -> 66
|
||||
"5.11d" -> 67
|
||||
"5.12a" -> 68
|
||||
"5.12b" -> 69
|
||||
"5.12c" -> 70
|
||||
"5.12d" -> 71
|
||||
"5.13a" -> 72
|
||||
"5.13b" -> 73
|
||||
"5.13c" -> 74
|
||||
"5.13d" -> 75
|
||||
"5.14a" -> 76
|
||||
"5.14b" -> 77
|
||||
"5.14c" -> 78
|
||||
"5.14d" -> 79
|
||||
"5.15a" -> 80
|
||||
"5.15b" -> 81
|
||||
"5.15c" -> 82
|
||||
"5.15d" -> 83
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
DifficultySystem.CUSTOM -> {
|
||||
// Custom grades are numeric strings, so parse them directly
|
||||
grade.toIntOrNull() ?: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,332 +0,0 @@
|
||||
package com.atridad.openclimb.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.openclimb.R
|
||||
import com.atridad.openclimb.data.model.Attempt
|
||||
import com.atridad.openclimb.data.model.AttemptResult
|
||||
import com.atridad.openclimb.data.model.ClimbType
|
||||
import com.atridad.openclimb.data.model.Gym
|
||||
import com.atridad.openclimb.data.model.Problem
|
||||
import com.atridad.openclimb.ui.components.SyncIndicator
|
||||
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String) -> Unit) {
|
||||
val problems by viewModel.problems.collectAsState()
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
val attempts by viewModel.attempts.collectAsState()
|
||||
val context = LocalContext.current
|
||||
|
||||
// Filter state
|
||||
var selectedClimbType by remember { mutableStateOf<ClimbType?>(null) }
|
||||
var selectedGym by remember { mutableStateOf<Gym?>(null) }
|
||||
|
||||
// Apply filters
|
||||
val filteredProblems =
|
||||
problems.filter { problem ->
|
||||
val climbTypeMatch = selectedClimbType?.let { it == problem.climbType } != false
|
||||
val gymMatch = selectedGym?.let { it.id == problem.gymId } != false
|
||||
climbTypeMatch && gymMatch
|
||||
}
|
||||
|
||||
// Separate active and inactive problems
|
||||
val activeProblems = filteredProblems.filter { it.isActive }
|
||||
val inactiveProblems = filteredProblems.filter { !it.isActive }
|
||||
val sortedProblems = activeProblems + inactiveProblems
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
|
||||
Row(
|
||||
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
|
||||
)
|
||||
Text(
|
||||
text = "Climbing Problems",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Filters Section
|
||||
if (problems.isNotEmpty()) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Filters",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Climb Type Filter
|
||||
Text(
|
||||
text = "Climb Type",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
item {
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = null },
|
||||
label = { Text("All Types") },
|
||||
selected = selectedClimbType == null
|
||||
)
|
||||
}
|
||||
items(ClimbType.entries) { climbType ->
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = climbType },
|
||||
label = { Text(climbType.getDisplayName()) },
|
||||
selected = selectedClimbType == climbType
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Gym Filter
|
||||
Text(
|
||||
text = "Gym",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
item {
|
||||
FilterChip(
|
||||
onClick = { selectedGym = null },
|
||||
label = { Text("All Gyms") },
|
||||
selected = selectedGym == null
|
||||
)
|
||||
}
|
||||
items(gyms) { gym ->
|
||||
FilterChip(
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Filter result count
|
||||
if (selectedClimbType != null || selectedGym != null) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
text =
|
||||
"Showing ${filteredProblems.size} of ${problems.size} problems (${activeProblems.size} active, ${inactiveProblems.size} reset)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
|
||||
if (filteredProblems.isEmpty()) {
|
||||
EmptyStateMessage(
|
||||
title =
|
||||
if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty()) "No Gyms Available" else "No Problems Yet"
|
||||
} else {
|
||||
"No Problems Match Filters"
|
||||
},
|
||||
message =
|
||||
if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty())
|
||||
"Add a gym first to start tracking problems and routes!"
|
||||
else "Start tracking your favorite problems and routes!"
|
||||
} else {
|
||||
"Try adjusting your filters to see more problems."
|
||||
},
|
||||
onActionClick = {},
|
||||
actionText = ""
|
||||
)
|
||||
} else {
|
||||
LazyColumn {
|
||||
items(sortedProblems) { problem ->
|
||||
ProblemCard(
|
||||
problem = problem,
|
||||
gymName = gyms.find { it.id == problem.gymId }?.name ?: "Unknown Gym",
|
||||
attempts = attempts,
|
||||
onClick = { onNavigateToProblemDetail(problem.id) },
|
||||
onToggleActive = {
|
||||
val updatedProblem = problem.copy(isActive = !problem.isActive)
|
||||
viewModel.updateProblem(updatedProblem, context)
|
||||
}
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ProblemCard(
|
||||
problem: Problem,
|
||||
gymName: String,
|
||||
attempts: List<Attempt>,
|
||||
onClick: () -> Unit,
|
||||
onToggleActive: (() -> Unit)? = null
|
||||
) {
|
||||
val isCompleted =
|
||||
attempts.any { attempt ->
|
||||
attempt.problemId == problem.id &&
|
||||
(attempt.result == AttemptResult.SUCCESS ||
|
||||
attempt.result == AttemptResult.FLASH)
|
||||
}
|
||||
|
||||
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.Top
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = problem.name ?: "Unnamed Problem",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color =
|
||||
if (problem.isActive) MaterialTheme.colorScheme.onSurface
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
|
||||
)
|
||||
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = if (problem.isActive) 1f else 0.6f
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
if (problem.imagePaths.isNotEmpty()) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Image,
|
||||
contentDescription = "Has images",
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
|
||||
if (isCompleted) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CheckCircle,
|
||||
contentDescription = "Completed",
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.tertiary
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = problem.difficulty.grade,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = problem.climbType.getDisplayName(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
problem.location?.let { location ->
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Location: $location",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
if (problem.tags.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Row {
|
||||
problem.tags.take(3).forEach { tag ->
|
||||
AssistChip(
|
||||
onClick = {},
|
||||
label = { Text(tag) },
|
||||
modifier = Modifier.padding(end = 4.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!problem.isActive) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "Reset / No Longer Set",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.tertiary,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
}
|
||||
|
||||
// Toggle active button
|
||||
if (onToggleActive != null) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
OutlinedButton(
|
||||
onClick = onToggleActive,
|
||||
colors =
|
||||
ButtonDefaults.outlinedButtonColors(
|
||||
contentColor =
|
||||
if (problem.isActive)
|
||||
MaterialTheme.colorScheme.tertiary
|
||||
else MaterialTheme.colorScheme.primary
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text(
|
||||
text = if (problem.isActive) "Mark as Reset" else "Mark as Active",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
package com.atridad.openclimb.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
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) {
|
||||
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)) {
|
||||
Row(
|
||||
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
|
||||
)
|
||||
Text(
|
||||
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) } }
|
||||
)
|
||||
|
||||
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 = ""
|
||||
)
|
||||
} else {
|
||||
LazyColumn {
|
||||
items(completedSessions) { session ->
|
||||
SessionCard(
|
||||
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)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
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
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmptyStateMessage(
|
||||
title: String,
|
||||
message: String,
|
||||
onActionClick: () -> Unit,
|
||||
actionText: String
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Text(
|
||||
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
|
||||
)
|
||||
|
||||
if (actionText.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Button(onClick = onActionClick) { Text(actionText) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatDate(dateString: String): String {
|
||||
return try {
|
||||
val date = LocalDateTime.parse(dateString.split("T")[0] + "T00:00:00")
|
||||
date.format(DateTimeFormatter.ofPattern("MMM dd, yyyy"))
|
||||
} catch (_: Exception) {
|
||||
dateString
|
||||
}
|
||||
}
|
||||
@@ -1,996 +0,0 @@
|
||||
package com.atridad.openclimb.ui.screens
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.atridad.openclimb.R
|
||||
import com.atridad.openclimb.ui.components.SyncIndicator
|
||||
import com.atridad.openclimb.ui.health.HealthConnectCard
|
||||
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(viewModel: ClimbViewModel) {
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
val context = LocalContext.current
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
|
||||
// Sync service state
|
||||
val syncService = viewModel.syncService
|
||||
val isSyncing by syncService.isSyncing.collectAsState()
|
||||
val isConnected by syncService.isConnected.collectAsState()
|
||||
val isConfigured by syncService.isConfiguredFlow.collectAsState()
|
||||
val isTesting by syncService.isTesting.collectAsState()
|
||||
val lastSyncTime by syncService.lastSyncTime.collectAsState()
|
||||
val syncError by syncService.syncError.collectAsState()
|
||||
val isAutoSyncEnabled by syncService.isAutoSyncEnabled.collectAsState()
|
||||
|
||||
// State for dialogs
|
||||
var showResetDialog by remember { mutableStateOf(false) }
|
||||
var showSyncConfigDialog by remember { mutableStateOf(false) }
|
||||
var showDisconnectDialog by remember { mutableStateOf(false) }
|
||||
|
||||
var showDeleteImagesDialog by remember { mutableStateOf(false) }
|
||||
|
||||
var isDeletingImages by remember { mutableStateOf(false) }
|
||||
|
||||
// Sync configuration state
|
||||
var serverUrl by remember { mutableStateOf(syncService.serverURL) }
|
||||
var authToken by remember { mutableStateOf(syncService.authToken) }
|
||||
|
||||
val packageInfo = remember { context.packageManager.getPackageInfo(context.packageName, 0) }
|
||||
val appVersion = packageInfo.versionName
|
||||
|
||||
// Update local state when sync service configuration changes
|
||||
LaunchedEffect(syncService.serverURL, syncService.authToken) {
|
||||
serverUrl = syncService.serverURL
|
||||
authToken = syncService.authToken
|
||||
}
|
||||
|
||||
// File picker launcher for import - only accepts ZIP files
|
||||
val importLauncher =
|
||||
rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri
|
||||
->
|
||||
uri?.let {
|
||||
try {
|
||||
val inputStream = context.contentResolver.openInputStream(uri)
|
||||
// Determine file extension from content resolver
|
||||
val fileName =
|
||||
context.contentResolver.query(uri, null, null, null, null)?.use {
|
||||
cursor ->
|
||||
val nameIndex =
|
||||
cursor.getColumnIndex(
|
||||
android.provider.OpenableColumns.DISPLAY_NAME
|
||||
)
|
||||
if (nameIndex >= 0 && cursor.moveToFirst()) {
|
||||
cursor.getString(nameIndex)
|
||||
} else null
|
||||
}
|
||||
?: "import_file"
|
||||
|
||||
// Only allow ZIP files
|
||||
if (!fileName.lowercase().endsWith(".zip")) {
|
||||
viewModel.setError(
|
||||
"Only ZIP files are supported for import. Please use a ZIP file exported from OpenClimb."
|
||||
)
|
||||
return@let
|
||||
}
|
||||
|
||||
val tempFile = File(context.cacheDir, "temp_import.zip")
|
||||
|
||||
inputStream?.use { input ->
|
||||
tempFile.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
viewModel.importData(tempFile)
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError("Failed to read file: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// File picker launcher for export - ZIP format with images
|
||||
val exportZipLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("application/zip")
|
||||
) { uri ->
|
||||
uri?.let {
|
||||
try {
|
||||
viewModel.exportDataToZipUri(context, uri)
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError("Failed to save file: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
item {
|
||||
Row(
|
||||
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
|
||||
)
|
||||
Text(
|
||||
text = "Settings",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||
}
|
||||
}
|
||||
|
||||
// Sync Section
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Sync",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
if (isConfigured) {
|
||||
// Connected state
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
if (isConnected)
|
||||
MaterialTheme.colorScheme
|
||||
.primaryContainer.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
else
|
||||
MaterialTheme.colorScheme
|
||||
.surfaceVariant.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = {
|
||||
Text(
|
||||
if (isConnected) "Connected to Server"
|
||||
else "Server Configured"
|
||||
)
|
||||
},
|
||||
supportingContent = {
|
||||
Column {
|
||||
Text("Server: ${syncService.serverURL}")
|
||||
lastSyncTime?.let { time ->
|
||||
Text(
|
||||
"Last sync: ${
|
||||
try {
|
||||
Instant.parse(time).toString()
|
||||
} catch (_: Exception) {
|
||||
time
|
||||
}
|
||||
}",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (isConnected) Icons.Default.CloudDone
|
||||
else Icons.Default.Cloud,
|
||||
contentDescription = null,
|
||||
tint =
|
||||
if (isConnected)
|
||||
MaterialTheme.colorScheme.primary
|
||||
else
|
||||
MaterialTheme.colorScheme
|
||||
.onSurfaceVariant
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// Manual Sync Button
|
||||
TextButton(
|
||||
onClick = {
|
||||
coroutineScope.launch {
|
||||
viewModel.performManualSync()
|
||||
}
|
||||
},
|
||||
enabled = isConnected && !isSyncing
|
||||
) {
|
||||
if (isSyncing) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Text("Sync")
|
||||
}
|
||||
}
|
||||
|
||||
// Configure Button
|
||||
TextButton(onClick = { showSyncConfigDialog = true }) {
|
||||
Text("Configure")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
// Auto-sync settings
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant
|
||||
.copy(alpha = 0.3f)
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Sync Mode",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("Auto-sync")
|
||||
Text(
|
||||
text =
|
||||
"Sync automatically on app launch and data changes",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurface.copy(
|
||||
alpha = 0.7f
|
||||
),
|
||||
maxLines = 2
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
Switch(
|
||||
checked = isAutoSyncEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
syncService.setAutoSyncEnabled(enabled)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
// Disconnect option
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer
|
||||
.copy(alpha = 0.3f)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Disconnect") },
|
||||
supportingContent = { Text("Clear sync configuration") },
|
||||
leadingContent = {
|
||||
Icon(
|
||||
Icons.Default.CloudOff,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(onClick = { showDisconnectDialog = true }) {
|
||||
Text(
|
||||
"Disconnect",
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Not configured state
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant
|
||||
.copy(alpha = 0.3f)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Setup Sync") },
|
||||
supportingContent = {
|
||||
Text("Connect to your OpenClimb sync server")
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.CloudSync, contentDescription = null)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(onClick = { showSyncConfigDialog = true }) {
|
||||
Text("Setup")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Show sync error if any
|
||||
syncError?.let { error ->
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item { HealthConnectCard() }
|
||||
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "Data Management",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
// Export Data
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Export Data with Images") },
|
||||
supportingContent = {
|
||||
Text(
|
||||
"Export all your climbing data and images to ZIP file (recommended)"
|
||||
)
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.Share, contentDescription = null)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
val defaultFileName =
|
||||
"openclimb_export_${
|
||||
java.time.LocalDateTime.now()
|
||||
.toString()
|
||||
.replace(":", "-")
|
||||
.replace(".", "-")
|
||||
}.zip"
|
||||
exportZipLauncher.launch(defaultFileName)
|
||||
},
|
||||
enabled = !uiState.isLoading
|
||||
) {
|
||||
if (uiState.isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Text("Export ZIP")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Import Data") },
|
||||
supportingContent = {
|
||||
Text("Import climbing data from ZIP file (recommended format)")
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.Add, contentDescription = null)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = { importLauncher.launch("application/zip") },
|
||||
enabled = !uiState.isLoading
|
||||
) {
|
||||
if (uiState.isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Text("Import")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Delete All Images") },
|
||||
supportingContent = {
|
||||
Text("Permanently delete all image files from device")
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(
|
||||
Icons.Default.Delete,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = { showDeleteImagesDialog = true },
|
||||
enabled = !isDeletingImages && !uiState.isLoading
|
||||
) {
|
||||
if (isDeletingImages) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Text("Delete", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.errorContainer.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Reset All Data") },
|
||||
supportingContent = {
|
||||
Text(
|
||||
"Permanently delete all gyms, problems, sessions, attempts, and images"
|
||||
)
|
||||
},
|
||||
leadingContent = {
|
||||
Icon(
|
||||
Icons.Default.Delete,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
TextButton(
|
||||
onClick = { showResetDialog = true },
|
||||
enabled = !uiState.isLoading
|
||||
) {
|
||||
if (uiState.isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Text("Reset", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// App Information Section
|
||||
item {
|
||||
Card(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Text(
|
||||
text = "App Information",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Icon(
|
||||
painter =
|
||||
painterResource(
|
||||
id = R.drawable.ic_mountains
|
||||
),
|
||||
contentDescription = "OpenClimb Logo",
|
||||
modifier = Modifier.size(24.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Text("OpenClimb")
|
||||
}
|
||||
},
|
||||
supportingContent = { Text("Track your climbing progress") },
|
||||
leadingContent = {}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Card(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||
alpha = 0.3f
|
||||
)
|
||||
)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text("Version") },
|
||||
supportingContent = { Text(appVersion ?: "Unknown") },
|
||||
leadingContent = {
|
||||
Icon(Icons.Default.Info, contentDescription = null)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show loading/message states
|
||||
if (uiState.isLoading) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset confirmation dialog
|
||||
if (showResetDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showResetDialog = false },
|
||||
title = { Text("Reset All Data") },
|
||||
text = {
|
||||
Column {
|
||||
Text("Are you sure you want to reset all data?")
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "This will permanently delete:",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text =
|
||||
"• All gyms and their information\n• All problems and their images\n• All climbing sessions\n• All attempts and progress data",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text =
|
||||
"This action cannot be undone. Consider exporting your data first.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.resetAllData()
|
||||
showResetDialog = false
|
||||
}
|
||||
) { Text("Reset All Data", color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showResetDialog = false }) { Text("Cancel") }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Sync Configuration Dialog
|
||||
if (showSyncConfigDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showSyncConfigDialog = false },
|
||||
title = { Text("Sync Configuration") },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = serverUrl,
|
||||
onValueChange = { serverUrl = it },
|
||||
label = { Text("Server URL") },
|
||||
placeholder = { Text("https://your-server.com") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = authToken,
|
||||
onValueChange = { authToken = it },
|
||||
label = { Text("Auth Token") },
|
||||
placeholder = { Text("your-secret-token") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Connection status indicator
|
||||
if (isTesting) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Testing connection...",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
} else if (isConnected && isConfigured) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.CheckCircle,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Connection successful",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
} else if (syncError != null && isConfigured) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Error,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Connection failed: $syncError",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
} else if (isConfigured) {
|
||||
Text(
|
||||
text = "Test connection before enabling sync features",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = "Enter your server URL and auth token to enable sync",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Row {
|
||||
// Primary action: Save & Test
|
||||
Button(
|
||||
onClick = {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
syncService.serverURL = serverUrl.trim()
|
||||
syncService.authToken = authToken.trim()
|
||||
viewModel.testSyncConnection()
|
||||
while (syncService.isTesting.value) {
|
||||
kotlinx.coroutines.delay(100)
|
||||
}
|
||||
showSyncConfigDialog = false
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError(
|
||||
"Failed to save and test: ${e.message}"
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled =
|
||||
!isTesting &&
|
||||
serverUrl.isNotBlank() &&
|
||||
authToken.isNotBlank()
|
||||
) {
|
||||
if (isTesting) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Save & Test")
|
||||
}
|
||||
} else {
|
||||
Text("Save & Test")
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
// Secondary action: Test only (when already configured)
|
||||
if (isConfigured) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
syncService.serverURL = serverUrl.trim()
|
||||
syncService.authToken = authToken.trim()
|
||||
viewModel.testSyncConnection()
|
||||
while (syncService.isTesting.value) {
|
||||
kotlinx.coroutines.delay(100)
|
||||
}
|
||||
if (isConnected) {
|
||||
showSyncConfigDialog = false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
viewModel.setError(
|
||||
"Connection test failed: ${e.message}"
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled =
|
||||
!isTesting &&
|
||||
serverUrl.isNotBlank() &&
|
||||
authToken.isNotBlank()
|
||||
) { Text("Test Only") }
|
||||
}
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
serverUrl = syncService.serverURL
|
||||
authToken = syncService.authToken
|
||||
showSyncConfigDialog = false
|
||||
}
|
||||
) { Text("Cancel") }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Disconnect Dialog
|
||||
if (showDisconnectDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showDisconnectDialog = false },
|
||||
title = { Text("Disconnect from Sync") },
|
||||
text = {
|
||||
Text(
|
||||
"Are you sure you want to disconnect from the sync server? This will clear your server configuration and disable auto-sync."
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.syncService.clearConfiguration()
|
||||
showDisconnectDialog = false
|
||||
}
|
||||
) { Text("Disconnect") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDisconnectDialog = false }) { Text("Cancel") }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Delete All Images dialog
|
||||
if (showDeleteImagesDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showDeleteImagesDialog = false },
|
||||
title = { Text("Delete All Images") },
|
||||
text = {
|
||||
Text(
|
||||
"This will permanently delete ALL image files from your device.\n\nProblems will keep their references but the actual image files will be removed. This cannot be undone.\n\nConsider exporting your data first if you want to keep your images."
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
isDeletingImages = true
|
||||
showDeleteImagesDialog = false
|
||||
coroutineScope.launch {
|
||||
viewModel.deleteAllImages(context)
|
||||
isDeletingImages = false
|
||||
viewModel.setMessage("All images deleted successfully!")
|
||||
}
|
||||
}
|
||||
) { Text("Delete", color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDeleteImagesDialog = false }) { Text("Cancel") }
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,609 +0,0 @@
|
||||
package com.atridad.openclimb.ui.viewmodel
|
||||
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.atridad.openclimb.data.health.HealthConnectManager
|
||||
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.ImageNamingUtils
|
||||
import com.atridad.openclimb.utils.ImageUtils
|
||||
import com.atridad.openclimb.utils.SessionShareUtils
|
||||
import com.atridad.openclimb.widget.ClimbStatsWidgetProvider
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class ClimbViewModel(
|
||||
private val repository: ClimbRepository,
|
||||
val syncService: SyncService,
|
||||
private val context: Context
|
||||
) : ViewModel() {
|
||||
|
||||
// Health Connect manager
|
||||
private val healthConnectManager = HealthConnectManager(context)
|
||||
|
||||
// UI State flows
|
||||
private val _uiState = MutableStateFlow(ClimbUiState())
|
||||
val uiState: StateFlow<ClimbUiState> = _uiState.asStateFlow()
|
||||
|
||||
// Data flows
|
||||
val gyms =
|
||||
repository
|
||||
.getAllGyms()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
val problems =
|
||||
repository
|
||||
.getAllProblems()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
val sessions =
|
||||
repository
|
||||
.getAllSessions()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
val activeSession =
|
||||
repository
|
||||
.getActiveSessionFlow()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = null
|
||||
)
|
||||
|
||||
val attempts =
|
||||
repository
|
||||
.getAllAttempts()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
// Gym operations
|
||||
fun addGym(gym: Gym) {
|
||||
viewModelScope.launch { repository.insertGym(gym) }
|
||||
}
|
||||
|
||||
fun addGym(gym: Gym, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.insertGym(gym)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun updateGym(gym: Gym) {
|
||||
viewModelScope.launch { repository.updateGym(gym) }
|
||||
}
|
||||
|
||||
fun updateGym(gym: Gym, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.updateGym(gym)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteGym(gym: Gym) {
|
||||
viewModelScope.launch { repository.deleteGym(gym) }
|
||||
}
|
||||
|
||||
fun deleteGym(gym: Gym, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.deleteGym(gym)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun getGymById(id: String): Flow<Gym?> = flow { emit(repository.getGymById(id)) }
|
||||
|
||||
// Problem operations
|
||||
fun addProblem(problem: Problem, context: Context) {
|
||||
viewModelScope.launch {
|
||||
val finalProblem = renameTemporaryImages(problem, context)
|
||||
repository.insertProblem(finalProblem)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
// Auto-sync now happens automatically via repository callback
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun renameTemporaryImages(problem: Problem, context: Context? = null): Problem {
|
||||
if (problem.imagePaths.isEmpty()) {
|
||||
return problem
|
||||
}
|
||||
|
||||
val appContext = context ?: return problem
|
||||
val finalImagePaths = mutableListOf<String>()
|
||||
|
||||
problem.imagePaths.forEachIndexed { index, tempPath ->
|
||||
if (tempPath.startsWith("temp_")) {
|
||||
val deterministicName = ImageNamingUtils.generateImageFilename(problem.id, index)
|
||||
val finalPath =
|
||||
ImageUtils.renameTemporaryImage(appContext, tempPath, problem.id, index)
|
||||
finalImagePaths.add(finalPath ?: tempPath)
|
||||
} else {
|
||||
finalImagePaths.add(tempPath)
|
||||
}
|
||||
}
|
||||
|
||||
return problem.copy(imagePaths = finalImagePaths)
|
||||
}
|
||||
|
||||
fun updateProblem(problem: Problem, context: Context) {
|
||||
viewModelScope.launch {
|
||||
val finalProblem = renameTemporaryImages(problem, context)
|
||||
repository.updateProblem(finalProblem)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteProblem(problem: Problem, context: Context) {
|
||||
viewModelScope.launch {
|
||||
// Delete associated images
|
||||
problem.imagePaths.forEach { imagePath -> ImageUtils.deleteImage(context, imagePath) }
|
||||
|
||||
repository.deleteProblem(problem)
|
||||
|
||||
cleanupOrphanedImages(context)
|
||||
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun cleanupOrphanedImages(context: Context) {
|
||||
val allProblems = repository.getAllProblems().first()
|
||||
val referencedImagePaths = allProblems.flatMap { it.imagePaths }.toSet()
|
||||
ImageUtils.cleanupOrphanedImages(context, referencedImagePaths)
|
||||
}
|
||||
|
||||
fun deleteAllImages(context: Context) {
|
||||
viewModelScope.launch {
|
||||
val imagesDir = ImageUtils.getImagesDirectory(context)
|
||||
var deletedCount = 0
|
||||
|
||||
imagesDir.listFiles()?.forEach { file ->
|
||||
if (file.isFile && file.extension.lowercase() == "jpg") {
|
||||
if (file.delete()) {
|
||||
deletedCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val allProblems = repository.getAllProblems().first()
|
||||
val updatedProblems =
|
||||
allProblems.map { problem ->
|
||||
if (problem.imagePaths.isNotEmpty()) {
|
||||
problem.copy(imagePaths = emptyList())
|
||||
} else {
|
||||
problem
|
||||
}
|
||||
}
|
||||
|
||||
for (updatedProblem in updatedProblems) {
|
||||
if (updatedProblem.imagePaths !=
|
||||
allProblems.find { it.id == updatedProblem.id }?.imagePaths
|
||||
) {
|
||||
repository.insertProblemWithoutSync(updatedProblem)
|
||||
}
|
||||
}
|
||||
|
||||
println("Deleted $deletedCount image files and cleared image references")
|
||||
}
|
||||
}
|
||||
|
||||
fun getProblemById(id: String): Flow<Problem?> = flow { emit(repository.getProblemById(id)) }
|
||||
|
||||
fun getProblemsByGym(gymId: String): Flow<List<Problem>> = repository.getProblemsByGym(gymId)
|
||||
|
||||
// Session operations
|
||||
fun addSession(session: ClimbSession) {
|
||||
viewModelScope.launch { repository.insertSession(session) }
|
||||
}
|
||||
|
||||
fun addSession(session: ClimbSession, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.insertSession(session)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun updateSession(session: ClimbSession) {
|
||||
viewModelScope.launch { repository.updateSession(session) }
|
||||
}
|
||||
|
||||
fun updateSession(session: ClimbSession, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.updateSession(session)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteSession(session: ClimbSession) {
|
||||
viewModelScope.launch { repository.deleteSession(session) }
|
||||
}
|
||||
|
||||
fun deleteSession(session: ClimbSession, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.deleteSession(session)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun getSessionById(id: String): Flow<ClimbSession?> = flow {
|
||||
emit(repository.getSessionById(id))
|
||||
}
|
||||
|
||||
fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>> =
|
||||
repository.getSessionsByGym(gymId)
|
||||
|
||||
// Get last used gym for shortcut functionality
|
||||
suspend fun getLastUsedGym(): Gym? = repository.getLastUsedGym()
|
||||
|
||||
// Active session management
|
||||
fun startSession(context: Context, gymId: String, notes: String? = null) {
|
||||
viewModelScope.launch {
|
||||
android.util.Log.d("ClimbViewModel", "startSession called with gymId: $gymId")
|
||||
|
||||
if (!com.atridad.openclimb.utils.NotificationPermissionUtils
|
||||
.isNotificationPermissionGranted(context)
|
||||
) {
|
||||
android.util.Log.d("ClimbViewModel", "Notification permission not granted")
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error =
|
||||
"Notification permission is required to track your climbing session. Please enable notifications in settings."
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val existingActive = repository.getActiveSession()
|
||||
if (existingActive != null) {
|
||||
android.util.Log.d(
|
||||
"ClimbViewModel",
|
||||
"Active session already exists: ${existingActive.id}"
|
||||
)
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error = "There's already an active session. Please end it first."
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
android.util.Log.d("ClimbViewModel", "Creating new session")
|
||||
val newSession = ClimbSession.create(gymId = gymId, notes = notes)
|
||||
repository.insertSession(newSession)
|
||||
|
||||
android.util.Log.d(
|
||||
"ClimbViewModel",
|
||||
"Starting tracking service for session: ${newSession.id}"
|
||||
)
|
||||
// Start the tracking service
|
||||
val serviceIntent = SessionTrackingService.createStartIntent(context, newSession.id)
|
||||
context.startForegroundService(serviceIntent)
|
||||
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
|
||||
_uiState.value = _uiState.value.copy(message = "Session started successfully!")
|
||||
}
|
||||
}
|
||||
|
||||
fun endSession(context: Context, sessionId: String) {
|
||||
viewModelScope.launch {
|
||||
if (!com.atridad.openclimb.utils.NotificationPermissionUtils
|
||||
.isNotificationPermissionGranted(context)
|
||||
) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error =
|
||||
"Notification permission is required to manage your climbing session. Please enable notifications in settings."
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val session = repository.getSessionById(sessionId)
|
||||
if (session != null && session.status == SessionStatus.ACTIVE) {
|
||||
val completedSession = with(ClimbSession) { session.complete() }
|
||||
repository.updateSession(completedSession)
|
||||
|
||||
val serviceIntent = SessionTrackingService.createStopIntent(context, sessionId)
|
||||
context.startService(serviceIntent)
|
||||
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
|
||||
syncToHealthConnect(completedSession)
|
||||
|
||||
_uiState.value = _uiState.value.copy(message = "Session completed!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun ensureSessionTrackingServiceRunning(context: Context) {
|
||||
viewModelScope.launch {
|
||||
val activeSession = repository.getActiveSession()
|
||||
if (activeSession != null && activeSession.status == SessionStatus.ACTIVE) {
|
||||
val serviceIntent =
|
||||
SessionTrackingService.createStartIntent(context, activeSession.id)
|
||||
context.startForegroundService(serviceIntent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attempt operations
|
||||
fun addAttempt(attempt: Attempt) {
|
||||
viewModelScope.launch { repository.insertAttempt(attempt) }
|
||||
}
|
||||
|
||||
fun addAttempt(attempt: Attempt, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.insertAttempt(attempt)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAttempt(attempt: Attempt) {
|
||||
viewModelScope.launch { repository.deleteAttempt(attempt) }
|
||||
}
|
||||
|
||||
fun deleteAttempt(attempt: Attempt, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.deleteAttempt(attempt)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun updateAttempt(attempt: Attempt) {
|
||||
viewModelScope.launch { repository.updateAttempt(attempt) }
|
||||
}
|
||||
|
||||
fun updateAttempt(attempt: Attempt, context: Context) {
|
||||
viewModelScope.launch {
|
||||
repository.updateAttempt(attempt)
|
||||
ClimbStatsWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
|
||||
fun getAttemptsBySession(sessionId: String): Flow<List<Attempt>> =
|
||||
repository.getAttemptsBySession(sessionId)
|
||||
|
||||
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>> =
|
||||
repository.getAttemptsByProblem(problemId)
|
||||
|
||||
fun exportDataToZipUri(context: Context, uri: android.net.Uri) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = true,
|
||||
message = "Creating ZIP file with images..."
|
||||
)
|
||||
repository.exportAllDataToZipUri(context, uri)
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
message =
|
||||
"Export complete! Your climbing data and images have been saved."
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
error = "Export failed: ${e.message}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun importData(file: File) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
|
||||
if (!file.name.lowercase().endsWith(".zip")) {
|
||||
throw Exception(
|
||||
"Only ZIP files are supported for import. Please use a ZIP file exported from OpenClimb."
|
||||
)
|
||||
}
|
||||
|
||||
repository.importDataFromZip(file)
|
||||
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
message = "Data imported successfully from ${file.name}"
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
error = "Import failed: ${e.message}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UI state operations
|
||||
fun clearMessage() {
|
||||
_uiState.value = _uiState.value.copy(message = null)
|
||||
}
|
||||
|
||||
fun clearError() {
|
||||
_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)
|
||||
}
|
||||
|
||||
fun setMessage(message: String) {
|
||||
_uiState.value = _uiState.value.copy(message = message)
|
||||
}
|
||||
|
||||
fun resetAllData() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
|
||||
repository.resetAllData()
|
||||
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
message = "All data has been reset successfully"
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(isLoading = false, error = "Reset failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun syncToHealthConnect(session: ClimbSession) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val gym = repository.getGymById(session.gymId)
|
||||
val gymName = gym?.name ?: "Unknown Gym"
|
||||
|
||||
val attempts = repository.getAttemptsBySession(session.id).first()
|
||||
val attemptCount = attempts.size
|
||||
|
||||
val result = healthConnectManager.autoSyncSession(session, gymName, attemptCount)
|
||||
|
||||
result
|
||||
.onSuccess {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
message =
|
||||
"Session synced to Health Connect successfully!"
|
||||
)
|
||||
}
|
||||
.onFailure { error ->
|
||||
if (healthConnectManager.isReadySync()) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error =
|
||||
"Failed to sync to Health Connect: ${error.message}"
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (healthConnectManager.isReadySync()) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(error = "Health Connect sync error: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun manualSyncToHealthConnect(sessionId: String) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val session = repository.getSessionById(sessionId)
|
||||
if (session == null) {
|
||||
_uiState.value = _uiState.value.copy(error = "Session not found")
|
||||
return@launch
|
||||
}
|
||||
|
||||
if (session.status != SessionStatus.COMPLETED) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(error = "Only completed sessions can be synced")
|
||||
return@launch
|
||||
}
|
||||
|
||||
val gym = repository.getGymById(session.gymId)
|
||||
val gymName = gym?.name ?: "Unknown Gym"
|
||||
val attempts = repository.getAttemptsBySession(session.id).first()
|
||||
val attemptCount = attempts.size
|
||||
|
||||
val result =
|
||||
healthConnectManager.syncClimbingSession(session, gymName, attemptCount)
|
||||
|
||||
result
|
||||
.onSuccess {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
message =
|
||||
"Session synced to Health Connect successfully!"
|
||||
)
|
||||
}
|
||||
.onFailure { error ->
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error =
|
||||
"Failed to sync to Health Connect: ${error.message}"
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(error = "Health Connect sync error: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getHealthConnectManager(): HealthConnectManager = healthConnectManager
|
||||
|
||||
// Share operations
|
||||
suspend fun generateSessionShareCard(context: Context, sessionId: String): File? =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val session = repository.getSessionById(sessionId) ?: return@withContext null
|
||||
val attempts = repository.getAttemptsBySession(sessionId).first()
|
||||
val problems =
|
||||
repository.getAllProblems().first().filter { problem ->
|
||||
attempts.any { it.problemId == problem.id }
|
||||
}
|
||||
val gym = repository.getGymById(session.gymId) ?: return@withContext null
|
||||
|
||||
val stats = SessionShareUtils.calculateSessionStats(session, attempts, problems)
|
||||
SessionShareUtils.generateShareCard(context, session, gym, stats)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
error = "Failed to generate share card: ${e.message}"
|
||||
)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun shareSessionCard(context: Context, imageFile: File) {
|
||||
SessionShareUtils.shareSessionCard(context, imageFile)
|
||||
}
|
||||
}
|
||||
|
||||
data class ClimbUiState(
|
||||
val isLoading: Boolean = false,
|
||||
val message: String? = null,
|
||||
val error: String? = null
|
||||
)
|
||||
@@ -1,46 +0,0 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
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, imageIndex: Int): String {
|
||||
val input = "${problemId}_${imageIndex}"
|
||||
val hash = createHash(input)
|
||||
|
||||
return "problem_${hash}_${imageIndex}${IMAGE_EXTENSION}"
|
||||
}
|
||||
|
||||
/** Legacy method for backward compatibility */
|
||||
fun generateImageFilename(problemId: String, timestamp: String, imageIndex: Int): String {
|
||||
return generateImageFilename(problemId, 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
|
||||
}
|
||||
|
||||
return parts[1]
|
||||
}
|
||||
|
||||
/** 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 (isValidImageFilename(oldFilename)) {
|
||||
return oldFilename
|
||||
}
|
||||
|
||||
return generateImageFilename(problemId, 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 = generateImageFilename(problemId, index)
|
||||
if (newFilename != oldFilename) {
|
||||
renameMap[oldFilename] = newFilename
|
||||
}
|
||||
}
|
||||
|
||||
return renameMap
|
||||
}
|
||||
|
||||
/** Generates the canonical filename for a problem image */
|
||||
fun getCanonicalImageFilename(problemId: String, imageIndex: Int): String {
|
||||
return generateImageFilename(problemId, imageIndex)
|
||||
}
|
||||
|
||||
/** Creates a mapping of existing server filenames to canonical filenames */
|
||||
fun createServerMigrationMap(
|
||||
problemId: String,
|
||||
serverImageFilenames: List<String>,
|
||||
localImageCount: Int
|
||||
): Map<String, String> {
|
||||
val migrationMap = mutableMapOf<String, String>()
|
||||
|
||||
for (imageIndex in 0 until localImageCount) {
|
||||
val canonicalName = getCanonicalImageFilename(problemId, imageIndex)
|
||||
|
||||
if (serverImageFilenames.contains(canonicalName)) {
|
||||
continue
|
||||
}
|
||||
|
||||
for (serverFilename in serverImageFilenames) {
|
||||
if (isValidImageFilename(serverFilename) &&
|
||||
!migrationMap.values.contains(serverFilename)
|
||||
) {
|
||||
migrationMap[serverFilename] = canonicalName
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return migrationMap
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user