Compare commits
24 Commits
ANDROID_2.
...
ANDROID_2.
| Author | SHA1 | Date | |
|---|---|---|---|
|
aa6ee4ecd4
|
|||
|
c0d9702e54
|
|||
|
0cc576bb12
|
|||
|
abb76e454b
|
|||
|
8154cd24bb
|
|||
| 06bfb02ccc | |||
| f82560bb1d | |||
|
a6508da413
|
|||
|
50b30442e8
|
|||
|
b365b967b2
|
|||
|
cacd178817
|
|||
|
922412c2c2
|
|||
|
acb1b1f532
|
|||
|
c8694eacab
|
|||
|
57855b8332
|
|||
|
6342bfed5c
|
|||
| 869ca0fc0d | |||
| 33562e9d16 | |||
|
a212f3f3b5
|
|||
|
a99196b9ca
|
|||
|
93fb7a41fb
|
|||
|
6d67ae6d81
|
|||
| 071e47f95e | |||
| c6c3e6084b |
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
|
||||||
77
.gitattributes
vendored
Normal file
77
.gitattributes
vendored
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
# 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
|
||||||
46
.gitignore
vendored
46
.gitignore
vendored
@@ -9,6 +9,11 @@ local.properties
|
|||||||
# Log/OS Files
|
# Log/OS Files
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.DS_Store?
|
||||||
|
._*
|
||||||
|
.Spotlight-V100
|
||||||
|
.Trashes
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
# Android Studio generated files and folders
|
# Android Studio generated files and folders
|
||||||
captures/
|
captures/
|
||||||
@@ -34,3 +39,44 @@ google-services.json
|
|||||||
|
|
||||||
# Android Profiling
|
# Android Profiling
|
||||||
*.hprof
|
*.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
|
||||||
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
|
||||||
@@ -6,6 +6,8 @@ plugins {
|
|||||||
alias(libs.plugins.kotlin.compose)
|
alias(libs.plugins.kotlin.compose)
|
||||||
alias(libs.plugins.kotlin.serialization)
|
alias(libs.plugins.kotlin.serialization)
|
||||||
alias(libs.plugins.ksp)
|
alias(libs.plugins.ksp)
|
||||||
|
alias(libs.plugins.detekt)
|
||||||
|
alias(libs.plugins.spotless)
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
@@ -16,8 +18,8 @@ android {
|
|||||||
applicationId = "com.atridad.ascently"
|
applicationId = "com.atridad.ascently"
|
||||||
minSdk = 31
|
minSdk = 31
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 46
|
versionCode = 49
|
||||||
versionName = "2.2.1"
|
versionName = "2.4.1"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
@@ -27,7 +29,7 @@ android {
|
|||||||
isMinifyEnabled = true
|
isMinifyEnabled = true
|
||||||
proguardFiles(
|
proguardFiles(
|
||||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
"proguard-rules.pro"
|
"proguard-rules.pro",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,7 +40,10 @@ android {
|
|||||||
|
|
||||||
java { toolchain { languageVersion.set(JavaLanguageVersion.of(17)) } }
|
java { toolchain { languageVersion.set(JavaLanguageVersion.of(17)) } }
|
||||||
|
|
||||||
buildFeatures { compose = true }
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
buildConfig = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } }
|
kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } }
|
||||||
@@ -80,7 +85,7 @@ dependencies {
|
|||||||
implementation(libs.coil.compose)
|
implementation(libs.coil.compose)
|
||||||
|
|
||||||
// Health Connect
|
// Health Connect
|
||||||
implementation("androidx.health.connect:connect-client:1.1.0-alpha07")
|
implementation(libs.health.connect)
|
||||||
|
|
||||||
// Testing
|
// Testing
|
||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
@@ -96,6 +101,51 @@ dependencies {
|
|||||||
androidTestImplementation(libs.androidx.ui.test.junit4)
|
androidTestImplementation(libs.androidx.ui.test.junit4)
|
||||||
debugImplementation(libs.androidx.ui.tooling)
|
debugImplementation(libs.androidx.ui.tooling)
|
||||||
debugImplementation(libs.androidx.ui.test.manifest)
|
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",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
60
android/app/proguard-rules.pro
vendored
60
android/app/proguard-rules.pro
vendored
@@ -5,17 +5,61 @@
|
|||||||
# For more details, see
|
# For more details, see
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
# 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
|
# If your project uses WebView with JS, uncomment the following
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
# and specify the fully qualified class name to the JavaScript interface
|
||||||
# class:
|
# class:
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||||
# public *;
|
# 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 -->
|
<!-- Permissions for notifications and foreground service -->
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<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" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
AscentlyApp(
|
AscentlyApp(
|
||||||
shortcutAction = shortcutAction,
|
shortcutAction = shortcutAction,
|
||||||
lastUsedGymId = lastUsedGymId,
|
lastUsedGymId = lastUsedGymId,
|
||||||
onShortcutActionProcessed = { clearShortcutAction() }
|
onShortcutActionProcessed = { clearShortcutAction() },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,5 +76,4 @@ class Converters {
|
|||||||
fun toSessionStatus(value: String): SessionStatus {
|
fun toSessionStatus(value: String): SessionStatus {
|
||||||
return SessionStatus.valueOf(value)
|
return SessionStatus.valueOf(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import com.atridad.ascently.data.model.*
|
|||||||
@Database(
|
@Database(
|
||||||
entities = [Gym::class, Problem::class, ClimbSession::class, Attempt::class],
|
entities = [Gym::class, Problem::class, ClimbSession::class, Attempt::class],
|
||||||
version = 6,
|
version = 6,
|
||||||
exportSchema = false
|
exportSchema = false,
|
||||||
)
|
)
|
||||||
@TypeConverters(Converters::class)
|
@TypeConverters(Converters::class)
|
||||||
abstract class AscentlyDatabase : RoomDatabase() {
|
abstract class AscentlyDatabase : RoomDatabase() {
|
||||||
@@ -46,15 +46,15 @@ abstract class AscentlyDatabase : RoomDatabase() {
|
|||||||
}
|
}
|
||||||
if (!existingColumns.contains("status")) {
|
if (!existingColumns.contains("status")) {
|
||||||
db.execSQL(
|
db.execSQL(
|
||||||
"ALTER TABLE climb_sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'COMPLETED'"
|
"ALTER TABLE climb_sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'COMPLETED'",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
db.execSQL(
|
db.execSQL(
|
||||||
"UPDATE climb_sessions SET startTime = createdAt WHERE startTime IS NULL"
|
"UPDATE climb_sessions SET startTime = createdAt WHERE startTime IS NULL",
|
||||||
)
|
)
|
||||||
db.execSQL(
|
db.execSQL(
|
||||||
"UPDATE climb_sessions SET status = 'COMPLETED' WHERE status IS NULL OR status = ''"
|
"UPDATE climb_sessions SET status = 'COMPLETED' WHERE status IS NULL OR status = ''",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,11 +74,11 @@ abstract class AscentlyDatabase : RoomDatabase() {
|
|||||||
|
|
||||||
if (!existingColumns.contains("updatedAt")) {
|
if (!existingColumns.contains("updatedAt")) {
|
||||||
db.execSQL(
|
db.execSQL(
|
||||||
"ALTER TABLE attempts ADD COLUMN updatedAt TEXT NOT NULL DEFAULT ''"
|
"ALTER TABLE attempts ADD COLUMN updatedAt TEXT NOT NULL DEFAULT ''",
|
||||||
)
|
)
|
||||||
// Set updatedAt to createdAt for existing records
|
// Set updatedAt to createdAt for existing records
|
||||||
db.execSQL(
|
db.execSQL(
|
||||||
"UPDATE attempts SET updatedAt = createdAt WHERE updatedAt = ''"
|
"UPDATE attempts SET updatedAt = createdAt WHERE updatedAt = ''",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,7 +91,7 @@ abstract class AscentlyDatabase : RoomDatabase() {
|
|||||||
Room.databaseBuilder(
|
Room.databaseBuilder(
|
||||||
context.applicationContext,
|
context.applicationContext,
|
||||||
AscentlyDatabase::class.java,
|
AscentlyDatabase::class.java,
|
||||||
"ascently_database"
|
"ascently_database",
|
||||||
)
|
)
|
||||||
.addMigrations(MIGRATION_4_5, MIGRATION_5_6)
|
.addMigrations(MIGRATION_4_5, MIGRATION_5_6)
|
||||||
.enableMultiInstanceInvalidation()
|
.enableMultiInstanceInvalidation()
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ interface ProblemDao {
|
|||||||
@Query("SELECT * FROM problems ORDER BY updatedAt DESC")
|
@Query("SELECT * FROM problems ORDER BY updatedAt DESC")
|
||||||
fun getAllProblems(): Flow<List<Problem>>
|
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")
|
@Query("SELECT * FROM problems WHERE gymId = :gymId ORDER BY updatedAt DESC")
|
||||||
fun getProblemsByGym(gymId: String): Flow<List<Problem>>
|
fun getProblemsByGym(gymId: String): Flow<List<Problem>>
|
||||||
@@ -20,7 +21,7 @@ interface ProblemDao {
|
|||||||
fun getProblemsByClimbType(climbType: ClimbType): Flow<List<Problem>>
|
fun getProblemsByClimbType(climbType: ClimbType): Flow<List<Problem>>
|
||||||
|
|
||||||
@Query(
|
@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>>
|
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")
|
@Query("SELECT * FROM problems WHERE gymId = :gymId AND isActive = 1 ORDER BY updatedAt DESC")
|
||||||
fun getActiveProblemsByGym(gymId: String): Flow<List<Problem>>
|
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)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun insertProblems(problems: List<Problem>)
|
suspend fun insertProblems(problems: List<Problem>)
|
||||||
@@ -39,7 +41,8 @@ interface ProblemDao {
|
|||||||
|
|
||||||
@Delete suspend fun deleteProblem(problem: Problem)
|
@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")
|
@Query("SELECT COUNT(*) FROM problems WHERE gymId = :gymId")
|
||||||
suspend fun getProblemsCountByGym(gymId: String): Int
|
suspend fun getProblemsCountByGym(gymId: String): Int
|
||||||
@@ -54,11 +57,13 @@ interface ProblemDao {
|
|||||||
OR description LIKE '%' || :searchQuery || '%'
|
OR description LIKE '%' || :searchQuery || '%'
|
||||||
OR location LIKE '%' || :searchQuery || '%')
|
OR location LIKE '%' || :searchQuery || '%')
|
||||||
ORDER BY updatedAt DESC
|
ORDER BY updatedAt DESC
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
fun searchProblems(searchQuery: String): Flow<List<Problem>>
|
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()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,14 +13,14 @@ data class ClimbDataBackup(
|
|||||||
val problems: List<BackupProblem>,
|
val problems: List<BackupProblem>,
|
||||||
val sessions: List<BackupClimbSession>,
|
val sessions: List<BackupClimbSession>,
|
||||||
val attempts: List<BackupAttempt>,
|
val attempts: List<BackupAttempt>,
|
||||||
val deletedItems: List<DeletedItem> = emptyList()
|
val deletedItems: List<DeletedItem> = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class DeletedItem(
|
data class DeletedItem(
|
||||||
val id: String,
|
val id: String,
|
||||||
val type: String, // "gym", "problem", "session", "attempt"
|
val type: String, // "gym", "problem", "session", "attempt"
|
||||||
val deletedAt: String
|
val deletedAt: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Platform-neutral gym representation for backup/restore
|
// Platform-neutral gym representation for backup/restore
|
||||||
@@ -35,7 +35,7 @@ data class BackupGym(
|
|||||||
val customDifficultyGrades: List<String>? = null,
|
val customDifficultyGrades: List<String>? = null,
|
||||||
val notes: String? = null,
|
val notes: String? = null,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String
|
val updatedAt: String,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun fromGym(gym: Gym): BackupGym {
|
fun fromGym(gym: Gym): BackupGym {
|
||||||
@@ -48,7 +48,7 @@ data class BackupGym(
|
|||||||
customDifficultyGrades = gym.customDifficultyGrades.ifEmpty { null },
|
customDifficultyGrades = gym.customDifficultyGrades.ifEmpty { null },
|
||||||
notes = gym.notes,
|
notes = gym.notes,
|
||||||
createdAt = gym.createdAt,
|
createdAt = gym.createdAt,
|
||||||
updatedAt = gym.updatedAt
|
updatedAt = gym.updatedAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -63,7 +63,7 @@ data class BackupGym(
|
|||||||
customDifficultyGrades = customDifficultyGrades ?: emptyList(),
|
customDifficultyGrades = customDifficultyGrades ?: emptyList(),
|
||||||
notes = notes,
|
notes = notes,
|
||||||
createdAt = createdAt,
|
createdAt = createdAt,
|
||||||
updatedAt = updatedAt
|
updatedAt = updatedAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -84,7 +84,7 @@ data class BackupProblem(
|
|||||||
val dateSet: String? = null,
|
val dateSet: String? = null,
|
||||||
val notes: String? = null,
|
val notes: String? = null,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String
|
val updatedAt: String,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun fromProblem(problem: Problem): BackupProblem {
|
fun fromProblem(problem: Problem): BackupProblem {
|
||||||
@@ -98,13 +98,16 @@ data class BackupProblem(
|
|||||||
tags = problem.tags,
|
tags = problem.tags,
|
||||||
location = problem.location,
|
location = problem.location,
|
||||||
imagePaths =
|
imagePaths =
|
||||||
if (problem.imagePaths.isEmpty()) null
|
if (problem.imagePaths.isEmpty()) {
|
||||||
else problem.imagePaths.map { path -> path.substringAfterLast('/') },
|
null
|
||||||
|
} else {
|
||||||
|
problem.imagePaths.map { path -> path.substringAfterLast('/') }
|
||||||
|
},
|
||||||
isActive = problem.isActive,
|
isActive = problem.isActive,
|
||||||
dateSet = problem.dateSet,
|
dateSet = problem.dateSet,
|
||||||
notes = problem.notes,
|
notes = problem.notes,
|
||||||
createdAt = problem.createdAt,
|
createdAt = problem.createdAt,
|
||||||
updatedAt = problem.updatedAt
|
updatedAt = problem.updatedAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,7 +127,7 @@ data class BackupProblem(
|
|||||||
dateSet = dateSet,
|
dateSet = dateSet,
|
||||||
notes = notes,
|
notes = notes,
|
||||||
createdAt = createdAt,
|
createdAt = createdAt,
|
||||||
updatedAt = updatedAt
|
updatedAt = updatedAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,7 +148,7 @@ data class BackupClimbSession(
|
|||||||
val status: SessionStatus,
|
val status: SessionStatus,
|
||||||
val notes: String? = null,
|
val notes: String? = null,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String
|
val updatedAt: String,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun fromClimbSession(session: ClimbSession): BackupClimbSession {
|
fun fromClimbSession(session: ClimbSession): BackupClimbSession {
|
||||||
@@ -159,7 +162,7 @@ data class BackupClimbSession(
|
|||||||
status = session.status,
|
status = session.status,
|
||||||
notes = session.notes,
|
notes = session.notes,
|
||||||
createdAt = session.createdAt,
|
createdAt = session.createdAt,
|
||||||
updatedAt = session.updatedAt
|
updatedAt = session.updatedAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -175,7 +178,7 @@ data class BackupClimbSession(
|
|||||||
status = status,
|
status = status,
|
||||||
notes = notes,
|
notes = notes,
|
||||||
createdAt = createdAt,
|
createdAt = createdAt,
|
||||||
updatedAt = updatedAt
|
updatedAt = updatedAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,7 +196,7 @@ data class BackupAttempt(
|
|||||||
val restTime: Long? = null,
|
val restTime: Long? = null,
|
||||||
val timestamp: String,
|
val timestamp: String,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String? = null
|
val updatedAt: String? = null,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun fromAttempt(attempt: Attempt): BackupAttempt {
|
fun fromAttempt(attempt: Attempt): BackupAttempt {
|
||||||
@@ -208,7 +211,7 @@ data class BackupAttempt(
|
|||||||
restTime = attempt.restTime,
|
restTime = attempt.restTime,
|
||||||
timestamp = attempt.timestamp,
|
timestamp = attempt.timestamp,
|
||||||
createdAt = attempt.createdAt,
|
createdAt = attempt.createdAt,
|
||||||
updatedAt = attempt.updatedAt
|
updatedAt = attempt.updatedAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -225,7 +228,7 @@ data class BackupAttempt(
|
|||||||
restTime = restTime,
|
restTime = restTime,
|
||||||
timestamp = timestamp,
|
timestamp = timestamp,
|
||||||
createdAt = createdAt,
|
createdAt = createdAt,
|
||||||
updatedAt = updatedAt ?: createdAt
|
updatedAt = updatedAt ?: createdAt,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package com.atridad.ascently.data.health
|
|||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import android.util.Log
|
|
||||||
import androidx.activity.result.contract.ActivityResultContract
|
import androidx.activity.result.contract.ActivityResultContract
|
||||||
import androidx.health.connect.client.HealthConnectClient
|
import androidx.health.connect.client.HealthConnectClient
|
||||||
import androidx.health.connect.client.PermissionController
|
import androidx.health.connect.client.PermissionController
|
||||||
@@ -14,14 +13,15 @@ import androidx.health.connect.client.records.TotalCaloriesBurnedRecord
|
|||||||
import androidx.health.connect.client.units.Energy
|
import androidx.health.connect.client.units.Energy
|
||||||
import com.atridad.ascently.data.model.ClimbSession
|
import com.atridad.ascently.data.model.ClimbSession
|
||||||
import com.atridad.ascently.data.model.SessionStatus
|
import com.atridad.ascently.data.model.SessionStatus
|
||||||
|
import com.atridad.ascently.utils.AppLogger
|
||||||
import com.atridad.ascently.utils.DateFormatUtils
|
import com.atridad.ascently.utils.DateFormatUtils
|
||||||
import java.time.Duration
|
|
||||||
import java.time.Instant
|
|
||||||
import java.time.ZoneOffset
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.flow
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import java.time.Duration
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.ZoneOffset
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Health Connect manager for Ascently that syncs climbing sessions to Samsung Health, Google Fit,
|
* Health Connect manager for Ascently that syncs climbing sessions to Samsung Health, Google Fit,
|
||||||
@@ -52,7 +52,7 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
HealthPermission.getReadPermission(HeartRateRecord::class),
|
HealthPermission.getReadPermission(HeartRateRecord::class),
|
||||||
HealthPermission.getWritePermission(HeartRateRecord::class),
|
HealthPermission.getWritePermission(HeartRateRecord::class),
|
||||||
HealthPermission.getReadPermission(TotalCaloriesBurnedRecord::class),
|
HealthPermission.getReadPermission(TotalCaloriesBurnedRecord::class),
|
||||||
HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class)
|
HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
try {
|
try {
|
||||||
HealthConnectClient.getOrCreate(context)
|
HealthConnectClient.getOrCreate(context)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Failed to create Health Connect client", e)
|
AppLogger.e(TAG, e) { "Failed to create Health Connect client" }
|
||||||
_isCompatible.value = false
|
_isCompatible.value = false
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
@@ -75,7 +75,7 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
val status = HealthConnectClient.getSdkStatus(context)
|
val status = HealthConnectClient.getSdkStatus(context)
|
||||||
emit(status == HealthConnectClient.SDK_AVAILABLE)
|
emit(status == HealthConnectClient.SDK_AVAILABLE)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Error checking Health Connect availability", e)
|
AppLogger.e(TAG, e) { "Error checking Health Connect availability" }
|
||||||
_isCompatible.value = false
|
_isCompatible.value = false
|
||||||
emit(false)
|
emit(false)
|
||||||
}
|
}
|
||||||
@@ -90,10 +90,10 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
try {
|
try {
|
||||||
val alreadyHasPermissions = hasAllPermissions()
|
val alreadyHasPermissions = hasAllPermissions()
|
||||||
if (!alreadyHasPermissions) {
|
if (!alreadyHasPermissions) {
|
||||||
Log.d(TAG, "Health Connect enabled - permissions will be requested by UI")
|
AppLogger.d(TAG) { "Health Connect enabled - permissions will be requested by UI" }
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "Error checking permissions when enabling Health Connect", e)
|
AppLogger.w(TAG, e) { "Error checking permissions when enabling Health Connect" }
|
||||||
}
|
}
|
||||||
} else if (!enabled) {
|
} else if (!enabled) {
|
||||||
setPermissionsGranted(false)
|
setPermissionsGranted(false)
|
||||||
@@ -119,7 +119,7 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
setPermissionsGranted(hasAll)
|
setPermissionsGranted(hasAll)
|
||||||
hasAll
|
hasAll
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Error checking permissions", e)
|
AppLogger.e(TAG, e) { "Error checking permissions" }
|
||||||
setPermissionsGranted(false)
|
setPermissionsGranted(false)
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
@@ -127,15 +127,16 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
|
|
||||||
suspend fun isReady(): Boolean {
|
suspend fun isReady(): Boolean {
|
||||||
return try {
|
return try {
|
||||||
if (!_isEnabled.value || !_isCompatible.value || healthConnectClient == null)
|
if (!_isEnabled.value || !_isCompatible.value || healthConnectClient == null) {
|
||||||
return false
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
val isAvailable =
|
val isAvailable =
|
||||||
HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE
|
HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE
|
||||||
val hasPerms = if (isAvailable) hasAllPermissions() else false
|
val hasPerms = if (isAvailable) hasAllPermissions() else false
|
||||||
isAvailable && hasPerms
|
isAvailable && hasPerms
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Error checking Health Connect readiness", e)
|
AppLogger.e(TAG, e) { "Error checking Health Connect readiness" }
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -148,7 +149,7 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
return try {
|
return try {
|
||||||
REQUIRED_PERMISSIONS.map { it }.toSet()
|
REQUIRED_PERMISSIONS.map { it }.toSet()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Error getting required permissions", e)
|
AppLogger.e(TAG, e) { "Error getting required permissions" }
|
||||||
emptySet()
|
emptySet()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -157,18 +158,18 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
suspend fun syncCompletedSession(
|
suspend fun syncCompletedSession(
|
||||||
session: ClimbSession,
|
session: ClimbSession,
|
||||||
gymName: String,
|
gymName: String,
|
||||||
attemptCount: Int = 0
|
attemptCount: Int = 0,
|
||||||
): Result<Unit> {
|
): Result<Unit> {
|
||||||
return try {
|
return try {
|
||||||
if (!isReady() || !_autoSync.value) {
|
if (!isReady() || !_autoSync.value) {
|
||||||
return Result.failure(
|
return Result.failure(
|
||||||
IllegalStateException("Health Connect not ready or auto-sync disabled")
|
IllegalStateException("Health Connect not ready or auto-sync disabled"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session.status != SessionStatus.COMPLETED) {
|
if (session.status != SessionStatus.COMPLETED) {
|
||||||
return Result.failure(
|
return Result.failure(
|
||||||
IllegalArgumentException("Only completed sessions can be synced")
|
IllegalArgumentException("Only completed sessions can be synced"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,11 +178,11 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
|
|
||||||
if (startTime == null || endTime == null) {
|
if (startTime == null || endTime == null) {
|
||||||
return Result.failure(
|
return Result.failure(
|
||||||
IllegalArgumentException("Session must have valid start and end times")
|
IllegalArgumentException("Session must have valid start and end times"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d(TAG, "Attempting to sync session '${session.id}' to Health Connect...")
|
AppLogger.d(TAG) { "Attempting to sync session '${session.id}' to Health Connect..." }
|
||||||
|
|
||||||
val records = mutableListOf<androidx.health.connect.client.records.Record>()
|
val records = mutableListOf<androidx.health.connect.client.records.Record>()
|
||||||
|
|
||||||
@@ -195,11 +196,11 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||||
exerciseType =
|
exerciseType =
|
||||||
ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING,
|
ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING,
|
||||||
title = "Rock Climbing at $gymName"
|
title = "Rock Climbing at $gymName",
|
||||||
)
|
)
|
||||||
records.add(exerciseSession)
|
records.add(exerciseSession)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "Failed to create exercise session record", e)
|
AppLogger.w(TAG, e) { "Failed to create exercise session record" }
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -215,28 +216,27 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
endTime = endTime,
|
endTime = endTime,
|
||||||
endZoneOffset =
|
endZoneOffset =
|
||||||
ZoneOffset.systemDefault().rules.getOffset(endTime),
|
ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||||
energy = Energy.calories(estimatedCalories)
|
energy = Energy.calories(estimatedCalories),
|
||||||
)
|
)
|
||||||
records.add(caloriesRecord)
|
records.add(caloriesRecord)
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "Failed to create calories record", e)
|
AppLogger.w(TAG, e) { "Failed to create calories record" }
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val heartRateRecord = createHeartRateRecord(startTime, endTime, attemptCount)
|
val heartRateRecord = createHeartRateRecord(startTime, endTime, attemptCount)
|
||||||
heartRateRecord?.let { records.add(it) }
|
heartRateRecord?.let { records.add(it) }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "Failed to create heart rate record", e)
|
AppLogger.w(TAG, e) { "Failed to create heart rate record" }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (records.isNotEmpty() && healthConnectClient != null) {
|
if (records.isNotEmpty() && healthConnectClient != null) {
|
||||||
Log.d(TAG, "Writing ${records.size} records to Health Connect...")
|
AppLogger.d(TAG) { "Writing ${records.size} records to Health Connect..." }
|
||||||
healthConnectClient!!.insertRecords(records)
|
healthConnectClient!!.insertRecords(records)
|
||||||
Log.i(
|
AppLogger.i(TAG) {
|
||||||
TAG,
|
|
||||||
"Successfully synced ${records.size} records for session '${session.id}' to Health Connect"
|
"Successfully synced ${records.size} records for session '${session.id}' to Health Connect"
|
||||||
)
|
}
|
||||||
|
|
||||||
preferences
|
preferences
|
||||||
.edit()
|
.edit()
|
||||||
@@ -249,13 +249,13 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
healthConnectClient == null -> "Health Connect client unavailable"
|
healthConnectClient == null -> "Health Connect client unavailable"
|
||||||
else -> "Unknown reason"
|
else -> "Unknown reason"
|
||||||
}
|
}
|
||||||
Log.w(TAG, "Sync failed for session '${session.id}': $reason")
|
AppLogger.w(TAG) { "Sync failed for session '${session.id}': $reason" }
|
||||||
return Result.failure(Exception("Sync failed: $reason"))
|
return Result.failure(Exception("Sync failed: $reason"))
|
||||||
}
|
}
|
||||||
|
|
||||||
Result.success(Unit)
|
Result.success(Unit)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Error syncing climbing session to Health Connect", e)
|
AppLogger.e(TAG, e) { "Error syncing climbing session to Health Connect" }
|
||||||
Result.failure(e)
|
Result.failure(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -263,10 +263,10 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
suspend fun autoSyncCompletedSession(
|
suspend fun autoSyncCompletedSession(
|
||||||
session: ClimbSession,
|
session: ClimbSession,
|
||||||
gymName: String,
|
gymName: String,
|
||||||
attemptCount: Int = 0
|
attemptCount: Int = 0,
|
||||||
): Result<Unit> {
|
): Result<Unit> {
|
||||||
return if (_autoSync.value && isReady() && session.status == SessionStatus.COMPLETED) {
|
return if (_autoSync.value && isReady() && session.status == SessionStatus.COMPLETED) {
|
||||||
Log.d(TAG, "Auto-syncing completed session '${session.id}' to Health Connect...")
|
AppLogger.d(TAG) { "Auto-syncing completed session '${session.id}' to Health Connect..." }
|
||||||
syncCompletedSession(session, gymName, attemptCount)
|
syncCompletedSession(session, gymName, attemptCount)
|
||||||
} else {
|
} else {
|
||||||
val reason =
|
val reason =
|
||||||
@@ -276,7 +276,7 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
!isReady() -> "Health Connect not ready"
|
!isReady() -> "Health Connect not ready"
|
||||||
else -> "unknown reason"
|
else -> "unknown reason"
|
||||||
}
|
}
|
||||||
Log.d(TAG, "Auto-sync skipped for session '${session.id}': $reason")
|
AppLogger.d(TAG) { "Auto-sync skipped for session '${session.id}': $reason" }
|
||||||
Result.success(Unit)
|
Result.success(Unit)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -296,7 +296,7 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
private fun createHeartRateRecord(
|
private fun createHeartRateRecord(
|
||||||
startTime: Instant,
|
startTime: Instant,
|
||||||
endTime: Instant,
|
endTime: Instant,
|
||||||
attemptCount: Int
|
attemptCount: Int,
|
||||||
): HeartRateRecord? {
|
): HeartRateRecord? {
|
||||||
return try {
|
return try {
|
||||||
val samples = mutableListOf<HeartRateRecord.Sample>()
|
val samples = mutableListOf<HeartRateRecord.Sample>()
|
||||||
@@ -325,10 +325,10 @@ class HealthConnectManager(private val context: Context) {
|
|||||||
startZoneOffset = ZoneOffset.systemDefault().rules.getOffset(startTime),
|
startZoneOffset = ZoneOffset.systemDefault().rules.getOffset(startTime),
|
||||||
endTime = endTime,
|
endTime = endTime,
|
||||||
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
endZoneOffset = ZoneOffset.systemDefault().rules.getOffset(endTime),
|
||||||
samples = samples
|
samples = samples,
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Error creating heart rate record", e)
|
AppLogger.e(TAG, e) { "Error creating heart rate record" }
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ enum class AttemptResult {
|
|||||||
SUCCESS,
|
SUCCESS,
|
||||||
FALL,
|
FALL,
|
||||||
NO_PROGRESS,
|
NO_PROGRESS,
|
||||||
FLASH
|
FLASH,
|
||||||
}
|
}
|
||||||
|
|
||||||
@Entity(
|
@Entity(
|
||||||
@@ -23,15 +23,16 @@ enum class AttemptResult {
|
|||||||
entity = ClimbSession::class,
|
entity = ClimbSession::class,
|
||||||
parentColumns = ["id"],
|
parentColumns = ["id"],
|
||||||
childColumns = ["sessionId"],
|
childColumns = ["sessionId"],
|
||||||
onDelete = ForeignKey.CASCADE
|
onDelete = ForeignKey.CASCADE,
|
||||||
),
|
),
|
||||||
ForeignKey(
|
ForeignKey(
|
||||||
entity = Problem::class,
|
entity = Problem::class,
|
||||||
parentColumns = ["id"],
|
parentColumns = ["id"],
|
||||||
childColumns = ["problemId"],
|
childColumns = ["problemId"],
|
||||||
onDelete = ForeignKey.CASCADE
|
onDelete = ForeignKey.CASCADE,
|
||||||
)],
|
),
|
||||||
indices = [Index(value = ["sessionId"]), Index(value = ["problemId"])]
|
],
|
||||||
|
indices = [Index(value = ["sessionId"]), Index(value = ["problemId"])],
|
||||||
)
|
)
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Attempt(
|
data class Attempt(
|
||||||
@@ -45,7 +46,7 @@ data class Attempt(
|
|||||||
val restTime: Long? = null,
|
val restTime: Long? = null,
|
||||||
val timestamp: String,
|
val timestamp: String,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String
|
val updatedAt: String,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun create(
|
fun create(
|
||||||
@@ -56,7 +57,7 @@ data class Attempt(
|
|||||||
notes: String? = null,
|
notes: String? = null,
|
||||||
duration: Long? = null,
|
duration: Long? = null,
|
||||||
restTime: Long? = null,
|
restTime: Long? = null,
|
||||||
timestamp: String = DateFormatUtils.nowISO8601()
|
timestamp: String = DateFormatUtils.nowISO8601(),
|
||||||
): Attempt {
|
): Attempt {
|
||||||
val now = DateFormatUtils.nowISO8601()
|
val now = DateFormatUtils.nowISO8601()
|
||||||
return Attempt(
|
return Attempt(
|
||||||
@@ -70,7 +71,7 @@ data class Attempt(
|
|||||||
restTime = restTime,
|
restTime = restTime,
|
||||||
timestamp = timestamp,
|
timestamp = timestamp,
|
||||||
createdAt = now,
|
createdAt = now,
|
||||||
updatedAt = now
|
updatedAt = now,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import kotlinx.serialization.Serializable
|
|||||||
enum class SessionStatus {
|
enum class SessionStatus {
|
||||||
ACTIVE,
|
ACTIVE,
|
||||||
COMPLETED,
|
COMPLETED,
|
||||||
PAUSED
|
PAUSED,
|
||||||
}
|
}
|
||||||
|
|
||||||
@Entity(
|
@Entity(
|
||||||
@@ -22,9 +22,10 @@ enum class SessionStatus {
|
|||||||
entity = Gym::class,
|
entity = Gym::class,
|
||||||
parentColumns = ["id"],
|
parentColumns = ["id"],
|
||||||
childColumns = ["gymId"],
|
childColumns = ["gymId"],
|
||||||
onDelete = ForeignKey.CASCADE
|
onDelete = ForeignKey.CASCADE,
|
||||||
)],
|
),
|
||||||
indices = [Index(value = ["gymId"])]
|
],
|
||||||
|
indices = [Index(value = ["gymId"])],
|
||||||
)
|
)
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ClimbSession(
|
data class ClimbSession(
|
||||||
@@ -37,7 +38,7 @@ data class ClimbSession(
|
|||||||
val status: SessionStatus = SessionStatus.ACTIVE,
|
val status: SessionStatus = SessionStatus.ACTIVE,
|
||||||
val notes: String? = null,
|
val notes: String? = null,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String
|
val updatedAt: String,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun create(gymId: String, notes: String? = null): ClimbSession {
|
fun create(gymId: String, notes: String? = null): ClimbSession {
|
||||||
@@ -50,7 +51,7 @@ data class ClimbSession(
|
|||||||
status = SessionStatus.ACTIVE,
|
status = SessionStatus.ACTIVE,
|
||||||
notes = notes,
|
notes = notes,
|
||||||
createdAt = now,
|
createdAt = now,
|
||||||
updatedAt = now
|
updatedAt = now,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,17 +64,21 @@ data class ClimbSession(
|
|||||||
val end = DateFormatUtils.parseISO8601(endTime)
|
val end = DateFormatUtils.parseISO8601(endTime)
|
||||||
if (start != null && end != null) {
|
if (start != null && end != null) {
|
||||||
java.time.Duration.between(start, end).toMinutes()
|
java.time.Duration.between(start, end).toMinutes()
|
||||||
} else null
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
} else null
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
return this.copy(
|
return this.copy(
|
||||||
endTime = endTime,
|
endTime = endTime,
|
||||||
duration = durationMinutes,
|
duration = durationMinutes,
|
||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
updatedAt = DateFormatUtils.nowISO8601()
|
updatedAt = DateFormatUtils.nowISO8601(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import kotlinx.serialization.Serializable
|
|||||||
@Serializable
|
@Serializable
|
||||||
enum class ClimbType {
|
enum class ClimbType {
|
||||||
ROPE,
|
ROPE,
|
||||||
BOULDER;
|
BOULDER,
|
||||||
|
;
|
||||||
|
|
||||||
val displayName: String
|
val displayName: String
|
||||||
get() =
|
get() =
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ enum class DifficultySystem {
|
|||||||
|
|
||||||
// Rope
|
// Rope
|
||||||
YDS,
|
YDS,
|
||||||
CUSTOM;
|
CUSTOM,
|
||||||
|
;
|
||||||
|
|
||||||
val displayName: String
|
val displayName: String
|
||||||
get() =
|
get() =
|
||||||
@@ -60,7 +61,7 @@ enum class DifficultySystem {
|
|||||||
"V14",
|
"V14",
|
||||||
"V15",
|
"V15",
|
||||||
"V16",
|
"V16",
|
||||||
"V17"
|
"V17",
|
||||||
)
|
)
|
||||||
FONT ->
|
FONT ->
|
||||||
listOf(
|
listOf(
|
||||||
@@ -88,7 +89,7 @@ enum class DifficultySystem {
|
|||||||
"8B",
|
"8B",
|
||||||
"8B+",
|
"8B+",
|
||||||
"8C",
|
"8C",
|
||||||
"8C+"
|
"8C+",
|
||||||
)
|
)
|
||||||
YDS ->
|
YDS ->
|
||||||
listOf(
|
listOf(
|
||||||
@@ -125,7 +126,7 @@ enum class DifficultySystem {
|
|||||||
"5.15a",
|
"5.15a",
|
||||||
"5.15b",
|
"5.15b",
|
||||||
"5.15c",
|
"5.15c",
|
||||||
"5.15d"
|
"5.15d",
|
||||||
)
|
)
|
||||||
CUSTOM -> emptyList()
|
CUSTOM -> emptyList()
|
||||||
}
|
}
|
||||||
@@ -144,7 +145,7 @@ data class DifficultyGrade(val system: DifficultySystem, val grade: String, val
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
system: DifficultySystem,
|
system: DifficultySystem,
|
||||||
grade: String
|
grade: String,
|
||||||
) : this(system = system, grade = grade, numericValue = calculateNumericValue(system, grade))
|
) : this(system = system, grade = grade, numericValue = calculateNumericValue(system, grade))
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -180,7 +181,7 @@ data class DifficultyGrade(val system: DifficultySystem, val grade: String, val
|
|||||||
"8B" to 24,
|
"8B" to 24,
|
||||||
"8B+" to 25,
|
"8B+" to 25,
|
||||||
"8C" to 26,
|
"8C" to 26,
|
||||||
"8C+" to 27
|
"8C+" to 27,
|
||||||
)
|
)
|
||||||
fontMapping[grade] ?: 0
|
fontMapping[grade] ?: 0
|
||||||
}
|
}
|
||||||
@@ -220,7 +221,7 @@ data class DifficultyGrade(val system: DifficultySystem, val grade: String, val
|
|||||||
"5.15a" to 80,
|
"5.15a" to 80,
|
||||||
"5.15b" to 81,
|
"5.15b" to 81,
|
||||||
"5.15c" to 82,
|
"5.15c" to 82,
|
||||||
"5.15d" to 83
|
"5.15d" to 83,
|
||||||
)
|
)
|
||||||
ydsMapping[grade] ?: 0
|
ydsMapping[grade] ?: 0
|
||||||
}
|
}
|
||||||
@@ -228,6 +229,7 @@ data class DifficultyGrade(val system: DifficultySystem, val grade: String, val
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compare this grade with another grade of the same system Returns negative if this grade is
|
* Compare this grade with another grade of the same system Returns negative if this grade is
|
||||||
* easier, positive if harder, 0 if equal
|
* easier, positive if harder, 0 if equal
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ data class Gym(
|
|||||||
val customDifficultyGrades: List<String> = emptyList(),
|
val customDifficultyGrades: List<String> = emptyList(),
|
||||||
val notes: String? = null,
|
val notes: String? = null,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String
|
val updatedAt: String,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun create(
|
fun create(
|
||||||
@@ -25,7 +25,7 @@ data class Gym(
|
|||||||
supportedClimbTypes: List<ClimbType>,
|
supportedClimbTypes: List<ClimbType>,
|
||||||
difficultySystems: List<DifficultySystem>,
|
difficultySystems: List<DifficultySystem>,
|
||||||
customDifficultyGrades: List<String> = emptyList(),
|
customDifficultyGrades: List<String> = emptyList(),
|
||||||
notes: String? = null
|
notes: String? = null,
|
||||||
): Gym {
|
): Gym {
|
||||||
val now = DateFormatUtils.nowISO8601()
|
val now = DateFormatUtils.nowISO8601()
|
||||||
return Gym(
|
return Gym(
|
||||||
@@ -37,7 +37,7 @@ data class Gym(
|
|||||||
customDifficultyGrades = customDifficultyGrades,
|
customDifficultyGrades = customDifficultyGrades,
|
||||||
notes = notes,
|
notes = notes,
|
||||||
createdAt = now,
|
createdAt = now,
|
||||||
updatedAt = now
|
updatedAt = now,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,9 +15,10 @@ import kotlinx.serialization.Serializable
|
|||||||
entity = Gym::class,
|
entity = Gym::class,
|
||||||
parentColumns = ["id"],
|
parentColumns = ["id"],
|
||||||
childColumns = ["gymId"],
|
childColumns = ["gymId"],
|
||||||
onDelete = ForeignKey.CASCADE
|
onDelete = ForeignKey.CASCADE,
|
||||||
)],
|
),
|
||||||
indices = [Index(value = ["gymId"])]
|
],
|
||||||
|
indices = [Index(value = ["gymId"])],
|
||||||
)
|
)
|
||||||
@Serializable
|
@Serializable
|
||||||
data class Problem(
|
data class Problem(
|
||||||
@@ -34,7 +35,7 @@ data class Problem(
|
|||||||
val dateSet: String? = null,
|
val dateSet: String? = null,
|
||||||
val notes: String? = null,
|
val notes: String? = null,
|
||||||
val createdAt: String,
|
val createdAt: String,
|
||||||
val updatedAt: String
|
val updatedAt: String,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun create(
|
fun create(
|
||||||
@@ -47,7 +48,7 @@ data class Problem(
|
|||||||
location: String? = null,
|
location: String? = null,
|
||||||
imagePaths: List<String> = emptyList(),
|
imagePaths: List<String> = emptyList(),
|
||||||
dateSet: String? = null,
|
dateSet: String? = null,
|
||||||
notes: String? = null
|
notes: String? = null,
|
||||||
): Problem {
|
): Problem {
|
||||||
val now = DateFormatUtils.nowISO8601()
|
val now = DateFormatUtils.nowISO8601()
|
||||||
return Problem(
|
return Problem(
|
||||||
@@ -64,7 +65,7 @@ data class Problem(
|
|||||||
dateSet = dateSet,
|
dateSet = dateSet,
|
||||||
notes = notes,
|
notes = notes,
|
||||||
createdAt = now,
|
createdAt = now,
|
||||||
updatedAt = now
|
updatedAt = now,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,12 +12,13 @@ import com.atridad.ascently.data.format.ClimbDataBackup
|
|||||||
import com.atridad.ascently.data.format.DeletedItem
|
import com.atridad.ascently.data.format.DeletedItem
|
||||||
import com.atridad.ascently.data.model.*
|
import com.atridad.ascently.data.model.*
|
||||||
import com.atridad.ascently.data.state.DataStateManager
|
import com.atridad.ascently.data.state.DataStateManager
|
||||||
|
import com.atridad.ascently.utils.AppLogger
|
||||||
import com.atridad.ascently.utils.DateFormatUtils
|
import com.atridad.ascently.utils.DateFormatUtils
|
||||||
import com.atridad.ascently.utils.ZipExportImportUtils
|
import com.atridad.ascently.utils.ZipExportImportUtils
|
||||||
import java.io.File
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
class ClimbRepository(database: AscentlyDatabase, private val context: Context) {
|
class ClimbRepository(database: AscentlyDatabase, private val context: Context) {
|
||||||
private val gymDao = database.gymDao()
|
private val gymDao = database.gymDao()
|
||||||
@@ -43,11 +44,13 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
triggerAutoSync()
|
triggerAutoSync()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun updateGym(gym: Gym) {
|
suspend fun updateGym(gym: Gym) {
|
||||||
gymDao.updateGym(gym)
|
gymDao.updateGym(gym)
|
||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
triggerAutoSync()
|
triggerAutoSync()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun deleteGym(gym: Gym) {
|
suspend fun deleteGym(gym: Gym) {
|
||||||
gymDao.deleteGym(gym)
|
gymDao.deleteGym(gym)
|
||||||
trackDeletion(gym.id, "gym")
|
trackDeletion(gym.id, "gym")
|
||||||
@@ -63,10 +66,12 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
problemDao.insertProblem(problem)
|
problemDao.insertProblem(problem)
|
||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun updateProblem(problem: Problem) {
|
suspend fun updateProblem(problem: Problem) {
|
||||||
problemDao.updateProblem(problem)
|
problemDao.updateProblem(problem)
|
||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun deleteProblem(problem: Problem) {
|
suspend fun deleteProblem(problem: Problem) {
|
||||||
problemDao.deleteProblem(problem)
|
problemDao.deleteProblem(problem)
|
||||||
trackDeletion(problem.id, "problem")
|
trackDeletion(problem.id, "problem")
|
||||||
@@ -78,6 +83,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
suspend fun getSessionById(id: String): ClimbSession? = sessionDao.getSessionById(id)
|
suspend fun getSessionById(id: String): ClimbSession? = sessionDao.getSessionById(id)
|
||||||
fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>> =
|
fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>> =
|
||||||
sessionDao.getSessionsByGym(gymId)
|
sessionDao.getSessionsByGym(gymId)
|
||||||
|
|
||||||
suspend fun getActiveSession(): ClimbSession? = sessionDao.getActiveSession()
|
suspend fun getActiveSession(): ClimbSession? = sessionDao.getActiveSession()
|
||||||
fun getActiveSessionFlow(): Flow<ClimbSession?> = sessionDao.getActiveSessionFlow()
|
fun getActiveSessionFlow(): Flow<ClimbSession?> = sessionDao.getActiveSessionFlow()
|
||||||
suspend fun insertSession(session: ClimbSession) {
|
suspend fun insertSession(session: ClimbSession) {
|
||||||
@@ -88,6 +94,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
triggerAutoSync()
|
triggerAutoSync()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun updateSession(session: ClimbSession) {
|
suspend fun updateSession(session: ClimbSession) {
|
||||||
sessionDao.updateSession(session)
|
sessionDao.updateSession(session)
|
||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
@@ -96,12 +103,14 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
triggerAutoSync()
|
triggerAutoSync()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun deleteSession(session: ClimbSession) {
|
suspend fun deleteSession(session: ClimbSession) {
|
||||||
sessionDao.deleteSession(session)
|
sessionDao.deleteSession(session)
|
||||||
trackDeletion(session.id, "session")
|
trackDeletion(session.id, "session")
|
||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
triggerAutoSync()
|
triggerAutoSync()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun getLastUsedGym(): Gym? {
|
suspend fun getLastUsedGym(): Gym? {
|
||||||
val recentSessions = sessionDao.getRecentSessions(1).first()
|
val recentSessions = sessionDao.getRecentSessions(1).first()
|
||||||
return if (recentSessions.isNotEmpty()) {
|
return if (recentSessions.isNotEmpty()) {
|
||||||
@@ -115,16 +124,20 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
fun getAllAttempts(): Flow<List<Attempt>> = attemptDao.getAllAttempts()
|
fun getAllAttempts(): Flow<List<Attempt>> = attemptDao.getAllAttempts()
|
||||||
fun getAttemptsBySession(sessionId: String): Flow<List<Attempt>> =
|
fun getAttemptsBySession(sessionId: String): Flow<List<Attempt>> =
|
||||||
attemptDao.getAttemptsBySession(sessionId)
|
attemptDao.getAttemptsBySession(sessionId)
|
||||||
|
|
||||||
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>> =
|
fun getAttemptsByProblem(problemId: String): Flow<List<Attempt>> =
|
||||||
attemptDao.getAttemptsByProblem(problemId)
|
attemptDao.getAttemptsByProblem(problemId)
|
||||||
|
|
||||||
suspend fun insertAttempt(attempt: Attempt) {
|
suspend fun insertAttempt(attempt: Attempt) {
|
||||||
attemptDao.insertAttempt(attempt)
|
attemptDao.insertAttempt(attempt)
|
||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun updateAttempt(attempt: Attempt) {
|
suspend fun updateAttempt(attempt: Attempt) {
|
||||||
attemptDao.updateAttempt(attempt)
|
attemptDao.updateAttempt(attempt)
|
||||||
dataStateManager.updateDataState()
|
dataStateManager.updateDataState()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun deleteAttempt(attempt: Attempt) {
|
suspend fun deleteAttempt(attempt: Attempt) {
|
||||||
attemptDao.deleteAttempt(attempt)
|
attemptDao.deleteAttempt(attempt)
|
||||||
trackDeletion(attempt.id, "attempt")
|
trackDeletion(attempt.id, "attempt")
|
||||||
@@ -148,7 +161,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
gyms = allGyms.map { BackupGym.fromGym(it) },
|
gyms = allGyms.map { BackupGym.fromGym(it) },
|
||||||
problems = allProblems.map { BackupProblem.fromProblem(it) },
|
problems = allProblems.map { BackupProblem.fromProblem(it) },
|
||||||
sessions = allSessions.map { BackupClimbSession.fromClimbSession(it) },
|
sessions = allSessions.map { BackupClimbSession.fromClimbSession(it) },
|
||||||
attempts = allAttempts.map { BackupAttempt.fromAttempt(it) }
|
attempts = allAttempts.map { BackupAttempt.fromAttempt(it) },
|
||||||
)
|
)
|
||||||
|
|
||||||
val referencedImagePaths = allProblems.flatMap { it.imagePaths }.toSet()
|
val referencedImagePaths = allProblems.flatMap { it.imagePaths }.toSet()
|
||||||
@@ -159,7 +172,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
val imageFile =
|
val imageFile =
|
||||||
com.atridad.ascently.utils.ImageUtils.getImageFile(
|
com.atridad.ascently.utils.ImageUtils.getImageFile(
|
||||||
context,
|
context,
|
||||||
imagePath
|
imagePath,
|
||||||
)
|
)
|
||||||
imageFile.exists() && imageFile.length() > 0
|
imageFile.exists() && imageFile.length() > 0
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
@@ -172,7 +185,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
context = context,
|
context = context,
|
||||||
uri = uri,
|
uri = uri,
|
||||||
exportData = backupData,
|
exportData = backupData,
|
||||||
referencedImagePaths = validImagePaths
|
referencedImagePaths = validImagePaths,
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw Exception("Export failed: ${e.message}")
|
throw Exception("Export failed: ${e.message}")
|
||||||
@@ -216,7 +229,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
val updatedBackupProblems =
|
val updatedBackupProblems =
|
||||||
ZipExportImportUtils.updateProblemImagePaths(
|
ZipExportImportUtils.updateProblemImagePaths(
|
||||||
importData.problems,
|
importData.problems,
|
||||||
importResult.importedImagePaths
|
importResult.importedImagePaths,
|
||||||
)
|
)
|
||||||
|
|
||||||
updatedBackupProblems.forEach { backupProblem ->
|
updatedBackupProblems.forEach { backupProblem ->
|
||||||
@@ -224,7 +237,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
problemDao.insertProblem(backupProblem.toProblem())
|
problemDao.insertProblem(backupProblem.toProblem())
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw Exception(
|
throw Exception(
|
||||||
"Failed to import problem '${backupProblem.name}': ${e.message}"
|
"Failed to import problem '${backupProblem.name}': ${e.message}",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,7 +279,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
currentDeletions.add(newDeletion)
|
currentDeletions.add(newDeletion)
|
||||||
|
|
||||||
val json = json.encodeToString(newDeletion)
|
val json = json.encodeToString(newDeletion)
|
||||||
deletionPreferences.edit { putString("deleted_${itemId}", json) }
|
deletionPreferences.edit { putString("deleted_$itemId", json) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getDeletedItems(): List<DeletedItem> {
|
fun getDeletedItems(): List<DeletedItem> {
|
||||||
@@ -295,20 +308,20 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
gyms: List<Gym>,
|
gyms: List<Gym>,
|
||||||
problems: List<Problem>,
|
problems: List<Problem>,
|
||||||
sessions: List<ClimbSession>,
|
sessions: List<ClimbSession>,
|
||||||
attempts: List<Attempt>
|
attempts: List<Attempt>,
|
||||||
) {
|
) {
|
||||||
val gymIds = gyms.map { it.id }.toSet()
|
val gymIds = gyms.map { it.id }.toSet()
|
||||||
val invalidProblems = problems.filter { it.gymId !in gymIds }
|
val invalidProblems = problems.filter { it.gymId !in gymIds }
|
||||||
if (invalidProblems.isNotEmpty()) {
|
if (invalidProblems.isNotEmpty()) {
|
||||||
throw Exception(
|
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 }
|
val invalidSessions = sessions.filter { it.gymId !in gymIds }
|
||||||
if (invalidSessions.isNotEmpty()) {
|
if (invalidSessions.isNotEmpty()) {
|
||||||
throw Exception(
|
throw Exception(
|
||||||
"Data integrity error: ${invalidSessions.size} sessions reference non-existent gyms"
|
"Data integrity error: ${invalidSessions.size} sessions reference non-existent gyms",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -319,7 +332,7 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
attempts.filter { it.problemId !in problemIds || it.sessionId !in sessionIds }
|
attempts.filter { it.problemId !in problemIds || it.sessionId !in sessionIds }
|
||||||
if (invalidAttempts.isNotEmpty()) {
|
if (invalidAttempts.isNotEmpty()) {
|
||||||
throw Exception(
|
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",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -386,10 +399,10 @@ class ClimbRepository(database: AscentlyDatabase, private val context: Context)
|
|||||||
if (imagesDir.exists() && imagesDir.isDirectory) {
|
if (imagesDir.exists() && imagesDir.isDirectory) {
|
||||||
val deletedCount = imagesDir.listFiles()?.size ?: 0
|
val deletedCount = imagesDir.listFiles()?.size ?: 0
|
||||||
imagesDir.deleteRecursively()
|
imagesDir.deleteRecursively()
|
||||||
android.util.Log.i("ClimbRepository", "Cleared $deletedCount image files")
|
AppLogger.i("ClimbRepository") { "Cleared $deletedCount image files" }
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} 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}" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ package com.atridad.ascently.data.state
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import android.util.Log
|
|
||||||
import androidx.core.content.edit
|
import androidx.core.content.edit
|
||||||
|
import com.atridad.ascently.utils.AppLogger
|
||||||
import com.atridad.ascently.utils.DateFormatUtils
|
import com.atridad.ascently.utils.DateFormatUtils
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,7 +26,7 @@ class DataStateManager(context: Context) {
|
|||||||
if (!isInitialized()) {
|
if (!isInitialized()) {
|
||||||
updateDataState()
|
updateDataState()
|
||||||
markAsInitialized()
|
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() {
|
fun updateDataState() {
|
||||||
val now = DateFormatUtils.nowISO8601()
|
val now = DateFormatUtils.nowISO8601()
|
||||||
prefs.edit { putString(KEY_LAST_MODIFIED, now) }
|
prefs.edit { putString(KEY_LAST_MODIFIED, now) }
|
||||||
Log.d(TAG, "Data state updated to: $now")
|
AppLogger.d(TAG) { "Data state updated to: $now" }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,743 @@
|
|||||||
|
package com.atridad.ascently.data.sync
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import androidx.annotation.RequiresPermission
|
||||||
|
import androidx.core.content.edit
|
||||||
|
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 com.atridad.ascently.utils.ImageNamingUtils
|
||||||
|
import com.atridad.ascently.utils.ImageUtils
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import java.io.IOException
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class AscentlySyncProvider(
|
||||||
|
private val context: Context,
|
||||||
|
private val repository: ClimbRepository,
|
||||||
|
) : SyncProvider {
|
||||||
|
|
||||||
|
override val type: SyncProviderType = SyncProviderType.SERVER
|
||||||
|
|
||||||
|
private val dataStateManager = DataStateManager(context)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "AscentlySyncProvider"
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
coerceInputValues = 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()
|
||||||
|
|
||||||
|
private var isOfflineMode = false
|
||||||
|
|
||||||
|
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 OFFLINE_MODE = "offline_mode"
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
loadInitialState()
|
||||||
|
updateConfiguredState()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadInitialState() {
|
||||||
|
_isConnected.value = sharedPreferences.getBoolean(Keys.IS_CONNECTED, false)
|
||||||
|
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) }
|
||||||
|
}
|
||||||
|
|
||||||
|
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) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@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)
|
||||||
|
override suspend fun sync() {
|
||||||
|
if (isOfflineMode) {
|
||||||
|
AppLogger.d(TAG) { "Sync skipped: Offline mode is enabled." }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!isNetworkAvailable()) {
|
||||||
|
AppLogger.d(TAG) { "Sync skipped: No internet connection." }
|
||||||
|
throw SyncException.NetworkError("No internet connection.")
|
||||||
|
}
|
||||||
|
if (!_isConfigured.value) {
|
||||||
|
throw SyncException.NotConfigured
|
||||||
|
}
|
||||||
|
if (!_isConnected.value) {
|
||||||
|
throw SyncException.NotConnected
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
val lastSyncTimeStr = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
||||||
|
if (hasLocalData && hasServerData && lastSyncTimeStr != null) {
|
||||||
|
AppLogger.d(TAG) { "Using delta sync for incremental updates" }
|
||||||
|
performDeltaSync(lastSyncTimeStr)
|
||||||
|
} else {
|
||||||
|
when {
|
||||||
|
!hasLocalData && hasServerData -> {
|
||||||
|
AppLogger.d(TAG) { "No local data found, performing full restore from server" }
|
||||||
|
val imagePathMapping = syncImagesFromServer(serverBackup)
|
||||||
|
importBackupToRepository(serverBackup, imagePathMapping)
|
||||||
|
AppLogger.d(TAG) { "Full restore completed" }
|
||||||
|
}
|
||||||
|
|
||||||
|
hasLocalData && !hasServerData -> {
|
||||||
|
AppLogger.d(TAG) { "No server data found, uploading local data to server" }
|
||||||
|
uploadData(localBackup)
|
||||||
|
syncImagesForBackup(localBackup)
|
||||||
|
AppLogger.d(TAG) { "Initial upload completed" }
|
||||||
|
}
|
||||||
|
|
||||||
|
hasLocalData && hasServerData -> {
|
||||||
|
AppLogger.d(TAG) { "Both local and server data exist, merging (server wins)" }
|
||||||
|
mergeDataSafely(serverBackup)
|
||||||
|
AppLogger.d(TAG) { "Merge completed" }
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
AppLogger.d(TAG) { "No data to sync" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val now = DateFormatUtils.nowISO8601()
|
||||||
|
sharedPreferences.edit { putString(Keys.LAST_SYNC_TIME, now) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun disconnect() {
|
||||||
|
serverUrl = ""
|
||||||
|
authToken = ""
|
||||||
|
_isConnected.value = false
|
||||||
|
sharedPreferences.edit {
|
||||||
|
remove(Keys.LAST_SYNC_TIME)
|
||||||
|
putBoolean(Keys.IS_CONNECTED, false)
|
||||||
|
}
|
||||||
|
updateConfiguredState()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun performDeltaSync(lastSyncTimeStr: String) {
|
||||||
|
AppLogger.d(TAG) { "Starting delta sync with lastSyncTime=$lastSyncTimeStr" }
|
||||||
|
|
||||||
|
val lastSyncDate = parseISO8601(lastSyncTimeStr) ?: Date(0)
|
||||||
|
|
||||||
|
val allGyms = repository.getAllGyms().first()
|
||||||
|
val modifiedGyms =
|
||||||
|
allGyms
|
||||||
|
.filter { gym -> parseISO8601(gym.updatedAt)?.after(lastSyncDate) == true }
|
||||||
|
.map { BackupGym.fromGym(it) }
|
||||||
|
|
||||||
|
val allProblems = repository.getAllProblems().first()
|
||||||
|
val modifiedProblems =
|
||||||
|
allProblems
|
||||||
|
.filter { problem ->
|
||||||
|
parseISO8601(problem.updatedAt)?.after(lastSyncDate) == true
|
||||||
|
}
|
||||||
|
.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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val allSessions = repository.getAllSessions().first()
|
||||||
|
val modifiedSessions =
|
||||||
|
allSessions
|
||||||
|
.filter { session ->
|
||||||
|
parseISO8601(session.updatedAt)?.after(lastSyncDate) == true
|
||||||
|
}
|
||||||
|
.map { BackupClimbSession.fromClimbSession(it) }
|
||||||
|
|
||||||
|
val allAttempts = repository.getAllAttempts().first()
|
||||||
|
val modifiedAttempts =
|
||||||
|
allAttempts
|
||||||
|
.filter { attempt ->
|
||||||
|
parseISO8601(attempt.createdAt)?.after(lastSyncDate) == true
|
||||||
|
}
|
||||||
|
.map { BackupAttempt.fromAttempt(it) }
|
||||||
|
|
||||||
|
val allDeletions = repository.getDeletedItems()
|
||||||
|
val modifiedDeletions =
|
||||||
|
allDeletions.filter { item ->
|
||||||
|
parseISO8601(item.deletedAt)?.after(lastSyncDate) == true
|
||||||
|
}
|
||||||
|
|
||||||
|
AppLogger.d(TAG) {
|
||||||
|
"Delta sync sending: gyms=${modifiedGyms.size}, problems=${modifiedProblems.size}, sessions=${modifiedSessions.size}, attempts=${modifiedAttempts.size}, deletions=${modifiedDeletions.size}"
|
||||||
|
}
|
||||||
|
|
||||||
|
val deltaRequest =
|
||||||
|
DeltaSyncRequest(
|
||||||
|
lastSyncTime = lastSyncTimeStr,
|
||||||
|
gyms = modifiedGyms,
|
||||||
|
problems = modifiedProblems,
|
||||||
|
sessions = modifiedSessions,
|
||||||
|
attempts = modifiedAttempts,
|
||||||
|
deletedItems = modifiedDeletions,
|
||||||
|
)
|
||||||
|
|
||||||
|
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 deltaResponse =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
try {
|
||||||
|
httpClient.newCall(request).execute().use { response ->
|
||||||
|
if (response.isSuccessful) {
|
||||||
|
val body = response.body?.string()
|
||||||
|
if (!body.isNullOrEmpty()) {
|
||||||
|
json.decodeFromString(DeltaSyncResponse.serializer(), body)
|
||||||
|
} else {
|
||||||
|
throw SyncException.InvalidResponse("Empty response body")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
handleHttpError(response.code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
throw SyncException.NetworkError(e.message ?: "Network error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AppLogger.d(TAG) {
|
||||||
|
"Delta sync received: gyms=${deltaResponse.gyms.size}, " +
|
||||||
|
"problems=${deltaResponse.problems.size}, sessions=${deltaResponse.sessions.size}, " +
|
||||||
|
"attempts=${deltaResponse.attempts.size}, deletions=${deltaResponse.deletedItems.size}"
|
||||||
|
}
|
||||||
|
|
||||||
|
applyDeltaResponse(deltaResponse)
|
||||||
|
syncModifiedImages(modifiedProblems)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseISO8601(dateString: String): Date? {
|
||||||
|
return try {
|
||||||
|
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
|
||||||
|
format.parse(dateString)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun applyDeltaResponse(response: DeltaSyncResponse) {
|
||||||
|
// SyncService handles the "isSyncing" state to prevent recursive sync triggers
|
||||||
|
// when the repository is modified during a sync operation.
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Merge and apply deletions first to prevent resurrection
|
||||||
|
val allDeletions = repository.getDeletedItems() + response.deletedItems
|
||||||
|
val uniqueDeletions = allDeletions.distinctBy { "${it.type}:${it.id}" }
|
||||||
|
|
||||||
|
AppLogger.d(TAG) { "Applying ${uniqueDeletions.size} deletion records before merging data" }
|
||||||
|
applyDeletions(uniqueDeletions)
|
||||||
|
|
||||||
|
// Build deleted item lookup set
|
||||||
|
val deletedItemSet = uniqueDeletions.map { "${it.type}:${it.id}" }.toSet()
|
||||||
|
|
||||||
|
// Download images for new/modified problems from server
|
||||||
|
val imagePathMapping = mutableMapOf<String, String>()
|
||||||
|
for (problem in response.problems) {
|
||||||
|
if (deletedItemSet.contains("problem:${problem.id}")) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
problem.imagePaths?.forEach { imagePath ->
|
||||||
|
val serverFilename = imagePath.substringAfterLast('/')
|
||||||
|
try {
|
||||||
|
val localImagePath = downloadImage(serverFilename)
|
||||||
|
if (localImagePath != null) {
|
||||||
|
imagePathMapping[imagePath] = localImagePath
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
AppLogger.w(TAG) { "Failed to download image $imagePath: ${e.message}" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge gyms
|
||||||
|
val existingGyms = repository.getAllGyms().first()
|
||||||
|
for (backupGym in response.gyms) {
|
||||||
|
if (deletedItemSet.contains("gym:${backupGym.id}")) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val existing = existingGyms.find { it.id == backupGym.id }
|
||||||
|
if (existing == null || backupGym.updatedAt >= existing.updatedAt) {
|
||||||
|
val gym = backupGym.toGym()
|
||||||
|
if (existing != null) {
|
||||||
|
repository.updateGym(gym)
|
||||||
|
} else {
|
||||||
|
repository.insertGym(gym)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge problems
|
||||||
|
val existingProblems = repository.getAllProblems().first()
|
||||||
|
for (backupProblem in response.problems) {
|
||||||
|
if (deletedItemSet.contains("problem:${backupProblem.id}")) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val updatedImagePaths =
|
||||||
|
backupProblem.imagePaths?.map { oldPath ->
|
||||||
|
imagePathMapping[oldPath] ?: oldPath
|
||||||
|
}
|
||||||
|
val problemToMerge = backupProblem.copy(imagePaths = updatedImagePaths)
|
||||||
|
val problem = problemToMerge.toProblem()
|
||||||
|
|
||||||
|
val existing = existingProblems.find { it.id == backupProblem.id }
|
||||||
|
if (existing == null || backupProblem.updatedAt >= existing.updatedAt) {
|
||||||
|
if (existing != null) {
|
||||||
|
repository.updateProblem(problem)
|
||||||
|
} else {
|
||||||
|
repository.insertProblem(problem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge sessions
|
||||||
|
val existingSessions = repository.getAllSessions().first()
|
||||||
|
for (backupSession in response.sessions) {
|
||||||
|
if (deletedItemSet.contains("session:${backupSession.id}")) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val session = backupSession.toClimbSession()
|
||||||
|
val existing = existingSessions.find { it.id == backupSession.id }
|
||||||
|
if (existing == null || backupSession.updatedAt >= existing.updatedAt) {
|
||||||
|
if (existing != null) {
|
||||||
|
repository.updateSession(session)
|
||||||
|
} else {
|
||||||
|
repository.insertSession(session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge attempts
|
||||||
|
val existingAttempts = repository.getAllAttempts().first()
|
||||||
|
for (backupAttempt in response.attempts) {
|
||||||
|
if (deletedItemSet.contains("attempt:${backupAttempt.id}")) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val attempt = backupAttempt.toAttempt()
|
||||||
|
val existing = existingAttempts.find { it.id == backupAttempt.id }
|
||||||
|
if (existing == null || backupAttempt.createdAt >= existing.createdAt) {
|
||||||
|
if (existing != null) {
|
||||||
|
repository.updateAttempt(attempt)
|
||||||
|
} else {
|
||||||
|
repository.insertAttempt(attempt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply deletions again for safety
|
||||||
|
applyDeletions(uniqueDeletions)
|
||||||
|
|
||||||
|
// Update deletion records
|
||||||
|
repository.clearDeletedItems()
|
||||||
|
uniqueDeletions.forEach { repository.trackDeletion(it.id, it.type) }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
AppLogger.e(TAG, e) { "Error applying delta response" }
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun applyDeletions(
|
||||||
|
deletions: List<com.atridad.ascently.data.format.DeletedItem>,
|
||||||
|
) {
|
||||||
|
val existingGyms = repository.getAllGyms().first()
|
||||||
|
val existingProblems = repository.getAllProblems().first()
|
||||||
|
val existingSessions = repository.getAllSessions().first()
|
||||||
|
val existingAttempts = repository.getAllAttempts().first()
|
||||||
|
|
||||||
|
for (item in deletions) {
|
||||||
|
when (item.type) {
|
||||||
|
"gym" -> {
|
||||||
|
existingGyms.find { it.id == item.id }?.let { repository.deleteGym(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
"problem" -> {
|
||||||
|
existingProblems.find { it.id == item.id }?.let { repository.deleteProblem(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
"session" -> {
|
||||||
|
existingSessions.find { it.id == item.id }?.let { repository.deleteSession(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
"attempt" -> {
|
||||||
|
existingAttempts.find { it.id == item.id }?.let { repository.deleteAttempt(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun syncModifiedImages(modifiedProblems: List<BackupProblem>) {
|
||||||
|
if (modifiedProblems.isEmpty()) return
|
||||||
|
|
||||||
|
AppLogger.d(TAG) { "Syncing images for ${modifiedProblems.size} modified problems" }
|
||||||
|
|
||||||
|
for (backupProblem in modifiedProblems) {
|
||||||
|
backupProblem.imagePaths?.forEach { imagePath ->
|
||||||
|
val filename = imagePath.substringAfterLast('/')
|
||||||
|
uploadImage(imagePath, filename)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(backup).toRequestBody("application/json".toMediaType())
|
||||||
|
|
||||||
|
val request =
|
||||||
|
Request.Builder()
|
||||||
|
.url("$serverUrl/sync")
|
||||||
|
.header("Authorization", "Bearer $authToken")
|
||||||
|
.put(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 }
|
||||||
|
AppLogger.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) {
|
||||||
|
AppLogger.w(TAG) { "Image not found on server: $imagePath" }
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
AppLogger.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) {
|
||||||
|
AppLogger.e(TAG, e) { "Network error downloading image $serverFilename" }
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun syncImagesForBackup(backup: ClimbDataBackup) {
|
||||||
|
AppLogger.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()) {
|
||||||
|
AppLogger.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) {
|
||||||
|
AppLogger.d(TAG) { "Successfully uploaded image: $filename" }
|
||||||
|
} else {
|
||||||
|
AppLogger.w(TAG) {
|
||||||
|
"Failed to upload image $filename. Server responded with ${response.code}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
AppLogger.e(TAG, e) { "Network error uploading image $filename" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
AppLogger.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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun testConnection() {
|
||||||
|
if (!_isConfigured.value) {
|
||||||
|
_isConnected.value = false
|
||||||
|
throw SyncException.NotConfigured
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
throw SyncException.NotConnected
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_isConnected.value = false
|
||||||
|
throw SyncException.NetworkError(e.message ?: "Connection error")
|
||||||
|
} finally {
|
||||||
|
sharedPreferences.edit { putBoolean(Keys.IS_CONNECTED, _isConnected.value) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@ data class DeltaSyncRequest(
|
|||||||
val problems: List<BackupProblem>,
|
val problems: List<BackupProblem>,
|
||||||
val sessions: List<BackupClimbSession>,
|
val sessions: List<BackupClimbSession>,
|
||||||
val attempts: List<BackupAttempt>,
|
val attempts: List<BackupAttempt>,
|
||||||
val deletedItems: List<DeletedItem>
|
val deletedItems: List<DeletedItem>,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Response structure for delta sync - receives only changes from server */
|
/** Response structure for delta sync - receives only changes from server */
|
||||||
@@ -26,5 +26,5 @@ data class DeltaSyncResponse(
|
|||||||
val problems: List<BackupProblem>,
|
val problems: List<BackupProblem>,
|
||||||
val sessions: List<BackupClimbSession>,
|
val sessions: List<BackupClimbSession>,
|
||||||
val attempts: List<BackupAttempt>,
|
val attempts: List<BackupAttempt>,
|
||||||
val deletedItems: List<DeletedItem>
|
val deletedItems: List<DeletedItem>,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
@@ -2,27 +2,9 @@ package com.atridad.ascently.data.sync
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.SharedPreferences
|
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 androidx.core.content.edit
|
||||||
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.repository.ClimbRepository
|
||||||
import com.atridad.ascently.data.state.DataStateManager
|
import com.atridad.ascently.utils.AppLogger
|
||||||
import com.atridad.ascently.utils.DateFormatUtils
|
|
||||||
import com.atridad.ascently.utils.ImageNamingUtils
|
|
||||||
import com.atridad.ascently.utils.ImageUtils
|
|
||||||
import java.io.IOException
|
|
||||||
import java.io.Serializable
|
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.Date
|
|
||||||
import java.util.Locale
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
@@ -31,43 +13,21 @@ import kotlinx.coroutines.delay
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.first
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
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) {
|
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())
|
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
|
private val syncMutex = Mutex()
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "SyncService"
|
private const val TAG = "SyncService"
|
||||||
}
|
}
|
||||||
|
|
||||||
private val sharedPreferences: SharedPreferences =
|
// Currently we only support one provider, but this allows for future expansion
|
||||||
context.getSharedPreferences("sync_preferences", Context.MODE_PRIVATE)
|
private val provider: SyncProvider = AscentlySyncProvider(context, repository)
|
||||||
|
|
||||||
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
|
|
||||||
coerceInputValues = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// State
|
// State
|
||||||
private val _isSyncing = MutableStateFlow(false)
|
private val _isSyncing = MutableStateFlow(false)
|
||||||
@@ -79,11 +39,9 @@ class SyncService(private val context: Context, private val repository: ClimbRep
|
|||||||
private val _syncError = MutableStateFlow<String?>(null)
|
private val _syncError = MutableStateFlow<String?>(null)
|
||||||
val syncError: StateFlow<String?> = _syncError.asStateFlow()
|
val syncError: StateFlow<String?> = _syncError.asStateFlow()
|
||||||
|
|
||||||
private val _isConnected = MutableStateFlow(false)
|
// Delegate to provider
|
||||||
val isConnected: StateFlow<Boolean> = _isConnected.asStateFlow()
|
val isConnected: StateFlow<Boolean> = provider.isConnected
|
||||||
|
val isConfiguredFlow: StateFlow<Boolean> = provider.isConfigured
|
||||||
private val _isConfigured = MutableStateFlow(false)
|
|
||||||
val isConfiguredFlow: StateFlow<Boolean> = _isConfigured.asStateFlow()
|
|
||||||
|
|
||||||
private val _isTesting = MutableStateFlow(false)
|
private val _isTesting = MutableStateFlow(false)
|
||||||
val isTesting: StateFlow<Boolean> = _isTesting.asStateFlow()
|
val isTesting: StateFlow<Boolean> = _isTesting.asStateFlow()
|
||||||
@@ -91,56 +49,40 @@ class SyncService(private val context: Context, private val repository: ClimbRep
|
|||||||
private val _isAutoSyncEnabled = MutableStateFlow(true)
|
private val _isAutoSyncEnabled = MutableStateFlow(true)
|
||||||
val isAutoSyncEnabled: StateFlow<Boolean> = _isAutoSyncEnabled.asStateFlow()
|
val isAutoSyncEnabled: StateFlow<Boolean> = _isAutoSyncEnabled.asStateFlow()
|
||||||
|
|
||||||
private var isOfflineMode = false
|
|
||||||
|
|
||||||
// Debounced sync properties
|
// Debounced sync properties
|
||||||
private var syncJob: Job? = null
|
private var syncJob: Job? = null
|
||||||
private var pendingChanges = false
|
private var pendingChanges = false
|
||||||
private val syncDebounceDelay = 2000L // 2 seconds
|
private val syncDebounceDelay = 2000L // 2 seconds
|
||||||
|
|
||||||
// Configuration keys
|
private val sharedPreferences: SharedPreferences =
|
||||||
|
context.getSharedPreferences("sync_preferences", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
private object 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 LAST_SYNC_TIME = "last_sync_time"
|
||||||
const val AUTO_SYNC_ENABLED = "auto_sync_enabled"
|
const val AUTO_SYNC_ENABLED = "auto_sync_enabled"
|
||||||
const val OFFLINE_MODE = "offline_mode"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
init {
|
init {
|
||||||
loadInitialState()
|
loadInitialState()
|
||||||
updateConfiguredState()
|
|
||||||
repository.setAutoSyncCallback { serviceScope.launch { triggerAutoSync() } }
|
repository.setAutoSyncCallback { serviceScope.launch { triggerAutoSync() } }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun loadInitialState() {
|
private fun loadInitialState() {
|
||||||
_lastSyncTime.value = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
_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)
|
_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()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Proxy properties for Ascently provider configuration
|
||||||
var serverUrl: String
|
var serverUrl: String
|
||||||
get() = sharedPreferences.getString(Keys.SERVER_URL, "") ?: ""
|
get() = (provider as? AscentlySyncProvider)?.serverUrl ?: ""
|
||||||
set(value) {
|
set(value) {
|
||||||
sharedPreferences.edit { putString(Keys.SERVER_URL, value) }
|
(provider as? AscentlySyncProvider)?.serverUrl = value
|
||||||
updateConfiguredState()
|
|
||||||
_isConnected.value = false
|
|
||||||
sharedPreferences.edit { putBoolean(Keys.IS_CONNECTED, false) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var authToken: String
|
var authToken: String
|
||||||
get() = sharedPreferences.getString(Keys.AUTH_TOKEN, "") ?: ""
|
get() = (provider as? AscentlySyncProvider)?.authToken ?: ""
|
||||||
set(value) {
|
set(value) {
|
||||||
sharedPreferences.edit { putString(Keys.AUTH_TOKEN, value) }
|
(provider as? AscentlySyncProvider)?.authToken = value
|
||||||
updateConfiguredState()
|
|
||||||
_isConnected.value = false
|
|
||||||
sharedPreferences.edit { putBoolean(Keys.IS_CONNECTED, false) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setAutoSyncEnabled(enabled: Boolean) {
|
fun setAutoSyncEnabled(enabled: Boolean) {
|
||||||
@@ -148,90 +90,20 @@ class SyncService(private val context: Context, private val repository: ClimbRep
|
|||||||
sharedPreferences.edit { putBoolean(Keys.AUTO_SYNC_ENABLED, 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() {
|
suspend fun syncWithServer() {
|
||||||
if (isOfflineMode) {
|
if (!isConfiguredFlow.value) {
|
||||||
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
|
throw SyncException.NotConfigured
|
||||||
}
|
}
|
||||||
if (!_isConnected.value) {
|
|
||||||
throw SyncException.NotConnected
|
|
||||||
}
|
|
||||||
|
|
||||||
syncMutex.withLock {
|
syncMutex.withLock {
|
||||||
_isSyncing.value = true
|
_isSyncing.value = true
|
||||||
_syncError.value = null
|
_syncError.value = null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val localBackup = createBackupFromRepository()
|
provider.sync()
|
||||||
val serverBackup = downloadData()
|
|
||||||
|
|
||||||
val hasLocalData =
|
// Update last sync time from shared prefs (provider updates it)
|
||||||
localBackup.gyms.isNotEmpty() ||
|
_lastSyncTime.value = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
||||||
localBackup.problems.isNotEmpty() ||
|
|
||||||
localBackup.sessions.isNotEmpty() ||
|
|
||||||
localBackup.attempts.isNotEmpty()
|
|
||||||
|
|
||||||
val hasServerData =
|
|
||||||
serverBackup.gyms.isNotEmpty() ||
|
|
||||||
serverBackup.problems.isNotEmpty() ||
|
|
||||||
serverBackup.sessions.isNotEmpty() ||
|
|
||||||
serverBackup.attempts.isNotEmpty()
|
|
||||||
|
|
||||||
// If both client and server have been synced before, use delta sync
|
|
||||||
val lastSyncTimeStr = sharedPreferences.getString(Keys.LAST_SYNC_TIME, null)
|
|
||||||
if (hasLocalData && hasServerData && lastSyncTimeStr != null) {
|
|
||||||
Log.d(TAG, "Using delta sync for incremental updates")
|
|
||||||
performDeltaSync(lastSyncTimeStr)
|
|
||||||
} else {
|
|
||||||
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) {
|
} catch (e: Exception) {
|
||||||
_syncError.value = e.message
|
_syncError.value = e.message
|
||||||
throw e
|
throw e
|
||||||
@@ -241,550 +113,21 @@ class SyncService(private val context: Context, private val repository: ClimbRep
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun performDeltaSync(lastSyncTimeStr: String) {
|
|
||||||
Log.d(TAG, "Starting delta sync with lastSyncTime=$lastSyncTimeStr")
|
|
||||||
|
|
||||||
// Parse last sync time to filter modified items
|
|
||||||
val lastSyncDate = parseISO8601(lastSyncTimeStr) ?: Date(0)
|
|
||||||
|
|
||||||
// Collect items modified since last sync
|
|
||||||
val allGyms = repository.getAllGyms().first()
|
|
||||||
val modifiedGyms =
|
|
||||||
allGyms
|
|
||||||
.filter { gym -> parseISO8601(gym.updatedAt)?.after(lastSyncDate) == true }
|
|
||||||
.map { BackupGym.fromGym(it) }
|
|
||||||
|
|
||||||
val allProblems = repository.getAllProblems().first()
|
|
||||||
val modifiedProblems =
|
|
||||||
allProblems
|
|
||||||
.filter { problem ->
|
|
||||||
parseISO8601(problem.updatedAt)?.after(lastSyncDate) == true
|
|
||||||
}
|
|
||||||
.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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val allSessions = repository.getAllSessions().first()
|
|
||||||
val modifiedSessions =
|
|
||||||
allSessions
|
|
||||||
.filter { session ->
|
|
||||||
parseISO8601(session.updatedAt)?.after(lastSyncDate) == true
|
|
||||||
}
|
|
||||||
.map { BackupClimbSession.fromClimbSession(it) }
|
|
||||||
|
|
||||||
val allAttempts = repository.getAllAttempts().first()
|
|
||||||
val modifiedAttempts =
|
|
||||||
allAttempts
|
|
||||||
.filter { attempt ->
|
|
||||||
parseISO8601(attempt.createdAt)?.after(lastSyncDate) == true
|
|
||||||
}
|
|
||||||
.map { BackupAttempt.fromAttempt(it) }
|
|
||||||
|
|
||||||
val allDeletions = repository.getDeletedItems()
|
|
||||||
val modifiedDeletions =
|
|
||||||
allDeletions.filter { item ->
|
|
||||||
parseISO8601(item.deletedAt)?.after(lastSyncDate) == true
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.d(
|
|
||||||
TAG,
|
|
||||||
"Delta sync sending: gyms=${modifiedGyms.size}, problems=${modifiedProblems.size}, sessions=${modifiedSessions.size}, attempts=${modifiedAttempts.size}, deletions=${modifiedDeletions.size}"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Create delta request
|
|
||||||
val deltaRequest =
|
|
||||||
DeltaSyncRequest(
|
|
||||||
lastSyncTime = lastSyncTimeStr,
|
|
||||||
gyms = modifiedGyms,
|
|
||||||
problems = modifiedProblems,
|
|
||||||
sessions = modifiedSessions,
|
|
||||||
attempts = modifiedAttempts,
|
|
||||||
deletedItems = modifiedDeletions
|
|
||||||
)
|
|
||||||
|
|
||||||
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 deltaResponse =
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
try {
|
|
||||||
httpClient.newCall(request).execute().use { response ->
|
|
||||||
if (response.isSuccessful) {
|
|
||||||
val body = response.body?.string()
|
|
||||||
if (!body.isNullOrEmpty()) {
|
|
||||||
json.decodeFromString(DeltaSyncResponse.serializer(), body)
|
|
||||||
} else {
|
|
||||||
throw SyncException.InvalidResponse("Empty response body")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
handleHttpError(response.code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: IOException) {
|
|
||||||
throw SyncException.NetworkError(e.message ?: "Network error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.d(
|
|
||||||
TAG,
|
|
||||||
"Delta sync received: gyms=${deltaResponse.gyms.size}, problems=${deltaResponse.problems.size}, sessions=${deltaResponse.sessions.size}, attempts=${deltaResponse.attempts.size}, deletions=${deltaResponse.deletedItems.size}"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Apply server changes to local data
|
|
||||||
applyDeltaResponse(deltaResponse)
|
|
||||||
|
|
||||||
// Sync only modified problem images
|
|
||||||
syncModifiedImages(modifiedProblems)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseISO8601(dateString: String): Date? {
|
|
||||||
return try {
|
|
||||||
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
|
|
||||||
format.parse(dateString)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun applyDeltaResponse(response: DeltaSyncResponse) {
|
|
||||||
// Temporarily disable auto-sync to prevent recursive sync triggers
|
|
||||||
repository.setAutoSyncCallback(null)
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Merge and apply deletions first to prevent resurrection
|
|
||||||
val allDeletions = repository.getDeletedItems() + response.deletedItems
|
|
||||||
val uniqueDeletions = allDeletions.distinctBy { "${it.type}:${it.id}" }
|
|
||||||
|
|
||||||
Log.d(TAG, "Applying ${uniqueDeletions.size} deletion records before merging data")
|
|
||||||
applyDeletions(uniqueDeletions)
|
|
||||||
|
|
||||||
// Build deleted item lookup set
|
|
||||||
val deletedItemSet = uniqueDeletions.map { "${it.type}:${it.id}" }.toSet()
|
|
||||||
|
|
||||||
// Download images for new/modified problems from server
|
|
||||||
val imagePathMapping = mutableMapOf<String, String>()
|
|
||||||
for (problem in response.problems) {
|
|
||||||
if (deletedItemSet.contains("problem:${problem.id}")) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
problem.imagePaths?.forEach { imagePath ->
|
|
||||||
val serverFilename = imagePath.substringAfterLast('/')
|
|
||||||
try {
|
|
||||||
val localImagePath = downloadImage(serverFilename)
|
|
||||||
if (localImagePath != null) {
|
|
||||||
imagePathMapping[imagePath] = localImagePath
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "Failed to download image $imagePath: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge gyms
|
|
||||||
val existingGyms = repository.getAllGyms().first()
|
|
||||||
for (backupGym in response.gyms) {
|
|
||||||
if (deletedItemSet.contains("gym:${backupGym.id}")) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
val existing = existingGyms.find { it.id == backupGym.id }
|
|
||||||
if (existing == null || backupGym.updatedAt >= existing.updatedAt) {
|
|
||||||
val gym = backupGym.toGym()
|
|
||||||
if (existing != null) {
|
|
||||||
repository.updateGym(gym)
|
|
||||||
} else {
|
|
||||||
repository.insertGym(gym)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge problems
|
|
||||||
val existingProblems = repository.getAllProblems().first()
|
|
||||||
for (backupProblem in response.problems) {
|
|
||||||
if (deletedItemSet.contains("problem:${backupProblem.id}")) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
val updatedImagePaths =
|
|
||||||
backupProblem.imagePaths?.map { oldPath ->
|
|
||||||
imagePathMapping[oldPath] ?: oldPath
|
|
||||||
}
|
|
||||||
val problemToMerge = backupProblem.copy(imagePaths = updatedImagePaths)
|
|
||||||
val problem = problemToMerge.toProblem()
|
|
||||||
|
|
||||||
val existing = existingProblems.find { it.id == backupProblem.id }
|
|
||||||
if (existing == null || backupProblem.updatedAt >= existing.updatedAt) {
|
|
||||||
if (existing != null) {
|
|
||||||
repository.updateProblem(problem)
|
|
||||||
} else {
|
|
||||||
repository.insertProblem(problem)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge sessions
|
|
||||||
val existingSessions = repository.getAllSessions().first()
|
|
||||||
for (backupSession in response.sessions) {
|
|
||||||
if (deletedItemSet.contains("session:${backupSession.id}")) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
val session = backupSession.toClimbSession()
|
|
||||||
val existing = existingSessions.find { it.id == backupSession.id }
|
|
||||||
if (existing == null || backupSession.updatedAt >= existing.updatedAt) {
|
|
||||||
if (existing != null) {
|
|
||||||
repository.updateSession(session)
|
|
||||||
} else {
|
|
||||||
repository.insertSession(session)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge attempts
|
|
||||||
val existingAttempts = repository.getAllAttempts().first()
|
|
||||||
for (backupAttempt in response.attempts) {
|
|
||||||
if (deletedItemSet.contains("attempt:${backupAttempt.id}")) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
val attempt = backupAttempt.toAttempt()
|
|
||||||
val existing = existingAttempts.find { it.id == backupAttempt.id }
|
|
||||||
if (existing == null || backupAttempt.createdAt >= existing.createdAt) {
|
|
||||||
if (existing != null) {
|
|
||||||
repository.updateAttempt(attempt)
|
|
||||||
} else {
|
|
||||||
repository.insertAttempt(attempt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Apply deletions again for safety
|
|
||||||
applyDeletions(uniqueDeletions)
|
|
||||||
|
|
||||||
// Update deletion records
|
|
||||||
repository.clearDeletedItems()
|
|
||||||
uniqueDeletions.forEach { repository.trackDeletion(it.id, it.type) }
|
|
||||||
} finally {
|
|
||||||
// Re-enable auto-sync
|
|
||||||
repository.setAutoSyncCallback { serviceScope.launch { triggerAutoSync() } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun applyDeletions(
|
|
||||||
deletions: List<com.atridad.ascently.data.format.DeletedItem>
|
|
||||||
) {
|
|
||||||
val existingGyms = repository.getAllGyms().first()
|
|
||||||
val existingProblems = repository.getAllProblems().first()
|
|
||||||
val existingSessions = repository.getAllSessions().first()
|
|
||||||
val existingAttempts = repository.getAllAttempts().first()
|
|
||||||
|
|
||||||
for (item in deletions) {
|
|
||||||
when (item.type) {
|
|
||||||
"gym" -> {
|
|
||||||
existingGyms.find { it.id == item.id }?.let { repository.deleteGym(it) }
|
|
||||||
}
|
|
||||||
"problem" -> {
|
|
||||||
existingProblems.find { it.id == item.id }?.let { repository.deleteProblem(it) }
|
|
||||||
}
|
|
||||||
"session" -> {
|
|
||||||
existingSessions.find { it.id == item.id }?.let { repository.deleteSession(it) }
|
|
||||||
}
|
|
||||||
"attempt" -> {
|
|
||||||
existingAttempts.find { it.id == item.id }?.let { repository.deleteAttempt(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun syncModifiedImages(modifiedProblems: List<BackupProblem>) {
|
|
||||||
if (modifiedProblems.isEmpty()) return
|
|
||||||
|
|
||||||
Log.d(TAG, "Syncing images for ${modifiedProblems.size} modified problems")
|
|
||||||
|
|
||||||
for (backupProblem in modifiedProblems) {
|
|
||||||
backupProblem.imagePaths?.forEach { imagePath ->
|
|
||||||
val filename = imagePath.substringAfterLast('/')
|
|
||||||
uploadImage(imagePath, filename)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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(backup).toRequestBody("application/json".toMediaType())
|
|
||||||
|
|
||||||
val request =
|
|
||||||
Request.Builder()
|
|
||||||
.url("$serverUrl/sync")
|
|
||||||
.header("Authorization", "Bearer $authToken")
|
|
||||||
.put(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() {
|
suspend fun testConnection() {
|
||||||
if (!_isConfigured.value) {
|
|
||||||
_isConnected.value = false
|
|
||||||
_syncError.value = "Server URL or Auth Token is not set."
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_isTesting.value = true
|
_isTesting.value = true
|
||||||
_syncError.value = null
|
_syncError.value = null
|
||||||
|
|
||||||
val request =
|
|
||||||
Request.Builder()
|
|
||||||
.url("$serverUrl/sync")
|
|
||||||
.header("Authorization", "Bearer $authToken")
|
|
||||||
.head()
|
|
||||||
.build()
|
|
||||||
try {
|
try {
|
||||||
withContext(Dispatchers.IO) {
|
provider.testConnection()
|
||||||
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) {
|
} catch (e: Exception) {
|
||||||
_isConnected.value = false
|
|
||||||
_syncError.value = "Connection error: ${e.message}"
|
_syncError.value = "Connection error: ${e.message}"
|
||||||
|
throw e
|
||||||
} finally {
|
} finally {
|
||||||
sharedPreferences.edit { putBoolean(Keys.IS_CONNECTED, _isConnected.value) }
|
|
||||||
_isTesting.value = false
|
_isTesting.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun triggerAutoSync() {
|
fun triggerAutoSync() {
|
||||||
if (!_isConfigured.value || !_isConnected.value || !_isAutoSyncEnabled.value) {
|
if (!isConfiguredFlow.value || !isConnected.value || !_isAutoSyncEnabled.value) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (_isSyncing.value) {
|
if (_isSyncing.value) {
|
||||||
@@ -798,7 +141,7 @@ class SyncService(private val context: Context, private val repository: ClimbRep
|
|||||||
try {
|
try {
|
||||||
syncWithServer()
|
syncWithServer()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Auto-sync failed", e)
|
AppLogger.e(TAG, e) { "Auto-sync failed" }
|
||||||
}
|
}
|
||||||
if (pendingChanges) {
|
if (pendingChanges) {
|
||||||
pendingChanges = false
|
pendingChanges = false
|
||||||
@@ -809,29 +152,9 @@ class SyncService(private val context: Context, private val repository: ClimbRep
|
|||||||
|
|
||||||
fun clearConfiguration() {
|
fun clearConfiguration() {
|
||||||
syncJob?.cancel()
|
syncJob?.cancel()
|
||||||
serverUrl = ""
|
provider.disconnect()
|
||||||
authToken = ""
|
|
||||||
setAutoSyncEnabled(true)
|
setAutoSyncEnabled(true)
|
||||||
_lastSyncTime.value = null
|
_lastSyncTime.value = null
|
||||||
_isConnected.value = false
|
|
||||||
_syncError.value = null
|
_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.")
|
|
||||||
|
|
||||||
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")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -11,26 +11,26 @@ val bottomNavigationItems =
|
|||||||
BottomNavigationItem(
|
BottomNavigationItem(
|
||||||
screen = Screen.Sessions,
|
screen = Screen.Sessions,
|
||||||
icon = Icons.Default.PlayArrow,
|
icon = Icons.Default.PlayArrow,
|
||||||
label = "Sessions"
|
label = "Sessions",
|
||||||
),
|
),
|
||||||
BottomNavigationItem(
|
BottomNavigationItem(
|
||||||
screen = Screen.Problems,
|
screen = Screen.Problems,
|
||||||
icon = Icons.Default.Star,
|
icon = Icons.Default.Star,
|
||||||
label = "Problems"
|
label = "Problems",
|
||||||
),
|
),
|
||||||
BottomNavigationItem(
|
BottomNavigationItem(
|
||||||
screen = Screen.Analytics,
|
screen = Screen.Analytics,
|
||||||
icon = Icons.Default.Info,
|
icon = Icons.Default.Info,
|
||||||
label = "Analytics"
|
label = "Analytics",
|
||||||
),
|
),
|
||||||
BottomNavigationItem(
|
BottomNavigationItem(
|
||||||
screen = Screen.Gyms,
|
screen = Screen.Gyms,
|
||||||
icon = Icons.Default.LocationOn,
|
icon = Icons.Default.LocationOn,
|
||||||
label = "Gyms"
|
label = "Gyms",
|
||||||
),
|
),
|
||||||
BottomNavigationItem(
|
BottomNavigationItem(
|
||||||
screen = Screen.Settings,
|
screen = Screen.Settings,
|
||||||
icon = Icons.Default.Settings,
|
icon = Icons.Default.Settings,
|
||||||
label = "Settings"
|
label = "Settings",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,18 +6,22 @@ import android.app.PendingIntent
|
|||||||
import android.app.Service
|
import android.app.Service
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import com.atridad.ascently.MainActivity
|
import com.atridad.ascently.MainActivity
|
||||||
import com.atridad.ascently.R
|
import com.atridad.ascently.R
|
||||||
import com.atridad.ascently.data.database.AscentlyDatabase
|
import com.atridad.ascently.data.database.AscentlyDatabase
|
||||||
import com.atridad.ascently.data.repository.ClimbRepository
|
import com.atridad.ascently.data.repository.ClimbRepository
|
||||||
|
import com.atridad.ascently.utils.AppLogger
|
||||||
import com.atridad.ascently.widget.ClimbStatsWidgetProvider
|
import com.atridad.ascently.widget.ClimbStatsWidgetProvider
|
||||||
import java.time.LocalDateTime
|
|
||||||
import java.time.temporal.ChronoUnit
|
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.flow.firstOrNull
|
import kotlinx.coroutines.flow.firstOrNull
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.temporal.ChronoUnit
|
||||||
|
|
||||||
class SessionTrackingService : Service() {
|
class SessionTrackingService : Service() {
|
||||||
|
|
||||||
@@ -29,6 +33,7 @@ class SessionTrackingService : Service() {
|
|||||||
private lateinit var notificationManager: NotificationManager
|
private lateinit var notificationManager: NotificationManager
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private const val LOG_TAG = "SessionTrackingService"
|
||||||
const val NOTIFICATION_ID = 1001
|
const val NOTIFICATION_ID = 1001
|
||||||
const val CHANNEL_ID = "session_tracking_channel"
|
const val CHANNEL_ID = "session_tracking_channel"
|
||||||
const val ACTION_START_SESSION = "start_session"
|
const val ACTION_START_SESSION = "start_session"
|
||||||
@@ -68,6 +73,7 @@ class SessionTrackingService : Service() {
|
|||||||
startSessionTracking(sessionId)
|
startSessionTracking(sessionId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ACTION_STOP_SESSION -> {
|
ACTION_STOP_SESSION -> {
|
||||||
val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)
|
val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
@@ -108,7 +114,7 @@ class SessionTrackingService : Service() {
|
|||||||
// Update widget when session tracking starts
|
// Update widget when session tracking starts
|
||||||
ClimbStatsWidgetProvider.updateAllWidgets(this)
|
ClimbStatsWidgetProvider.updateAllWidgets(this)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e(LOG_TAG, e) { "Failed to initialize session tracking notification" }
|
||||||
}
|
}
|
||||||
|
|
||||||
notificationJob =
|
notificationJob =
|
||||||
@@ -124,7 +130,7 @@ class SessionTrackingService : Service() {
|
|||||||
updateNotification(sessionId)
|
updateNotification(sessionId)
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e(LOG_TAG, e) { "Notification updater loop crashed" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,7 +155,7 @@ class SessionTrackingService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e(LOG_TAG, e) { "Session monitoring loop crashed" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,13 +184,13 @@ class SessionTrackingService : Service() {
|
|||||||
// Update widget when notification updates
|
// Update widget when notification updates
|
||||||
ClimbStatsWidgetProvider.updateAllWidgets(this)
|
ClimbStatsWidgetProvider.updateAllWidgets(this)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e(LOG_TAG, e) { "Failed to update notification; retrying in 10s" }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
delay(10000L)
|
delay(10000L)
|
||||||
createAndShowNotification(sessionId)
|
createAndShowNotification(sessionId)
|
||||||
} catch (retryException: Exception) {
|
} catch (retryException: Exception) {
|
||||||
retryException.printStackTrace()
|
AppLogger.e(LOG_TAG, retryException) { "Retrying notification update failed" }
|
||||||
stopSessionTracking()
|
stopSessionTracking()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -206,6 +212,54 @@ class SessionTrackingService : Service() {
|
|||||||
repository.getAttemptsBySession(sessionId).firstOrNull() ?: emptyList()
|
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 {
|
||||||
|
val start = LocalDateTime.parse(startTime)
|
||||||
|
val zoneId = ZoneId.systemDefault()
|
||||||
|
start.atZone(zoneId).toInstant().toEpochMilli()
|
||||||
|
} 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 =
|
val duration =
|
||||||
session.startTime?.let { startTime ->
|
session.startTime?.let { startTime ->
|
||||||
try {
|
try {
|
||||||
@@ -227,36 +281,20 @@ class SessionTrackingService : Service() {
|
|||||||
}
|
}
|
||||||
?: "Active"
|
?: "Active"
|
||||||
|
|
||||||
val notification =
|
notificationBuilder
|
||||||
NotificationCompat.Builder(this, CHANNEL_ID)
|
|
||||||
.setContentTitle("Climbing Session Active")
|
.setContentTitle("Climbing Session Active")
|
||||||
.setContentText(
|
.setContentText(
|
||||||
"${gym?.name ?: "Gym"} • $duration • ${attempts.size} attempts"
|
"${gym?.name ?: "Gym"} • $duration • ${attempts.size} attempts",
|
||||||
)
|
)
|
||||||
.setSmallIcon(R.drawable.ic_mountains)
|
}
|
||||||
.setOngoing(true)
|
|
||||||
.setAutoCancel(false)
|
val notification = notificationBuilder.build()
|
||||||
.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)
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
|
|
||||||
notificationManager.notify(NOTIFICATION_ID, notification)
|
notificationManager.notify(NOTIFICATION_ID, notification)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e(LOG_TAG, e) { "Failed to build session tracking notification" }
|
||||||
throw e
|
throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,7 +309,7 @@ class SessionTrackingService : Service() {
|
|||||||
this,
|
this,
|
||||||
0,
|
0,
|
||||||
intent,
|
intent,
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,7 +319,7 @@ class SessionTrackingService : Service() {
|
|||||||
this,
|
this,
|
||||||
1,
|
1,
|
||||||
intent,
|
intent,
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,7 +328,7 @@ class SessionTrackingService : Service() {
|
|||||||
NotificationChannel(
|
NotificationChannel(
|
||||||
CHANNEL_ID,
|
CHANNEL_ID,
|
||||||
"Session Tracking",
|
"Session Tracking",
|
||||||
NotificationManager.IMPORTANCE_DEFAULT
|
NotificationManager.IMPORTANCE_DEFAULT,
|
||||||
)
|
)
|
||||||
.apply {
|
.apply {
|
||||||
description = "Shows active climbing session information"
|
description = "Shows active climbing session information"
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import com.atridad.ascently.ui.components.NotificationPermissionDialog
|
|||||||
import com.atridad.ascently.ui.screens.*
|
import com.atridad.ascently.ui.screens.*
|
||||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModelFactory
|
import com.atridad.ascently.ui.viewmodel.ClimbViewModelFactory
|
||||||
|
import com.atridad.ascently.utils.AppLogger
|
||||||
import com.atridad.ascently.utils.AppShortcutManager
|
import com.atridad.ascently.utils.AppShortcutManager
|
||||||
import com.atridad.ascently.utils.NotificationPermissionUtils
|
import com.atridad.ascently.utils.NotificationPermissionUtils
|
||||||
|
|
||||||
@@ -34,7 +35,7 @@ import com.atridad.ascently.utils.NotificationPermissionUtils
|
|||||||
fun AscentlyApp(
|
fun AscentlyApp(
|
||||||
shortcutAction: String? = null,
|
shortcutAction: String? = null,
|
||||||
lastUsedGymId: String? = null,
|
lastUsedGymId: String? = null,
|
||||||
onShortcutActionProcessed: () -> Unit = {}
|
onShortcutActionProcessed: () -> Unit = {},
|
||||||
) {
|
) {
|
||||||
val navController = rememberNavController()
|
val navController = rememberNavController()
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
@@ -52,7 +53,7 @@ fun AscentlyApp(
|
|||||||
|
|
||||||
val permissionLauncher =
|
val permissionLauncher =
|
||||||
rememberLauncherForActivityResult(
|
rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.RequestPermission()
|
contract = ActivityResultContracts.RequestPermission(),
|
||||||
) { isGranted: Boolean ->
|
) { isGranted: Boolean ->
|
||||||
if (!isGranted) {
|
if (!isGranted) {
|
||||||
showNotificationPermissionDialog = false
|
showNotificationPermissionDialog = false
|
||||||
@@ -89,7 +90,7 @@ fun AscentlyApp(
|
|||||||
context = context,
|
context = context,
|
||||||
hasActiveSession = activeSession != null,
|
hasActiveSession = activeSession != null,
|
||||||
hasGyms = gyms.isNotEmpty(),
|
hasGyms = gyms.isNotEmpty(),
|
||||||
lastUsedGym = if (activeSession == null && gyms.size > 1) lastUsedGym else null
|
lastUsedGym = if (activeSession == null && gyms.size > 1) lastUsedGym else null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +102,7 @@ fun AscentlyApp(
|
|||||||
launchSingleTop = true
|
launchSingleTop = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
AppShortcutManager.ACTION_END_SESSION -> {
|
AppShortcutManager.ACTION_END_SESSION -> {
|
||||||
navController.navigate(Screen.Sessions) {
|
navController.navigate(Screen.Sessions) {
|
||||||
popUpTo(0) { inclusive = true }
|
popUpTo(0) { inclusive = true }
|
||||||
@@ -114,25 +116,19 @@ fun AscentlyApp(
|
|||||||
|
|
||||||
LaunchedEffect(shortcutAction, activeSession, gyms, lastUsedGym) {
|
LaunchedEffect(shortcutAction, activeSession, gyms, lastUsedGym) {
|
||||||
if (shortcutAction == AppShortcutManager.ACTION_START_SESSION && gyms.isNotEmpty()) {
|
if (shortcutAction == AppShortcutManager.ACTION_START_SESSION && gyms.isNotEmpty()) {
|
||||||
android.util.Log.d(
|
AppLogger.d("AscentlyApp") { "Processing shortcut action: activeSession=$activeSession, gyms.size=${gyms.size}, lastUsedGymId=$lastUsedGymId, lastUsedGym=${lastUsedGym?.name}" }
|
||||||
"AscentlyApp",
|
|
||||||
"Processing shortcut action: activeSession=$activeSession, gyms.size=${gyms.size}, lastUsedGymId=$lastUsedGymId, lastUsedGym=${lastUsedGym?.name}"
|
|
||||||
)
|
|
||||||
|
|
||||||
if (activeSession == null) {
|
if (activeSession == null) {
|
||||||
if (NotificationPermissionUtils.shouldRequestNotificationPermission() &&
|
if (NotificationPermissionUtils.shouldRequestNotificationPermission() &&
|
||||||
!NotificationPermissionUtils.isNotificationPermissionGranted(
|
!NotificationPermissionUtils.isNotificationPermissionGranted(
|
||||||
context
|
context,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
android.util.Log.d("AscentlyApp", "Showing notification permission dialog")
|
AppLogger.d("AscentlyApp") { "Showing notification permission dialog" }
|
||||||
showNotificationPermissionDialog = true
|
showNotificationPermissionDialog = true
|
||||||
} else {
|
} else {
|
||||||
if (gyms.size == 1) {
|
if (gyms.size == 1) {
|
||||||
android.util.Log.d(
|
AppLogger.d("AscentlyApp") { "Starting session with single gym: ${gyms.first().name}" }
|
||||||
"AscentlyApp",
|
|
||||||
"Starting session with single gym: ${gyms.first().name}"
|
|
||||||
)
|
|
||||||
viewModel.startSession(context, gyms.first().id)
|
viewModel.startSession(context, gyms.first().id)
|
||||||
} else {
|
} else {
|
||||||
val targetGym =
|
val targetGym =
|
||||||
@@ -140,25 +136,16 @@ fun AscentlyApp(
|
|||||||
?: lastUsedGym
|
?: lastUsedGym
|
||||||
|
|
||||||
if (targetGym != null) {
|
if (targetGym != null) {
|
||||||
android.util.Log.d(
|
AppLogger.d("AscentlyApp") { "Starting session with target gym: ${targetGym.name}" }
|
||||||
"AscentlyApp",
|
|
||||||
"Starting session with target gym: ${targetGym.name}"
|
|
||||||
)
|
|
||||||
viewModel.startSession(context, targetGym.id)
|
viewModel.startSession(context, targetGym.id)
|
||||||
} else {
|
} else {
|
||||||
android.util.Log.d(
|
AppLogger.d("AscentlyApp") { "No target gym found, navigating to selection" }
|
||||||
"AscentlyApp",
|
|
||||||
"No target gym found, navigating to selection"
|
|
||||||
)
|
|
||||||
navController.navigate(Screen.AddEditSession())
|
navController.navigate(Screen.AddEditSession())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
android.util.Log.d(
|
AppLogger.d("AscentlyApp") { "Active session already exists: ${activeSession?.id}" }
|
||||||
"AscentlyApp",
|
|
||||||
"Active session already exists: ${activeSession?.id}"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onShortcutActionProcessed()
|
onShortcutActionProcessed()
|
||||||
@@ -173,20 +160,20 @@ fun AscentlyApp(
|
|||||||
fabConfig?.let { config ->
|
fabConfig?.let { config ->
|
||||||
FloatingActionButton(
|
FloatingActionButton(
|
||||||
onClick = config.onClick,
|
onClick = config.onClick,
|
||||||
containerColor = MaterialTheme.colorScheme.primary
|
containerColor = MaterialTheme.colorScheme.primary,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = config.icon,
|
imageVector = config.icon,
|
||||||
contentDescription = config.contentDescription
|
contentDescription = config.contentDescription,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
) { innerPadding ->
|
) { innerPadding ->
|
||||||
NavHost(
|
NavHost(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
startDestination = Screen.Sessions,
|
startDestination = Screen.Sessions,
|
||||||
modifier = Modifier.padding(innerPadding)
|
modifier = Modifier.padding(innerPadding),
|
||||||
) {
|
) {
|
||||||
composable<Screen.Sessions> {
|
composable<Screen.Sessions> {
|
||||||
LaunchedEffect(gyms, activeSession) {
|
LaunchedEffect(gyms, activeSession) {
|
||||||
@@ -200,14 +187,14 @@ fun AscentlyApp(
|
|||||||
.shouldRequestNotificationPermission() &&
|
.shouldRequestNotificationPermission() &&
|
||||||
!NotificationPermissionUtils
|
!NotificationPermissionUtils
|
||||||
.isNotificationPermissionGranted(
|
.isNotificationPermissionGranted(
|
||||||
context
|
context,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
showNotificationPermissionDialog = true
|
showNotificationPermissionDialog = true
|
||||||
} else {
|
} else {
|
||||||
navController.navigate(Screen.AddEditSession())
|
navController.navigate(Screen.AddEditSession())
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
@@ -217,7 +204,7 @@ fun AscentlyApp(
|
|||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onNavigateToSessionDetail = { sessionId ->
|
onNavigateToSessionDetail = { sessionId ->
|
||||||
navController.navigate(Screen.SessionDetail(sessionId))
|
navController.navigate(Screen.SessionDetail(sessionId))
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,7 +217,7 @@ fun AscentlyApp(
|
|||||||
contentDescription = "Add Problem",
|
contentDescription = "Add Problem",
|
||||||
onClick = {
|
onClick = {
|
||||||
navController.navigate(Screen.AddEditProblem())
|
navController.navigate(Screen.AddEditProblem())
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
@@ -240,7 +227,7 @@ fun AscentlyApp(
|
|||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onNavigateToProblemDetail = { problemId ->
|
onNavigateToProblemDetail = { problemId ->
|
||||||
navController.navigate(Screen.ProblemDetail(problemId))
|
navController.navigate(Screen.ProblemDetail(problemId))
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -255,14 +242,14 @@ fun AscentlyApp(
|
|||||||
FabConfig(
|
FabConfig(
|
||||||
icon = Icons.Default.Add,
|
icon = Icons.Default.Add,
|
||||||
contentDescription = "Add Gym",
|
contentDescription = "Add Gym",
|
||||||
onClick = { navController.navigate(Screen.AddEditGym()) }
|
onClick = { navController.navigate(Screen.AddEditGym()) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
GymsScreen(
|
GymsScreen(
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onNavigateToGymDetail = { gymId ->
|
onNavigateToGymDetail = { gymId ->
|
||||||
navController.navigate(Screen.GymDetail(gymId))
|
navController.navigate(Screen.GymDetail(gymId))
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,7 +267,7 @@ fun AscentlyApp(
|
|||||||
onNavigateBack = { navController.popBackStack() },
|
onNavigateBack = { navController.popBackStack() },
|
||||||
onNavigateToProblemDetail = { problemId ->
|
onNavigateToProblemDetail = { problemId ->
|
||||||
navController.navigate(Screen.ProblemDetail(problemId))
|
navController.navigate(Screen.ProblemDetail(problemId))
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,7 +280,7 @@ fun AscentlyApp(
|
|||||||
onNavigateBack = { navController.popBackStack() },
|
onNavigateBack = { navController.popBackStack() },
|
||||||
onNavigateToEdit = { problemId ->
|
onNavigateToEdit = { problemId ->
|
||||||
navController.navigate(Screen.AddEditProblem(problemId = problemId))
|
navController.navigate(Screen.AddEditProblem(problemId = problemId))
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -312,7 +299,7 @@ fun AscentlyApp(
|
|||||||
},
|
},
|
||||||
onNavigateToProblemDetail = { problemId ->
|
onNavigateToProblemDetail = { problemId ->
|
||||||
navController.navigate(Screen.ProblemDetail(problemId))
|
navController.navigate(Screen.ProblemDetail(problemId))
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,7 +309,7 @@ fun AscentlyApp(
|
|||||||
AddEditGymScreen(
|
AddEditGymScreen(
|
||||||
gymId = args.gymId,
|
gymId = args.gymId,
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onNavigateBack = { navController.popBackStack() }
|
onNavigateBack = { navController.popBackStack() },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,7 +320,7 @@ fun AscentlyApp(
|
|||||||
problemId = args.problemId,
|
problemId = args.problemId,
|
||||||
gymId = args.gymId,
|
gymId = args.gymId,
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onNavigateBack = { navController.popBackStack() }
|
onNavigateBack = { navController.popBackStack() },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -344,7 +331,7 @@ fun AscentlyApp(
|
|||||||
sessionId = args.sessionId,
|
sessionId = args.sessionId,
|
||||||
gymId = args.gymId,
|
gymId = args.gymId,
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onNavigateBack = { navController.popBackStack() }
|
onNavigateBack = { navController.popBackStack() },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -354,9 +341,9 @@ fun AscentlyApp(
|
|||||||
onDismiss = { showNotificationPermissionDialog = false },
|
onDismiss = { showNotificationPermissionDialog = false },
|
||||||
onRequestPermission = {
|
onRequestPermission = {
|
||||||
permissionLauncher.launch(
|
permissionLauncher.launch(
|
||||||
NotificationPermissionUtils.getNotificationPermissionString()
|
NotificationPermissionUtils.getNotificationPermissionString(),
|
||||||
)
|
)
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -390,7 +377,7 @@ fun AscentlyBottomNavigation(navController: NavHostController) {
|
|||||||
// Don't restore state - always start fresh when switching tabs
|
// Don't restore state - always start fresh when switching tabs
|
||||||
restoreState = false
|
restoreState = false
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -399,5 +386,5 @@ fun AscentlyBottomNavigation(navController: NavHostController) {
|
|||||||
data class FabConfig(
|
data class FabConfig(
|
||||||
val icon: androidx.compose.ui.graphics.vector.ImageVector,
|
val icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||||
val contentDescription: String,
|
val contentDescription: String,
|
||||||
val onClick: () -> Unit
|
val onClick: () -> Unit,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ fun ActiveSessionBanner(
|
|||||||
activeSession: ClimbSession?,
|
activeSession: ClimbSession?,
|
||||||
gym: Gym?,
|
gym: Gym?,
|
||||||
onSessionClick: () -> Unit,
|
onSessionClick: () -> Unit,
|
||||||
onEndSession: () -> Unit
|
onEndSession: () -> Unit,
|
||||||
) {
|
) {
|
||||||
if (activeSession != null) {
|
if (activeSession != null) {
|
||||||
// Add a timer that updates every second for real-time duration counting
|
// Add a timer that updates every second for real-time duration counting
|
||||||
@@ -40,32 +40,32 @@ fun ActiveSessionBanner(
|
|||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.clickable { onSessionClick() },
|
.clickable { onSessionClick() },
|
||||||
colors = CardDefaults.cardColors(
|
colors = CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.primaryContainer
|
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(16.dp),
|
.padding(16.dp),
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.PlayArrow,
|
Icons.Default.PlayArrow,
|
||||||
contentDescription = "Active session",
|
contentDescription = "Active session",
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier.size(16.dp)
|
modifier = Modifier.size(16.dp),
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Active Session",
|
text = "Active Session",
|
||||||
style = MaterialTheme.typography.titleSmall,
|
style = MaterialTheme.typography.titleSmall,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +74,7 @@ fun ActiveSessionBanner(
|
|||||||
Text(
|
Text(
|
||||||
text = gym?.name ?: "Unknown Gym",
|
text = gym?.name ?: "Unknown Gym",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
)
|
)
|
||||||
|
|
||||||
activeSession.startTime?.let { startTime ->
|
activeSession.startTime?.let { startTime ->
|
||||||
@@ -82,7 +82,7 @@ fun ActiveSessionBanner(
|
|||||||
Text(
|
Text(
|
||||||
text = duration,
|
text = duration,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f)
|
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,12 +91,12 @@ fun ActiveSessionBanner(
|
|||||||
onClick = onEndSession,
|
onClick = onEndSession,
|
||||||
colors = IconButtonDefaults.iconButtonColors(
|
colors = IconButtonDefaults.iconButtonColors(
|
||||||
containerColor = MaterialTheme.colorScheme.error,
|
containerColor = MaterialTheme.colorScheme.error,
|
||||||
contentColor = MaterialTheme.colorScheme.onError
|
contentColor = MaterialTheme.colorScheme.onError,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = CustomIcons.Stop(MaterialTheme.colorScheme.onError),
|
imageVector = CustomIcons.Stop(MaterialTheme.colorScheme.onError),
|
||||||
contentDescription = "End session"
|
contentDescription = "End session",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ data class BarChartStyle(
|
|||||||
val barColor: Color,
|
val barColor: Color,
|
||||||
val gridColor: Color,
|
val gridColor: Color,
|
||||||
val textColor: Color,
|
val textColor: Color,
|
||||||
val backgroundColor: Color
|
val backgroundColor: Color,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Custom Bar Chart for displaying grade distribution */
|
/** Custom Bar Chart for displaying grade distribution */
|
||||||
@@ -39,9 +39,9 @@ fun BarChart(
|
|||||||
barColor = MaterialTheme.colorScheme.primary,
|
barColor = MaterialTheme.colorScheme.primary,
|
||||||
gridColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
gridColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
||||||
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
backgroundColor = MaterialTheme.colorScheme.surface
|
backgroundColor = MaterialTheme.colorScheme.surface,
|
||||||
),
|
),
|
||||||
showGrid: Boolean = true
|
showGrid: Boolean = true,
|
||||||
) {
|
) {
|
||||||
val textMeasurer = rememberTextMeasurer()
|
val textMeasurer = rememberTextMeasurer()
|
||||||
val density = LocalDensity.current
|
val density = LocalDensity.current
|
||||||
@@ -70,7 +70,7 @@ fun BarChart(
|
|||||||
drawRect(
|
drawRect(
|
||||||
color = style.backgroundColor,
|
color = style.backgroundColor,
|
||||||
topLeft = Offset(padding, padding),
|
topLeft = Offset(padding, padding),
|
||||||
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight)
|
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Draw grid
|
// Draw grid
|
||||||
@@ -82,7 +82,7 @@ fun BarChart(
|
|||||||
gridColor = style.gridColor,
|
gridColor = style.gridColor,
|
||||||
maxValue = maxValue,
|
maxValue = maxValue,
|
||||||
textMeasurer = textMeasurer,
|
textMeasurer = textMeasurer,
|
||||||
textColor = style.textColor
|
textColor = style.textColor,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,7 +91,9 @@ fun BarChart(
|
|||||||
val barHeight =
|
val barHeight =
|
||||||
if (maxValue > 0) {
|
if (maxValue > 0) {
|
||||||
(dataPoint.value.toFloat() / maxValue.toFloat()) * chartHeight * 0.8f
|
(dataPoint.value.toFloat() / maxValue.toFloat()) * chartHeight * 0.8f
|
||||||
} else 0f
|
} else {
|
||||||
|
0f
|
||||||
|
}
|
||||||
|
|
||||||
val barX =
|
val barX =
|
||||||
padding +
|
padding +
|
||||||
@@ -103,7 +105,7 @@ fun BarChart(
|
|||||||
drawRect(
|
drawRect(
|
||||||
color = style.barColor,
|
color = style.barColor,
|
||||||
topLeft = Offset(barX, barY),
|
topLeft = Offset(barX, barY),
|
||||||
size = androidx.compose.ui.geometry.Size(barWidth, barHeight)
|
size = androidx.compose.ui.geometry.Size(barWidth, barHeight),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Draw value on bar
|
// Draw value on bar
|
||||||
@@ -131,7 +133,7 @@ fun BarChart(
|
|||||||
textMeasurer = textMeasurer,
|
textMeasurer = textMeasurer,
|
||||||
text = valueText,
|
text = valueText,
|
||||||
style = textStyle.copy(color = textColor),
|
style = textStyle.copy(color = textColor),
|
||||||
topLeft = Offset(barX + barWidth / 2f - textSize.size.width / 2f, textY)
|
topLeft = Offset(barX + barWidth / 2f - textSize.size.width / 2f, textY),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,8 +149,8 @@ fun BarChart(
|
|||||||
topLeft =
|
topLeft =
|
||||||
Offset(
|
Offset(
|
||||||
barX + barWidth / 2f - labelTextSize.size.width / 2f,
|
barX + barWidth / 2f - labelTextSize.size.width / 2f,
|
||||||
padding + chartHeight + 8.dp.toPx()
|
padding + chartHeight + 8.dp.toPx(),
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -162,7 +164,7 @@ private fun DrawScope.drawGrid(
|
|||||||
gridColor: Color,
|
gridColor: Color,
|
||||||
maxValue: Int,
|
maxValue: Int,
|
||||||
textMeasurer: TextMeasurer,
|
textMeasurer: TextMeasurer,
|
||||||
textColor: Color
|
textColor: Color,
|
||||||
) {
|
) {
|
||||||
val textStyle = TextStyle(color = textColor, fontSize = 10.sp)
|
val textStyle = TextStyle(color = textColor, fontSize = 10.sp)
|
||||||
|
|
||||||
@@ -186,7 +188,7 @@ private fun DrawScope.drawGrid(
|
|||||||
color = gridColor,
|
color = gridColor,
|
||||||
start = Offset(padding, y),
|
start = Offset(padding, y),
|
||||||
end = Offset(padding + chartWidth, y),
|
end = Offset(padding + chartWidth, y),
|
||||||
strokeWidth = 1.dp.toPx()
|
strokeWidth = 1.dp.toPx(),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Draw Y-axis label
|
// Draw Y-axis label
|
||||||
@@ -200,8 +202,8 @@ private fun DrawScope.drawGrid(
|
|||||||
topLeft =
|
topLeft =
|
||||||
Offset(
|
Offset(
|
||||||
padding - textSize.size.width - 8.dp.toPx(),
|
padding - textSize.size.width - 8.dp.toPx(),
|
||||||
y - textSize.size.height / 2f
|
y - textSize.size.height / 2f,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDis
|
|||||||
if (imagePaths.size > 1) {
|
if (imagePaths.size > 1) {
|
||||||
thumbnailListState.animateScrollToItem(
|
thumbnailListState.animateScrollToItem(
|
||||||
index = pagerState.currentPage,
|
index = pagerState.currentPage,
|
||||||
scrollOffset = -200
|
scrollOffset = -200,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDis
|
|||||||
Dialog(
|
Dialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties =
|
properties =
|
||||||
DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = true)
|
DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = true),
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize().background(Color.Black).systemBarsPadding()) {
|
Box(modifier = Modifier.fillMaxSize().background(Color.Black).systemBarsPadding()) {
|
||||||
// Main image pager
|
// Main image pager
|
||||||
@@ -58,26 +58,26 @@ fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDis
|
|||||||
imagePath = imagePaths[page],
|
imagePath = imagePaths[page],
|
||||||
contentDescription = "Full screen image",
|
contentDescription = "Full screen image",
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentScale = ContentScale.Fit
|
contentScale = ContentScale.Fit,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Top bar with back button and counter
|
// Top bar with back button and counter
|
||||||
Surface(
|
Surface(
|
||||||
modifier = Modifier.fillMaxWidth().align(Alignment.TopStart),
|
modifier = Modifier.fillMaxWidth().align(Alignment.TopStart),
|
||||||
color = Color.Black.copy(alpha = 0.6f)
|
color = Color.Black.copy(alpha = 0.6f),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier =
|
modifier =
|
||||||
Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 8.dp),
|
Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 8.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
// Back button
|
// Back button
|
||||||
IconButton(onClick = onDismiss) {
|
IconButton(onClick = onDismiss) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||||
contentDescription = "Close",
|
contentDescription = "Close",
|
||||||
tint = Color.White
|
tint = Color.White,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDis
|
|||||||
Text(
|
Text(
|
||||||
text = "${pagerState.currentPage + 1} / ${imagePaths.size}",
|
text = "${pagerState.currentPage + 1} / ${imagePaths.size}",
|
||||||
color = Color.White,
|
color = Color.White,
|
||||||
style = MaterialTheme.typography.bodyMedium
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,13 +100,13 @@ fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDis
|
|||||||
if (imagePaths.size > 1) {
|
if (imagePaths.size > 1) {
|
||||||
Surface(
|
Surface(
|
||||||
modifier = Modifier.fillMaxWidth().align(Alignment.BottomCenter),
|
modifier = Modifier.fillMaxWidth().align(Alignment.BottomCenter),
|
||||||
color = Color.Black.copy(alpha = 0.6f)
|
color = Color.Black.copy(alpha = 0.6f),
|
||||||
) {
|
) {
|
||||||
LazyRow(
|
LazyRow(
|
||||||
state = thumbnailListState,
|
state = thumbnailListState,
|
||||||
modifier = Modifier.padding(vertical = 12.dp),
|
modifier = Modifier.padding(vertical = 12.dp),
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
contentPadding = PaddingValues(horizontal = 16.dp)
|
contentPadding = PaddingValues(horizontal = 16.dp),
|
||||||
) {
|
) {
|
||||||
itemsIndexed(imagePaths) { index, imagePath ->
|
itemsIndexed(imagePaths) { index, imagePath ->
|
||||||
val isSelected = index == pagerState.currentPage
|
val isSelected = index == pagerState.currentPage
|
||||||
@@ -119,13 +119,13 @@ fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDis
|
|||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
pagerState.animateScrollToPage(index)
|
pagerState.animateScrollToPage(index)
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
) {
|
) {
|
||||||
OrientationAwareImage(
|
OrientationAwareImage(
|
||||||
imagePath = imagePath,
|
imagePath = imagePath,
|
||||||
contentDescription = "Thumbnail ${index + 1}",
|
contentDescription = "Thumbnail ${index + 1}",
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentScale = ContentScale.Crop
|
contentScale = ContentScale.Crop,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Selection indicator
|
// Selection indicator
|
||||||
@@ -135,20 +135,20 @@ fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDis
|
|||||||
Modifier.fillMaxSize()
|
Modifier.fillMaxSize()
|
||||||
.background(
|
.background(
|
||||||
Color.White.copy(alpha = 0.3f),
|
Color.White.copy(alpha = 0.3f),
|
||||||
RoundedCornerShape(8.dp)
|
RoundedCornerShape(8.dp),
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
Box(
|
Box(
|
||||||
modifier =
|
modifier =
|
||||||
Modifier.fillMaxSize()
|
Modifier.fillMaxSize()
|
||||||
.background(
|
.background(
|
||||||
Color.Transparent,
|
Color.Transparent,
|
||||||
RoundedCornerShape(8.dp)
|
RoundedCornerShape(8.dp),
|
||||||
)
|
)
|
||||||
.clip(RoundedCornerShape(8.dp))
|
.clip(RoundedCornerShape(8.dp))
|
||||||
.background(
|
.background(
|
||||||
Color.White.copy(alpha = 0.2f)
|
Color.White.copy(alpha = 0.2f),
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ fun ImageDisplay(
|
|||||||
imagePaths: List<String>,
|
imagePaths: List<String>,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
imageSize: Int = 120,
|
imageSize: Int = 120,
|
||||||
onImageClick: ((Int) -> Unit)? = null
|
onImageClick: ((Int) -> Unit)? = null,
|
||||||
) {
|
) {
|
||||||
LocalContext.current
|
LocalContext.current
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ fun ImageDisplay(
|
|||||||
.clickable(enabled = onImageClick != null) {
|
.clickable(enabled = onImageClick != null) {
|
||||||
onImageClick?.invoke(index)
|
onImageClick?.invoke(index)
|
||||||
},
|
},
|
||||||
contentScale = ContentScale.Crop
|
contentScale = ContentScale.Crop,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,14 +46,14 @@ fun ImageDisplaySection(
|
|||||||
imagePaths: List<String>,
|
imagePaths: List<String>,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
title: String = "Photos",
|
title: String = "Photos",
|
||||||
onImageClick: ((Int) -> Unit)? = null
|
onImageClick: ((Int) -> Unit)? = null,
|
||||||
) {
|
) {
|
||||||
if (imagePaths.isNotEmpty()) {
|
if (imagePaths.isNotEmpty()) {
|
||||||
Column(modifier = modifier) {
|
Column(modifier = modifier) {
|
||||||
Text(
|
Text(
|
||||||
text = title,
|
text = title,
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurface
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ fun ImagePicker(
|
|||||||
imageUris: List<String>,
|
imageUris: List<String>,
|
||||||
onImagesChanged: (List<String>) -> Unit,
|
onImagesChanged: (List<String>) -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
maxImages: Int = 5
|
maxImages: Int = 5,
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
var tempImageUris by remember { mutableStateOf(imageUris) }
|
var tempImageUris by remember { mutableStateOf(imageUris) }
|
||||||
@@ -45,7 +45,7 @@ fun ImagePicker(
|
|||||||
// Image picker launcher
|
// Image picker launcher
|
||||||
val imagePickerLauncher =
|
val imagePickerLauncher =
|
||||||
rememberLauncherForActivityResult(
|
rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.GetMultipleContents()
|
contract = ActivityResultContracts.GetMultipleContents(),
|
||||||
) { uris ->
|
) { uris ->
|
||||||
if (uris.isNotEmpty()) {
|
if (uris.isNotEmpty()) {
|
||||||
val currentCount = tempImageUris.size
|
val currentCount = tempImageUris.size
|
||||||
@@ -88,7 +88,7 @@ fun ImagePicker(
|
|||||||
// Camera permission launcher
|
// Camera permission launcher
|
||||||
val cameraPermissionLauncher =
|
val cameraPermissionLauncher =
|
||||||
rememberLauncherForActivityResult(
|
rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.RequestPermission()
|
contract = ActivityResultContracts.RequestPermission(),
|
||||||
) { isGranted ->
|
) { isGranted ->
|
||||||
if (isGranted) {
|
if (isGranted) {
|
||||||
// Create image file for camera
|
// Create image file for camera
|
||||||
@@ -97,7 +97,7 @@ fun ImagePicker(
|
|||||||
FileProvider.getUriForFile(
|
FileProvider.getUriForFile(
|
||||||
context,
|
context,
|
||||||
"${context.packageName}.fileprovider",
|
"${context.packageName}.fileprovider",
|
||||||
imageFile
|
imageFile,
|
||||||
)
|
)
|
||||||
cameraImageUri = uri
|
cameraImageUri = uri
|
||||||
cameraLauncher.launch(uri)
|
cameraLauncher.launch(uri)
|
||||||
@@ -108,11 +108,11 @@ fun ImagePicker(
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "Photos (${tempImageUris.size}/$maxImages)",
|
text = "Photos (${tempImageUris.size}/$maxImages)",
|
||||||
style = MaterialTheme.typography.titleMedium
|
style = MaterialTheme.typography.titleMedium,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (tempImageUris.size < maxImages) {
|
if (tempImageUris.size < maxImages) {
|
||||||
@@ -120,7 +120,7 @@ fun ImagePicker(
|
|||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Add,
|
Icons.Default.Add,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(16.dp)
|
modifier = Modifier.size(16.dp),
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(4.dp))
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
Text("Add Photos")
|
Text("Add Photos")
|
||||||
@@ -142,7 +142,7 @@ fun ImagePicker(
|
|||||||
|
|
||||||
// Delete the image file
|
// Delete the image file
|
||||||
ImageUtils.deleteImage(context, imagePath)
|
ImageUtils.deleteImage(context, imagePath)
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,22 +154,22 @@ fun ImagePicker(
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Add,
|
Icons.Default.Add,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Add photos of this problem",
|
text = "Add photos of this problem",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,12 +188,12 @@ fun ImagePicker(
|
|||||||
onClick = {
|
onClick = {
|
||||||
showImageSourceDialog = false
|
showImageSourceDialog = false
|
||||||
imagePickerLauncher.launch("image/*")
|
imagePickerLauncher.launch("image/*")
|
||||||
}
|
},
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.PhotoLibrary,
|
Icons.Default.PhotoLibrary,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(16.dp)
|
modifier = Modifier.size(16.dp),
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(4.dp))
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
Text("Gallery")
|
Text("Gallery")
|
||||||
@@ -202,9 +202,10 @@ fun ImagePicker(
|
|||||||
TextButton(
|
TextButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
showImageSourceDialog = false
|
showImageSourceDialog = false
|
||||||
when (ContextCompat.checkSelfPermission(
|
when (
|
||||||
|
ContextCompat.checkSelfPermission(
|
||||||
context,
|
context,
|
||||||
Manifest.permission.CAMERA
|
Manifest.permission.CAMERA,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
PackageManager.PERMISSION_GRANTED -> {
|
PackageManager.PERMISSION_GRANTED -> {
|
||||||
@@ -214,23 +215,23 @@ fun ImagePicker(
|
|||||||
FileProvider.getUriForFile(
|
FileProvider.getUriForFile(
|
||||||
context,
|
context,
|
||||||
"${context.packageName}.fileprovider",
|
"${context.packageName}.fileprovider",
|
||||||
imageFile
|
imageFile,
|
||||||
)
|
)
|
||||||
cameraImageUri = uri
|
cameraImageUri = uri
|
||||||
cameraLauncher.launch(uri)
|
cameraLauncher.launch(uri)
|
||||||
}
|
}
|
||||||
else -> {
|
else -> {
|
||||||
cameraPermissionLauncher.launch(
|
cameraPermissionLauncher.launch(
|
||||||
Manifest.permission.CAMERA
|
Manifest.permission.CAMERA,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.CameraAlt,
|
Icons.Default.CameraAlt,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(16.dp)
|
modifier = Modifier.size(16.dp),
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(4.dp))
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
Text("Camera")
|
Text("Camera")
|
||||||
@@ -239,7 +240,7 @@ fun ImagePicker(
|
|||||||
},
|
},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
TextButton(onClick = { showImageSourceDialog = false }) { Text("Cancel") }
|
TextButton(onClick = { showImageSourceDialog = false }) { Text("Cancel") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -262,7 +263,7 @@ private fun ImageItem(imagePath: String, onRemove: () -> Unit, modifier: Modifie
|
|||||||
imagePath = imagePath,
|
imagePath = imagePath,
|
||||||
contentDescription = "Problem photo",
|
contentDescription = "Problem photo",
|
||||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||||
contentScale = ContentScale.Crop
|
contentScale = ContentScale.Crop,
|
||||||
)
|
)
|
||||||
|
|
||||||
IconButton(onClick = onRemove, modifier = Modifier.align(Alignment.TopEnd).size(24.dp)) {
|
IconButton(onClick = onRemove, modifier = Modifier.align(Alignment.TopEnd).size(24.dp)) {
|
||||||
@@ -270,14 +271,14 @@ private fun ImageItem(imagePath: String, onRemove: () -> Unit, modifier: Modifie
|
|||||||
shape = RoundedCornerShape(12.dp),
|
shape = RoundedCornerShape(12.dp),
|
||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.errorContainer
|
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Close,
|
Icons.Default.Close,
|
||||||
contentDescription = "Remove photo",
|
contentDescription = "Remove photo",
|
||||||
modifier = Modifier.fillMaxSize().padding(2.dp),
|
modifier = Modifier.fillMaxSize().padding(2.dp),
|
||||||
tint = MaterialTheme.colorScheme.onErrorContainer
|
tint = MaterialTheme.colorScheme.onErrorContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import androidx.compose.ui.unit.sp
|
|||||||
data class ChartDataPoint(
|
data class ChartDataPoint(
|
||||||
val x: Float,
|
val x: Float,
|
||||||
val y: Float,
|
val y: Float,
|
||||||
val label: String? = null
|
val label: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,7 +37,7 @@ data class ChartStyle(
|
|||||||
val lineWidth: Float = 3f,
|
val lineWidth: Float = 3f,
|
||||||
val gridColor: Color,
|
val gridColor: Color,
|
||||||
val textColor: Color,
|
val textColor: Color,
|
||||||
val backgroundColor: Color
|
val backgroundColor: Color,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -52,11 +52,11 @@ fun LineChart(
|
|||||||
fillColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
|
fillColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
|
||||||
gridColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
gridColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
||||||
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
backgroundColor = MaterialTheme.colorScheme.surface
|
backgroundColor = MaterialTheme.colorScheme.surface,
|
||||||
),
|
),
|
||||||
showGrid: Boolean = true,
|
showGrid: Boolean = true,
|
||||||
xAxisFormatter: (Float) -> String = { it.toString() },
|
xAxisFormatter: (Float) -> String = { it.toString() },
|
||||||
yAxisFormatter: (Float) -> String = { it.toString() }
|
yAxisFormatter: (Float) -> String = { it.toString() },
|
||||||
) {
|
) {
|
||||||
val textMeasurer = rememberTextMeasurer()
|
val textMeasurer = rememberTextMeasurer()
|
||||||
val density = LocalDensity.current
|
val density = LocalDensity.current
|
||||||
@@ -65,7 +65,7 @@ fun LineChart(
|
|||||||
Canvas(
|
Canvas(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(16.dp)
|
.padding(16.dp),
|
||||||
) {
|
) {
|
||||||
if (data.isEmpty()) return@Canvas
|
if (data.isEmpty()) return@Canvas
|
||||||
|
|
||||||
@@ -102,7 +102,7 @@ fun LineChart(
|
|||||||
drawRect(
|
drawRect(
|
||||||
color = style.backgroundColor,
|
color = style.backgroundColor,
|
||||||
topLeft = Offset(padding, padding),
|
topLeft = Offset(padding, padding),
|
||||||
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight)
|
size = androidx.compose.ui.geometry.Size(chartWidth, chartHeight),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Draw grid
|
// Draw grid
|
||||||
@@ -120,7 +120,7 @@ fun LineChart(
|
|||||||
textColor = style.textColor,
|
textColor = style.textColor,
|
||||||
xAxisFormatter = xAxisFormatter,
|
xAxisFormatter = xAxisFormatter,
|
||||||
yAxisFormatter = yAxisFormatter,
|
yAxisFormatter = yAxisFormatter,
|
||||||
actualDataPoints = data
|
actualDataPoints = data,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +130,7 @@ fun LineChart(
|
|||||||
points = screenPoints,
|
points = screenPoints,
|
||||||
padding = padding,
|
padding = padding,
|
||||||
chartHeight = chartHeight,
|
chartHeight = chartHeight,
|
||||||
fillColor = style.fillColor
|
fillColor = style.fillColor,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,7 +139,7 @@ fun LineChart(
|
|||||||
drawLine(
|
drawLine(
|
||||||
points = screenPoints,
|
points = screenPoints,
|
||||||
lineColor = style.lineColor,
|
lineColor = style.lineColor,
|
||||||
lineWidth = style.lineWidth
|
lineWidth = style.lineWidth,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,20 +149,20 @@ fun LineChart(
|
|||||||
drawCircle(
|
drawCircle(
|
||||||
color = style.lineColor,
|
color = style.lineColor,
|
||||||
radius = 8f,
|
radius = 8f,
|
||||||
center = point
|
center = point,
|
||||||
)
|
)
|
||||||
// Draw inner circle (white center)
|
// Draw inner circle (white center)
|
||||||
drawCircle(
|
drawCircle(
|
||||||
color = style.backgroundColor,
|
color = style.backgroundColor,
|
||||||
radius = 5f,
|
radius = 5f,
|
||||||
center = point
|
center = point,
|
||||||
)
|
)
|
||||||
// Draw border for better visibility
|
// Draw border for better visibility
|
||||||
drawCircle(
|
drawCircle(
|
||||||
color = style.lineColor,
|
color = style.lineColor,
|
||||||
radius = 8f,
|
radius = 8f,
|
||||||
center = point,
|
center = point,
|
||||||
style = Stroke(width = 2f)
|
style = Stroke(width = 2f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,11 +182,11 @@ private fun DrawScope.drawGrid(
|
|||||||
textColor: Color,
|
textColor: Color,
|
||||||
xAxisFormatter: (Float) -> String,
|
xAxisFormatter: (Float) -> String,
|
||||||
yAxisFormatter: (Float) -> String,
|
yAxisFormatter: (Float) -> String,
|
||||||
actualDataPoints: List<ChartDataPoint>
|
actualDataPoints: List<ChartDataPoint>,
|
||||||
) {
|
) {
|
||||||
val textStyle = TextStyle(
|
val textStyle = TextStyle(
|
||||||
color = textColor,
|
color = textColor,
|
||||||
fontSize = 10.sp
|
fontSize = 10.sp,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Draw vertical grid lines (X-axis) - only at integer values for sessions
|
// Draw vertical grid lines (X-axis) - only at integer values for sessions
|
||||||
@@ -203,7 +203,7 @@ private fun DrawScope.drawGrid(
|
|||||||
color = gridColor,
|
color = gridColor,
|
||||||
start = Offset(x, padding),
|
start = Offset(x, padding),
|
||||||
end = Offset(x, padding + chartHeight),
|
end = Offset(x, padding + chartHeight),
|
||||||
strokeWidth = 1.dp.toPx()
|
strokeWidth = 1.dp.toPx(),
|
||||||
)
|
)
|
||||||
|
|
||||||
// X-axis labels removed per user request
|
// X-axis labels removed per user request
|
||||||
@@ -226,7 +226,7 @@ private fun DrawScope.drawGrid(
|
|||||||
color = gridColor,
|
color = gridColor,
|
||||||
start = Offset(padding, y),
|
start = Offset(padding, y),
|
||||||
end = Offset(padding + chartWidth, y),
|
end = Offset(padding + chartWidth, y),
|
||||||
strokeWidth = 1.dp.toPx()
|
strokeWidth = 1.dp.toPx(),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Draw label
|
// Draw label
|
||||||
@@ -238,8 +238,8 @@ private fun DrawScope.drawGrid(
|
|||||||
style = textStyle,
|
style = textStyle,
|
||||||
topLeft = Offset(
|
topLeft = Offset(
|
||||||
padding - textSize.size.width - 8.dp.toPx(),
|
padding - textSize.size.width - 8.dp.toPx(),
|
||||||
y - textSize.size.height / 2f
|
y - textSize.size.height / 2f,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -250,7 +250,7 @@ private fun DrawScope.drawAreaFill(
|
|||||||
points: List<Offset>,
|
points: List<Offset>,
|
||||||
padding: Float,
|
padding: Float,
|
||||||
chartHeight: Float,
|
chartHeight: Float,
|
||||||
fillColor: Color
|
fillColor: Color,
|
||||||
) {
|
) {
|
||||||
val bottomY = padding + chartHeight // This represents the bottom of the chart area
|
val bottomY = padding + chartHeight // This represents the bottom of the chart area
|
||||||
|
|
||||||
@@ -274,14 +274,14 @@ private fun DrawScope.drawAreaFill(
|
|||||||
|
|
||||||
drawPath(
|
drawPath(
|
||||||
path = path,
|
path = path,
|
||||||
color = fillColor
|
color = fillColor,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun DrawScope.drawLine(
|
private fun DrawScope.drawLine(
|
||||||
points: List<Offset>,
|
points: List<Offset>,
|
||||||
lineColor: Color,
|
lineColor: Color,
|
||||||
lineWidth: Float
|
lineWidth: Float,
|
||||||
) {
|
) {
|
||||||
val path = Path().apply {
|
val path = Path().apply {
|
||||||
moveTo(points.first().x, points.first().y)
|
moveTo(points.first().x, points.first().y)
|
||||||
@@ -296,7 +296,7 @@ private fun DrawScope.drawLine(
|
|||||||
style = Stroke(
|
style = Stroke(
|
||||||
width = lineWidth,
|
width = lineWidth,
|
||||||
cap = StrokeCap.Round,
|
cap = StrokeCap.Round,
|
||||||
join = StrokeJoin.Round
|
join = StrokeJoin.Round,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,21 +16,21 @@ import androidx.compose.ui.window.DialogProperties
|
|||||||
fun NotificationPermissionDialog(onDismiss: () -> Unit, onRequestPermission: () -> Unit) {
|
fun NotificationPermissionDialog(onDismiss: () -> Unit, onRequestPermission: () -> Unit) {
|
||||||
Dialog(
|
Dialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
|
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false),
|
||||||
) {
|
) {
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
shape = MaterialTheme.shapes.medium
|
shape = MaterialTheme.shapes.medium,
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.padding(24.dp),
|
modifier = Modifier.padding(24.dp),
|
||||||
horizontalAlignment = Alignment.CenterHorizontally
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Default.Notifications,
|
imageVector = Icons.Default.Notifications,
|
||||||
contentDescription = "Notifications",
|
contentDescription = "Notifications",
|
||||||
modifier = Modifier.size(48.dp),
|
modifier = Modifier.size(48.dp),
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
@@ -39,7 +39,7 @@ fun NotificationPermissionDialog(onDismiss: () -> Unit, onRequestPermission: ()
|
|||||||
text = "Enable Notifications",
|
text = "Enable Notifications",
|
||||||
style = MaterialTheme.typography.headlineSmall,
|
style = MaterialTheme.typography.headlineSmall,
|
||||||
fontWeight = MaterialTheme.typography.headlineSmall.fontWeight,
|
fontWeight = MaterialTheme.typography.headlineSmall.fontWeight,
|
||||||
textAlign = TextAlign.Center
|
textAlign = TextAlign.Center,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(12.dp))
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
@@ -49,14 +49,14 @@ fun NotificationPermissionDialog(onDismiss: () -> Unit, onRequestPermission: ()
|
|||||||
"Ascently needs notification permission to show your active climbing session. This helps you track your progress and ensures the session doesn't get interrupted.",
|
"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,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(24.dp))
|
Spacer(modifier = Modifier.height(24.dp))
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
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")
|
Text("Not Now")
|
||||||
@@ -67,7 +67,7 @@ fun NotificationPermissionDialog(onDismiss: () -> Unit, onRequestPermission: ()
|
|||||||
onRequestPermission()
|
onRequestPermission()
|
||||||
onDismiss()
|
onDismiss()
|
||||||
},
|
},
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f),
|
||||||
) { Text("Enable") }
|
) { Text("Enable") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,16 +16,16 @@ import androidx.compose.ui.platform.LocalContext
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.exifinterface.media.ExifInterface
|
import androidx.exifinterface.media.ExifInterface
|
||||||
import com.atridad.ascently.utils.ImageUtils
|
import com.atridad.ascently.utils.ImageUtils
|
||||||
import java.io.File
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun OrientationAwareImage(
|
fun OrientationAwareImage(
|
||||||
imagePath: String,
|
imagePath: String,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
contentDescription: String? = null,
|
contentDescription: String? = null,
|
||||||
contentScale: ContentScale = ContentScale.Fit
|
contentScale: ContentScale = ContentScale.Fit,
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
var imageBitmap by
|
var imageBitmap by
|
||||||
@@ -62,7 +62,7 @@ fun OrientationAwareImage(
|
|||||||
bitmap = bitmap,
|
bitmap = bitmap,
|
||||||
contentDescription = contentDescription,
|
contentDescription = contentDescription,
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentScale = contentScale
|
contentScale = contentScale,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,14 +71,14 @@ fun OrientationAwareImage(
|
|||||||
|
|
||||||
private fun correctImageOrientation(
|
private fun correctImageOrientation(
|
||||||
imageFile: File,
|
imageFile: File,
|
||||||
bitmap: android.graphics.Bitmap
|
bitmap: android.graphics.Bitmap,
|
||||||
): android.graphics.Bitmap {
|
): android.graphics.Bitmap {
|
||||||
return try {
|
return try {
|
||||||
val exif = ExifInterface(imageFile.absolutePath)
|
val exif = ExifInterface(imageFile.absolutePath)
|
||||||
val orientation =
|
val orientation =
|
||||||
exif.getAttributeInt(
|
exif.getAttributeInt(
|
||||||
ExifInterface.TAG_ORIENTATION,
|
ExifInterface.TAG_ORIENTATION,
|
||||||
ExifInterface.ORIENTATION_NORMAL
|
ExifInterface.ORIENTATION_NORMAL,
|
||||||
)
|
)
|
||||||
|
|
||||||
val matrix = Matrix()
|
val matrix = Matrix()
|
||||||
@@ -131,7 +131,7 @@ private fun correctImageOrientation(
|
|||||||
bitmap.width,
|
bitmap.width,
|
||||||
bitmap.height,
|
bitmap.height,
|
||||||
matrix,
|
matrix,
|
||||||
true
|
true,
|
||||||
)
|
)
|
||||||
if (rotatedBitmap != bitmap) {
|
if (rotatedBitmap != bitmap) {
|
||||||
bitmap.recycle()
|
bitmap.recycle()
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ fun SyncIndicator(isSyncing: StateFlow<Boolean>, modifier: Modifier = Modifier)
|
|||||||
visible = syncing,
|
visible = syncing,
|
||||||
enter = scaleIn() + fadeIn(),
|
enter = scaleIn() + fadeIn(),
|
||||||
exit = scaleOut() + fadeOut(),
|
exit = scaleOut() + fadeOut(),
|
||||||
modifier = modifier
|
modifier = modifier,
|
||||||
) {
|
) {
|
||||||
Box(
|
Box(
|
||||||
modifier =
|
modifier =
|
||||||
@@ -37,12 +37,12 @@ fun SyncIndicator(isSyncing: StateFlow<Boolean>, modifier: Modifier = Modifier)
|
|||||||
.clip(CircleShape)
|
.clip(CircleShape)
|
||||||
.background(MaterialTheme.colorScheme.primaryContainer, CircleShape)
|
.background(MaterialTheme.colorScheme.primaryContainer, CircleShape)
|
||||||
.padding(6.dp),
|
.padding(6.dp),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp,
|
strokeWidth = 2.dp,
|
||||||
color = MaterialTheme.colorScheme.primary
|
color = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
// Permission launcher
|
// Permission launcher
|
||||||
val permissionLauncher =
|
val permissionLauncher =
|
||||||
rememberLauncherForActivityResult(
|
rememberLauncherForActivityResult(
|
||||||
contract = healthConnectManager.getPermissionRequestContract()
|
contract = healthConnectManager.getPermissionRequestContract(),
|
||||||
) { _ ->
|
) { _ ->
|
||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
val allGranted = healthConnectManager.hasAllPermissions()
|
val allGranted = healthConnectManager.hasAllPermissions()
|
||||||
@@ -77,17 +77,17 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
shape = RoundedCornerShape(16.dp),
|
shape = RoundedCornerShape(16.dp),
|
||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.fillMaxWidth().padding(20.dp),
|
modifier = Modifier.fillMaxWidth().padding(20.dp),
|
||||||
horizontalAlignment = Alignment.CenterHorizontally
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
) {
|
) {
|
||||||
// Header with icon and title
|
// Header with icon and title
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Default.HealthAndSafety,
|
imageVector = Icons.Default.HealthAndSafety,
|
||||||
@@ -98,7 +98,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
MaterialTheme.colorScheme.primary
|
MaterialTheme.colorScheme.primary
|
||||||
} else {
|
} else {
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.width(12.dp))
|
Spacer(modifier = Modifier.width(12.dp))
|
||||||
@@ -108,7 +108,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
text = "Health Connect",
|
text = "Health Connect",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
@@ -126,7 +126,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
when {
|
when {
|
||||||
isLoading ->
|
isLoading ->
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||||
alpha = 0.7f
|
alpha = 0.7f,
|
||||||
)
|
)
|
||||||
|
|
||||||
!isCompatible -> MaterialTheme.colorScheme.error
|
!isCompatible -> MaterialTheme.colorScheme.error
|
||||||
@@ -139,9 +139,9 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
|
|
||||||
else ->
|
else ->
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||||
alpha = 0.7f
|
alpha = 0.7f,
|
||||||
)
|
)
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,7 +167,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = isHealthConnectAvailable && !isLoading && isCompatible
|
enabled = isHealthConnectAvailable && !isLoading && isCompatible,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +179,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
|
|
||||||
if (!hasPermissions) {
|
if (!hasPermissions) {
|
||||||
@@ -190,9 +190,9 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.errorContainer.copy(
|
MaterialTheme.colorScheme.errorContainer.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
@@ -200,7 +200,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
imageVector = Icons.Default.Warning,
|
imageVector = Icons.Default.Warning,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(20.dp),
|
modifier = Modifier.size(20.dp),
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
@@ -209,7 +209,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
text = "Permissions needed",
|
text = "Permissions needed",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = FontWeight.Medium,
|
fontWeight = FontWeight.Medium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,8 +221,8 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color =
|
color =
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||||
alpha = 0.8f
|
alpha = 0.8f,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -243,7 +243,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) { Text("Grant Permissions") }
|
) { Text("Grant Permissions") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -254,7 +254,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
"Sync your climbing sessions to Samsung Health, Google Fit, and other fitness apps through Health Connect.",
|
"Sync your climbing sessions to Samsung Health, Google Fit, and other fitness apps through Health Connect.",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
|
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
errorMessage?.let { error ->
|
errorMessage?.let { error ->
|
||||||
@@ -266,19 +266,19 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.errorContainer.copy(
|
MaterialTheme.colorScheme.errorContainer.copy(
|
||||||
alpha = 0.5f
|
alpha = 0.5f,
|
||||||
)
|
),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Default.Warning,
|
imageVector = Icons.Default.Warning,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
@@ -286,7 +286,7 @@ fun HealthConnectCard(modifier: Modifier = Modifier) {
|
|||||||
Text(
|
Text(
|
||||||
text = error,
|
text = error,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onErrorContainer
|
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ import androidx.compose.ui.unit.dp
|
|||||||
import com.atridad.ascently.data.model.*
|
import com.atridad.ascently.data.model.*
|
||||||
import com.atridad.ascently.ui.components.ImagePicker
|
import com.atridad.ascently.ui.components.ImagePicker
|
||||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||||
import java.time.LocalDateTime
|
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -72,7 +72,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
IconButton(onClick = onNavigateBack) {
|
IconButton(onClick = onNavigateBack) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.AutoMirrored.Filled.ArrowBack,
|
Icons.AutoMirrored.Filled.ArrowBack,
|
||||||
contentDescription = "Back"
|
contentDescription = "Back",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -85,7 +85,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
location,
|
location,
|
||||||
selectedClimbTypes.toList(),
|
selectedClimbTypes.toList(),
|
||||||
selectedDifficultySystems.toList(),
|
selectedDifficultySystems.toList(),
|
||||||
notes = notes
|
notes = notes,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (isEditing) {
|
if (isEditing) {
|
||||||
@@ -98,15 +98,15 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
enabled =
|
enabled =
|
||||||
name.isNotBlank() &&
|
name.isNotBlank() &&
|
||||||
selectedClimbTypes.isNotEmpty() &&
|
selectedClimbTypes.isNotEmpty() &&
|
||||||
selectedDifficultySystems.isNotEmpty()
|
selectedDifficultySystems.isNotEmpty(),
|
||||||
) { Text("Save") }
|
) { Text("Save") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
},
|
||||||
) { paddingValues ->
|
) { paddingValues ->
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
// Name field
|
// Name field
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
@@ -114,7 +114,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
onValueChange = { name = it },
|
onValueChange = { name = it },
|
||||||
label = { Text("Gym Name") },
|
label = { Text("Gym Name") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true
|
singleLine = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Location field
|
// Location field
|
||||||
@@ -123,7 +123,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
onValueChange = { location = it },
|
onValueChange = { location = it },
|
||||||
label = { Text("Location (Optional)") },
|
label = { Text("Location (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true
|
singleLine = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Climb Types
|
// Climb Types
|
||||||
@@ -132,7 +132,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
Text(
|
Text(
|
||||||
text = "Supported Climb Types",
|
text = "Supported Climb Types",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -156,12 +156,12 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
climbType
|
climbType
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
role = Role.Checkbox
|
role = Role.Checkbox,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Checkbox(
|
Checkbox(
|
||||||
checked = climbType in selectedClimbTypes,
|
checked = climbType in selectedClimbTypes,
|
||||||
onCheckedChange = null
|
onCheckedChange = null,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(climbType.displayName)
|
Text(climbType.displayName)
|
||||||
@@ -176,7 +176,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
Text(
|
Text(
|
||||||
text = "Difficulty Systems",
|
text = "Difficulty Systems",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -187,7 +187,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
"Select climb types first to see available difficulty systems",
|
"Select climb types first to see available difficulty systems",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
modifier = Modifier.padding(vertical = 8.dp)
|
modifier = Modifier.padding(vertical = 8.dp),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
availableDifficultySystems.forEach { system ->
|
availableDifficultySystems.forEach { system ->
|
||||||
@@ -211,12 +211,12 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
system
|
system
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
role = Role.Checkbox
|
role = Role.Checkbox,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Checkbox(
|
Checkbox(
|
||||||
checked = system in selectedDifficultySystems,
|
checked = system in selectedDifficultySystems,
|
||||||
onCheckedChange = null
|
onCheckedChange = null,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(system.displayName)
|
Text(system.displayName)
|
||||||
@@ -232,7 +232,7 @@ fun AddEditGymScreen(gymId: String?, viewModel: ClimbViewModel, onNavigateBack:
|
|||||||
onValueChange = { notes = it },
|
onValueChange = { notes = it },
|
||||||
label = { Text("Notes (Optional)") },
|
label = { Text("Notes (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
minLines = 3
|
minLines = 3,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -244,7 +244,7 @@ fun AddEditProblemScreen(
|
|||||||
problemId: String?,
|
problemId: String?,
|
||||||
gymId: String?,
|
gymId: String?,
|
||||||
viewModel: ClimbViewModel,
|
viewModel: ClimbViewModel,
|
||||||
onNavigateBack: () -> Unit
|
onNavigateBack: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val isEditing = problemId != null
|
val isEditing = problemId != null
|
||||||
val gyms by viewModel.gyms.collectAsState()
|
val gyms by viewModel.gyms.collectAsState()
|
||||||
@@ -337,7 +337,7 @@ fun AddEditProblemScreen(
|
|||||||
IconButton(onClick = onNavigateBack) {
|
IconButton(onClick = onNavigateBack) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.AutoMirrored.Filled.ArrowBack,
|
Icons.AutoMirrored.Filled.ArrowBack,
|
||||||
contentDescription = "Back"
|
contentDescription = "Back",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -350,12 +350,13 @@ fun AddEditProblemScreen(
|
|||||||
system = selectedDifficultySystem,
|
system = selectedDifficultySystem,
|
||||||
grade = difficultyGrade,
|
grade = difficultyGrade,
|
||||||
numericValue =
|
numericValue =
|
||||||
when (selectedDifficultySystem
|
when (
|
||||||
|
selectedDifficultySystem
|
||||||
) {
|
) {
|
||||||
DifficultySystem.V_SCALE ->
|
DifficultySystem.V_SCALE ->
|
||||||
difficultyGrade
|
difficultyGrade
|
||||||
.removePrefix(
|
.removePrefix(
|
||||||
"V"
|
"V",
|
||||||
)
|
)
|
||||||
.toIntOrNull()
|
.toIntOrNull()
|
||||||
?: 0
|
?: 0
|
||||||
@@ -363,7 +364,7 @@ fun AddEditProblemScreen(
|
|||||||
difficultyGrade
|
difficultyGrade
|
||||||
.hashCode() %
|
.hashCode() %
|
||||||
100 // Simple mapping for other systems
|
100 // Simple mapping for other systems
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
val problem =
|
val problem =
|
||||||
@@ -382,7 +383,7 @@ fun AddEditProblemScreen(
|
|||||||
},
|
},
|
||||||
location = location.ifBlank { null },
|
location = location.ifBlank { null },
|
||||||
imagePaths = imagePaths,
|
imagePaths = imagePaths,
|
||||||
notes = notes.ifBlank { null }
|
notes = notes.ifBlank { null },
|
||||||
)
|
)
|
||||||
|
|
||||||
if (isEditing) {
|
if (isEditing) {
|
||||||
@@ -395,15 +396,15 @@ fun AddEditProblemScreen(
|
|||||||
onNavigateBack()
|
onNavigateBack()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = selectedGym != null && difficultyGrade.isNotBlank()
|
enabled = selectedGym != null && difficultyGrade.isNotBlank(),
|
||||||
) { Text("Save") }
|
) { Text("Save") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
},
|
||||||
) { paddingValues ->
|
) { paddingValues ->
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
// Gym Selection
|
// Gym Selection
|
||||||
item {
|
item {
|
||||||
@@ -412,7 +413,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Select Gym",
|
text = "Select Gym",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -421,7 +422,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "No gyms available. Add a gym first.",
|
text = "No gyms available. Add a gym first.",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.error
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -429,7 +430,7 @@ fun AddEditProblemScreen(
|
|||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedGym = gym },
|
onClick = { selectedGym = gym },
|
||||||
label = { Text(gym.name) },
|
label = { Text(gym.name) },
|
||||||
selected = selectedGym?.id == gym.id
|
selected = selectedGym?.id == gym.id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -445,7 +446,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Problem Details",
|
text = "Problem Details",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
@@ -456,7 +457,7 @@ fun AddEditProblemScreen(
|
|||||||
label = { Text("Problem Name (Optional)") },
|
label = { Text("Problem Name (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
placeholder = { Text("e.g., 'The Overhang Monster', 'Yellow V4'") }
|
placeholder = { Text("e.g., 'The Overhang Monster', 'Yellow V4'") },
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -467,7 +468,7 @@ fun AddEditProblemScreen(
|
|||||||
label = { Text("Description (Optional)") },
|
label = { Text("Description (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
minLines = 2,
|
minLines = 2,
|
||||||
placeholder = { Text("Describe the problem, holds, style, etc.") }
|
placeholder = { Text("Describe the problem, holds, style, etc.") },
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -480,7 +481,7 @@ fun AddEditProblemScreen(
|
|||||||
label = { Text("Location (Optional)") },
|
label = { Text("Location (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
placeholder = { Text("e.g., 'Cave area', 'Wall 3', 'Right side'") }
|
placeholder = { Text("e.g., 'Cave area', 'Wall 3', 'Right side'") },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -494,7 +495,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Climb Type",
|
text = "Climb Type",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -504,7 +505,7 @@ fun AddEditProblemScreen(
|
|||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedClimbType = climbType },
|
onClick = { selectedClimbType = climbType },
|
||||||
label = { Text(climbType.displayName) },
|
label = { Text(climbType.displayName) },
|
||||||
selected = selectedClimbType == climbType
|
selected = selectedClimbType == climbType,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -521,7 +522,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Difficulty",
|
text = "Difficulty",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -529,7 +530,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Difficulty System",
|
text = "Difficulty System",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
|
|
||||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -537,7 +538,7 @@ fun AddEditProblemScreen(
|
|||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedDifficultySystem = system },
|
onClick = { selectedDifficultySystem = system },
|
||||||
label = { Text(system.displayName) },
|
label = { Text(system.displayName) },
|
||||||
selected = selectedDifficultySystem == system
|
selected = selectedDifficultySystem == system,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -564,7 +565,7 @@ fun AddEditProblemScreen(
|
|||||||
Text("Custom grades must be whole numbers")
|
Text("Custom grades must be whole numbers")
|
||||||
},
|
},
|
||||||
keyboardOptions =
|
keyboardOptions =
|
||||||
KeyboardOptions(keyboardType = KeyboardType.Number)
|
KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
var expanded by remember { mutableStateOf(false) }
|
var expanded by remember { mutableStateOf(false) }
|
||||||
@@ -573,7 +574,7 @@ fun AddEditProblemScreen(
|
|||||||
ExposedDropdownMenuBox(
|
ExposedDropdownMenuBox(
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
onExpandedChange = { expanded = !expanded },
|
onExpandedChange = { expanded = !expanded },
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = difficultyGrade,
|
value = difficultyGrade,
|
||||||
@@ -582,7 +583,7 @@ fun AddEditProblemScreen(
|
|||||||
label = { Text("Grade *") },
|
label = { Text("Grade *") },
|
||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
ExposedDropdownMenuDefaults.TrailingIcon(
|
ExposedDropdownMenuDefaults.TrailingIcon(
|
||||||
expanded = expanded
|
expanded = expanded,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
colors =
|
colors =
|
||||||
@@ -592,13 +593,13 @@ fun AddEditProblemScreen(
|
|||||||
Modifier.menuAnchor(
|
Modifier.menuAnchor(
|
||||||
ExposedDropdownMenuAnchorType
|
ExposedDropdownMenuAnchorType
|
||||||
.PrimaryNotEditable,
|
.PrimaryNotEditable,
|
||||||
enabled = true
|
enabled = true,
|
||||||
)
|
)
|
||||||
.fillMaxWidth()
|
.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
ExposedDropdownMenu(
|
ExposedDropdownMenu(
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
onDismissRequest = { expanded = false }
|
onDismissRequest = { expanded = false },
|
||||||
) {
|
) {
|
||||||
availableGrades.forEach { grade ->
|
availableGrades.forEach { grade ->
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
@@ -606,7 +607,7 @@ fun AddEditProblemScreen(
|
|||||||
onClick = {
|
onClick = {
|
||||||
difficultyGrade = grade
|
difficultyGrade = grade
|
||||||
expanded = false
|
expanded = false
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -624,7 +625,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Photos",
|
text = "Photos",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
@@ -632,7 +633,7 @@ fun AddEditProblemScreen(
|
|||||||
ImagePicker(
|
ImagePicker(
|
||||||
imageUris = imagePaths,
|
imageUris = imagePaths,
|
||||||
onImagesChanged = { imagePaths = it },
|
onImagesChanged = { imagePaths = it },
|
||||||
maxImages = 5
|
maxImages = 5,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -644,7 +645,7 @@ fun AddEditProblemScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Additional Info",
|
text = "Additional Info",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
@@ -655,7 +656,7 @@ fun AddEditProblemScreen(
|
|||||||
label = { Text("Tags (Optional)") },
|
label = { Text("Tags (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
placeholder = { Text("e.g., crimpy, dynamic (comma-separated)") }
|
placeholder = { Text("e.g., crimpy, dynamic (comma-separated)") },
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -666,7 +667,7 @@ fun AddEditProblemScreen(
|
|||||||
label = { Text("Notes (Optional)") },
|
label = { Text("Notes (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
minLines = 3,
|
minLines = 3,
|
||||||
placeholder = { Text("Any additional notes about this problem") }
|
placeholder = { Text("Any additional notes about this problem") },
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
@@ -678,14 +679,14 @@ fun AddEditProblemScreen(
|
|||||||
.selectable(
|
.selectable(
|
||||||
selected = isActive,
|
selected = isActive,
|
||||||
onClick = { isActive = !isActive },
|
onClick = { isActive = !isActive },
|
||||||
role = Role.Checkbox
|
role = Role.Checkbox,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Checkbox(checked = isActive, onCheckedChange = null)
|
Checkbox(checked = isActive, onCheckedChange = null)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Problem is currently active",
|
text = "Problem is currently active",
|
||||||
style = MaterialTheme.typography.bodyMedium
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -701,7 +702,7 @@ fun AddEditSessionScreen(
|
|||||||
sessionId: String?,
|
sessionId: String?,
|
||||||
gymId: String?,
|
gymId: String?,
|
||||||
viewModel: ClimbViewModel,
|
viewModel: ClimbViewModel,
|
||||||
onNavigateBack: () -> Unit
|
onNavigateBack: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val isEditing = sessionId != null
|
val isEditing = sessionId != null
|
||||||
val gyms by viewModel.gyms.collectAsState()
|
val gyms by viewModel.gyms.collectAsState()
|
||||||
@@ -745,7 +746,7 @@ fun AddEditSessionScreen(
|
|||||||
IconButton(onClick = onNavigateBack) {
|
IconButton(onClick = onNavigateBack) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.AutoMirrored.Filled.ArrowBack,
|
Icons.AutoMirrored.Filled.ArrowBack,
|
||||||
contentDescription = "Back"
|
contentDescription = "Back",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -760,7 +761,7 @@ fun AddEditSessionScreen(
|
|||||||
notes =
|
notes =
|
||||||
sessionNotes.ifBlank {
|
sessionNotes.ifBlank {
|
||||||
null
|
null
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
sessionId.let { id ->
|
sessionId.let { id ->
|
||||||
viewModel.updateSession(session.copy(id = id))
|
viewModel.updateSession(session.copy(id = id))
|
||||||
@@ -769,21 +770,21 @@ fun AddEditSessionScreen(
|
|||||||
viewModel.startSession(
|
viewModel.startSession(
|
||||||
context,
|
context,
|
||||||
gym.id,
|
gym.id,
|
||||||
sessionNotes.ifBlank { null }
|
sessionNotes.ifBlank { null },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
onNavigateBack()
|
onNavigateBack()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = selectedGym != null
|
enabled = selectedGym != null,
|
||||||
) { Text("Save") }
|
) { Text("Save") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
},
|
||||||
) { paddingValues ->
|
) { paddingValues ->
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
modifier = Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
// Gym Selection
|
// Gym Selection
|
||||||
item {
|
item {
|
||||||
@@ -792,7 +793,7 @@ fun AddEditSessionScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Select Gym",
|
text = "Select Gym",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -801,7 +802,7 @@ fun AddEditSessionScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "No gyms available. Add a gym first.",
|
text = "No gyms available. Add a gym first.",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.error
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -809,7 +810,7 @@ fun AddEditSessionScreen(
|
|||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedGym = gym },
|
onClick = { selectedGym = gym },
|
||||||
label = { Text(gym.name) },
|
label = { Text(gym.name) },
|
||||||
selected = selectedGym?.id == gym.id
|
selected = selectedGym?.id == gym.id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -825,7 +826,7 @@ fun AddEditSessionScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = "Session Details",
|
text = "Session Details",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
@@ -835,7 +836,7 @@ fun AddEditSessionScreen(
|
|||||||
onValueChange = { sessionDate = it },
|
onValueChange = { sessionDate = it },
|
||||||
label = { Text("Date (YYYY-MM-DD)") },
|
label = { Text("Date (YYYY-MM-DD)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true
|
singleLine = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -847,7 +848,7 @@ fun AddEditSessionScreen(
|
|||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
keyboardOptions =
|
keyboardOptions =
|
||||||
KeyboardOptions(keyboardType = KeyboardType.Number)
|
KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -857,7 +858,7 @@ fun AddEditSessionScreen(
|
|||||||
onValueChange = { sessionNotes = it },
|
onValueChange = { sessionNotes = it },
|
||||||
label = { Text("Session Notes (Optional)") },
|
label = { Text("Session Notes (Optional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
minLines = 3
|
minLines = 3,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,25 +29,25 @@ fun AnalyticsScreen(viewModel: ClimbViewModel) {
|
|||||||
|
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
item {
|
item {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(id = R.drawable.ic_mountains),
|
painter = painterResource(id = R.drawable.ic_mountains),
|
||||||
contentDescription = "Ascently Logo",
|
contentDescription = "Ascently Logo",
|
||||||
modifier = Modifier.size(32.dp),
|
modifier = Modifier.size(32.dp),
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "Analytics",
|
text = "Analytics",
|
||||||
style = MaterialTheme.typography.headlineMedium,
|
style = MaterialTheme.typography.headlineMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||||
}
|
}
|
||||||
@@ -59,7 +59,7 @@ fun AnalyticsScreen(viewModel: ClimbViewModel) {
|
|||||||
totalSessions = sessions.size,
|
totalSessions = sessions.size,
|
||||||
totalProblems = problems.size,
|
totalProblems = problems.size,
|
||||||
totalAttempts = attempts.size,
|
totalAttempts = attempts.size,
|
||||||
totalGyms = gyms.size
|
totalGyms = gyms.size,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ fun AnalyticsScreen(viewModel: ClimbViewModel) {
|
|||||||
|
|
||||||
FavoriteGymCard(
|
FavoriteGymCard(
|
||||||
gymName = favoriteGym?.first ?: "No sessions yet",
|
gymName = favoriteGym?.first ?: "No sessions yet",
|
||||||
sessionCount = favoriteGym?.second ?: 0
|
sessionCount = favoriteGym?.second ?: 0,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,14 +98,14 @@ fun OverallStatsCard(totalSessions: Int, totalProblems: Int, totalAttempts: Int,
|
|||||||
Text(
|
Text(
|
||||||
text = "Overall Stats",
|
text = "Overall Stats",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(12.dp))
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly
|
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||||
) {
|
) {
|
||||||
StatItem(label = "Sessions", value = totalSessions.toString())
|
StatItem(label = "Sessions", value = totalSessions.toString())
|
||||||
StatItem(label = "Problems", value = totalProblems.toString())
|
StatItem(label = "Problems", value = totalProblems.toString())
|
||||||
@@ -137,7 +137,7 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
Text(
|
Text(
|
||||||
text = "Grade Distribution",
|
text = "Grade Distribution",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(12.dp))
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
@@ -146,7 +146,7 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
// Time period toggle
|
// Time period toggle
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -161,8 +161,8 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
FilterChipDefaults.filterChipColors(
|
FilterChipDefaults.filterChipColors(
|
||||||
selectedContainerColor =
|
selectedContainerColor =
|
||||||
MaterialTheme.colorScheme.primary,
|
MaterialTheme.colorScheme.primary,
|
||||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimary
|
selectedLabelColor = MaterialTheme.colorScheme.onPrimary,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
// 7 Days button
|
// 7 Days button
|
||||||
@@ -174,8 +174,8 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
FilterChipDefaults.filterChipColors(
|
FilterChipDefaults.filterChipColors(
|
||||||
selectedContainerColor =
|
selectedContainerColor =
|
||||||
MaterialTheme.colorScheme.primary,
|
MaterialTheme.colorScheme.primary,
|
||||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimary
|
selectedLabelColor = MaterialTheme.colorScheme.onPrimary,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,7 +183,7 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
if (usedSystems.size > 1) {
|
if (usedSystems.size > 1) {
|
||||||
ExposedDropdownMenuBox(
|
ExposedDropdownMenuBox(
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
onExpandedChange = { expanded = !expanded }
|
onExpandedChange = { expanded = !expanded },
|
||||||
) {
|
) {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value =
|
value =
|
||||||
@@ -203,14 +203,14 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
type =
|
type =
|
||||||
ExposedDropdownMenuAnchorType
|
ExposedDropdownMenuAnchorType
|
||||||
.PrimaryNotEditable,
|
.PrimaryNotEditable,
|
||||||
enabled = true
|
enabled = true,
|
||||||
)
|
)
|
||||||
.width(120.dp),
|
.width(120.dp),
|
||||||
textStyle = MaterialTheme.typography.bodyMedium
|
textStyle = MaterialTheme.typography.bodyMedium,
|
||||||
)
|
)
|
||||||
ExposedDropdownMenu(
|
ExposedDropdownMenu(
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
onDismissRequest = { expanded = false }
|
onDismissRequest = { expanded = false },
|
||||||
) {
|
) {
|
||||||
usedSystems.forEach { system ->
|
usedSystems.forEach { system ->
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
@@ -221,13 +221,13 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
DifficultySystem.FONT -> "Font"
|
DifficultySystem.FONT -> "Font"
|
||||||
DifficultySystem.YDS -> "YDS"
|
DifficultySystem.YDS -> "YDS"
|
||||||
DifficultySystem.CUSTOM -> "Custom"
|
DifficultySystem.CUSTOM -> "Custom"
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
onClick = {
|
onClick = {
|
||||||
selectedSystem = system
|
selectedSystem = system
|
||||||
expanded = false
|
expanded = false
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -275,7 +275,7 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
BarChartDataPoint(
|
BarChartDataPoint(
|
||||||
label = grade,
|
label = grade,
|
||||||
value = count,
|
value = count,
|
||||||
gradeNumeric = firstDataPoint.gradeNumeric
|
gradeNumeric = firstDataPoint.gradeNumeric,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,19 +292,19 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
DifficultySystem.CUSTOM -> "custom grade"
|
DifficultySystem.CUSTOM -> "custom grade"
|
||||||
}}",
|
}}",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.fillMaxWidth().height(220.dp),
|
modifier = Modifier.fillMaxWidth().height(220.dp),
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
verticalArrangement = Arrangement.Center
|
verticalArrangement = Arrangement.Center,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(id = R.drawable.ic_mountains),
|
painter = painterResource(id = R.drawable.ic_mountains),
|
||||||
contentDescription = "No data",
|
contentDescription = "No data",
|
||||||
modifier = Modifier.size(48.dp),
|
modifier = Modifier.size(48.dp),
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
|
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -312,16 +312,18 @@ fun GradeDistributionChartCard(gradeDistributionData: List<GradeDistributionData
|
|||||||
Text(
|
Text(
|
||||||
text = "No data available.",
|
text = "No data available.",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
text =
|
text =
|
||||||
if (showAllTime)
|
if (showAllTime) {
|
||||||
"Complete some climbs to see your grade distribution!"
|
"Complete some climbs to see your grade distribution!"
|
||||||
else "No climbs in the last 7 days",
|
} else {
|
||||||
|
"No climbs in the last 7 days"
|
||||||
|
},
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
|
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -336,7 +338,7 @@ fun FavoriteGymCard(gymName: String, sessionCount: Int) {
|
|||||||
Text(
|
Text(
|
||||||
text = "Favorite Gym",
|
text = "Favorite Gym",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -344,14 +346,14 @@ fun FavoriteGymCard(gymName: String, sessionCount: Int) {
|
|||||||
Text(
|
Text(
|
||||||
text = gymName,
|
text = gymName,
|
||||||
style = MaterialTheme.typography.titleLarge,
|
style = MaterialTheme.typography.titleLarge,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (sessionCount > 0) {
|
if (sessionCount > 0) {
|
||||||
Text(
|
Text(
|
||||||
text = "$sessionCount sessions",
|
text = "$sessionCount sessions",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -365,7 +367,7 @@ fun RecentActivityCard(recentSessions: Int) {
|
|||||||
Text(
|
Text(
|
||||||
text = "Recent Activity",
|
text = "Recent Activity",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -377,7 +379,7 @@ fun RecentActivityCard(recentSessions: Int) {
|
|||||||
} else {
|
} else {
|
||||||
"No recent activity"
|
"No recent activity"
|
||||||
},
|
},
|
||||||
style = MaterialTheme.typography.bodyMedium
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -389,13 +391,13 @@ data class GradeDistributionDataPoint(
|
|||||||
val gradeNumeric: Int,
|
val gradeNumeric: Int,
|
||||||
val count: Int,
|
val count: Int,
|
||||||
val climbType: ClimbType,
|
val climbType: ClimbType,
|
||||||
val difficultySystem: DifficultySystem
|
val difficultySystem: DifficultySystem,
|
||||||
)
|
)
|
||||||
|
|
||||||
fun calculateGradeDistribution(
|
fun calculateGradeDistribution(
|
||||||
sessions: List<com.atridad.ascently.data.model.ClimbSession>,
|
sessions: List<com.atridad.ascently.data.model.ClimbSession>,
|
||||||
problems: List<com.atridad.ascently.data.model.Problem>,
|
problems: List<com.atridad.ascently.data.model.Problem>,
|
||||||
attempts: List<com.atridad.ascently.data.model.Attempt>
|
attempts: List<com.atridad.ascently.data.model.Attempt>,
|
||||||
): List<GradeDistributionDataPoint> {
|
): List<GradeDistributionDataPoint> {
|
||||||
if (sessions.isEmpty() || problems.isEmpty() || attempts.isEmpty()) {
|
if (sessions.isEmpty() || problems.isEmpty() || attempts.isEmpty()) {
|
||||||
return emptyList()
|
return emptyList()
|
||||||
@@ -432,11 +434,11 @@ fun calculateGradeDistribution(
|
|||||||
gradeNumeric =
|
gradeNumeric =
|
||||||
gradeToNumeric(
|
gradeToNumeric(
|
||||||
problem.difficulty.system,
|
problem.difficulty.system,
|
||||||
problem.difficulty.grade
|
problem.difficulty.grade,
|
||||||
),
|
),
|
||||||
count = 1,
|
count = 1,
|
||||||
climbType = problem.climbType,
|
climbType = problem.climbType,
|
||||||
difficultySystem = problem.difficulty.system
|
difficultySystem = problem.difficulty.system,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -24,19 +24,19 @@ fun GymsScreen(viewModel: ClimbViewModel, onNavigateToGymDetail: (String) -> Uni
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(id = R.drawable.ic_mountains),
|
painter = painterResource(id = R.drawable.ic_mountains),
|
||||||
contentDescription = "Ascently Logo",
|
contentDescription = "Ascently Logo",
|
||||||
modifier = Modifier.size(32.dp),
|
modifier = Modifier.size(32.dp),
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "Climbing Gyms",
|
text = "Climbing Gyms",
|
||||||
style = MaterialTheme.typography.headlineMedium,
|
style = MaterialTheme.typography.headlineMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ fun GymsScreen(viewModel: ClimbViewModel, onNavigateToGymDetail: (String) -> Uni
|
|||||||
title = "No Gyms Added",
|
title = "No Gyms Added",
|
||||||
message = "Add your favorite climbing gyms to start tracking your progress!",
|
message = "Add your favorite climbing gyms to start tracking your progress!",
|
||||||
onActionClick = {},
|
onActionClick = {},
|
||||||
actionText = ""
|
actionText = "",
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
LazyColumn {
|
LazyColumn {
|
||||||
@@ -69,7 +69,7 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
|||||||
Text(
|
Text(
|
||||||
text = gym.name,
|
text = gym.name,
|
||||||
style = MaterialTheme.typography.titleLarge,
|
style = MaterialTheme.typography.titleLarge,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
gym.location?.let { location ->
|
gym.location?.let { location ->
|
||||||
@@ -77,7 +77,7 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
|||||||
Text(
|
Text(
|
||||||
text = location,
|
text = location,
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
|||||||
AssistChip(
|
AssistChip(
|
||||||
onClick = {},
|
onClick = {},
|
||||||
label = { Text(climbType.displayName) },
|
label = { Text(climbType.displayName) },
|
||||||
modifier = Modifier.padding(end = 4.dp)
|
modifier = Modifier.padding(end = 4.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -99,7 +99,7 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
|||||||
text =
|
text =
|
||||||
"Systems: ${gym.difficultySystems.joinToString(", ") { it.displayName }}",
|
"Systems: ${gym.difficultySystems.joinToString(", ") { it.displayName }}",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,7 +110,7 @@ fun GymCard(gym: Gym, onClick: () -> Unit) {
|
|||||||
text = notes,
|
text = notes,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
maxLines = 2
|
maxLines = 2,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,19 +51,19 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(id = R.drawable.ic_mountains),
|
painter = painterResource(id = R.drawable.ic_mountains),
|
||||||
contentDescription = "Ascently Logo",
|
contentDescription = "Ascently Logo",
|
||||||
modifier = Modifier.size(32.dp),
|
modifier = Modifier.size(32.dp),
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "Climbing Problems",
|
text = "Climbing Problems",
|
||||||
style = MaterialTheme.typography.headlineMedium,
|
style = MaterialTheme.typography.headlineMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||||
}
|
}
|
||||||
@@ -77,7 +77,7 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
Text(
|
Text(
|
||||||
text = "Filters",
|
text = "Filters",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(12.dp))
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
@@ -86,7 +86,7 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
Text(
|
Text(
|
||||||
text = "Climb Type",
|
text = "Climb Type",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -96,14 +96,14 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedClimbType = null },
|
onClick = { selectedClimbType = null },
|
||||||
label = { Text("All Types") },
|
label = { Text("All Types") },
|
||||||
selected = selectedClimbType == null
|
selected = selectedClimbType == null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
items(ClimbType.entries) { climbType ->
|
items(ClimbType.entries) { climbType ->
|
||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedClimbType = climbType },
|
onClick = { selectedClimbType = climbType },
|
||||||
label = { Text(climbType.displayName) },
|
label = { Text(climbType.displayName) },
|
||||||
selected = selectedClimbType == climbType
|
selected = selectedClimbType == climbType,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -114,7 +114,7 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
Text(
|
Text(
|
||||||
text = "Gym",
|
text = "Gym",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -124,14 +124,14 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedGym = null },
|
onClick = { selectedGym = null },
|
||||||
label = { Text("All Gyms") },
|
label = { Text("All Gyms") },
|
||||||
selected = selectedGym == null
|
selected = selectedGym == null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
items(gyms) { gym ->
|
items(gyms) { gym ->
|
||||||
FilterChip(
|
FilterChip(
|
||||||
onClick = { selectedGym = gym },
|
onClick = { selectedGym = gym },
|
||||||
label = { Text(gym.name) },
|
label = { Text(gym.name) },
|
||||||
selected = selectedGym?.id == gym.id
|
selected = selectedGym?.id == gym.id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -143,7 +143,7 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
text =
|
text =
|
||||||
"Showing ${filteredProblems.size} of ${problems.size} problems (${activeProblems.size} active, ${inactiveProblems.size} reset)",
|
"Showing ${filteredProblems.size} of ${problems.size} problems (${activeProblems.size} active, ${inactiveProblems.size} reset)",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -162,14 +162,16 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
},
|
},
|
||||||
message =
|
message =
|
||||||
if (problems.isEmpty()) {
|
if (problems.isEmpty()) {
|
||||||
if (gyms.isEmpty())
|
if (gyms.isEmpty()) {
|
||||||
"Add a gym first to start tracking problems and routes!"
|
"Add a gym first to start tracking problems and routes!"
|
||||||
else "Start tracking your favorite problems and routes!"
|
} else {
|
||||||
|
"Start tracking your favorite problems and routes!"
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
"Try adjusting your filters to see more problems."
|
"Try adjusting your filters to see more problems."
|
||||||
},
|
},
|
||||||
onActionClick = {},
|
onActionClick = {},
|
||||||
actionText = ""
|
actionText = "",
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
LazyColumn {
|
LazyColumn {
|
||||||
@@ -182,7 +184,7 @@ fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String
|
|||||||
onToggleActive = {
|
onToggleActive = {
|
||||||
val updatedProblem = problem.copy(isActive = !problem.isActive)
|
val updatedProblem = problem.copy(isActive = !problem.isActive)
|
||||||
viewModel.updateProblem(updatedProblem)
|
viewModel.updateProblem(updatedProblem)
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
}
|
}
|
||||||
@@ -198,13 +200,15 @@ fun ProblemCard(
|
|||||||
gymName: String,
|
gymName: String,
|
||||||
attempts: List<Attempt>,
|
attempts: List<Attempt>,
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
onToggleActive: (() -> Unit)? = null
|
onToggleActive: (() -> Unit)? = null,
|
||||||
) {
|
) {
|
||||||
val isCompleted =
|
val isCompleted =
|
||||||
attempts.any { attempt ->
|
attempts.any { attempt ->
|
||||||
attempt.problemId == problem.id &&
|
attempt.problemId == problem.id &&
|
||||||
(attempt.result == AttemptResult.SUCCESS ||
|
(
|
||||||
attempt.result == AttemptResult.FLASH)
|
attempt.result == AttemptResult.SUCCESS ||
|
||||||
|
attempt.result == AttemptResult.FLASH
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
|
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
|
||||||
@@ -212,7 +216,7 @@ fun ProblemCard(
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.Top
|
verticalAlignment = Alignment.Top,
|
||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
Text(
|
||||||
@@ -220,8 +224,11 @@ fun ProblemCard(
|
|||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
color =
|
color =
|
||||||
if (problem.isActive) MaterialTheme.colorScheme.onSurface
|
if (problem.isActive) {
|
||||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
|
MaterialTheme.colorScheme.onSurface
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
@@ -229,22 +236,22 @@ fun ProblemCard(
|
|||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color =
|
color =
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||||
alpha = if (problem.isActive) 1f else 0.6f
|
alpha = if (problem.isActive) 1f else 0.6f,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(horizontalAlignment = Alignment.End) {
|
Column(horizontalAlignment = Alignment.End) {
|
||||||
Row(
|
Row(
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
if (problem.imagePaths.isNotEmpty()) {
|
if (problem.imagePaths.isNotEmpty()) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Default.Image,
|
imageVector = Icons.Default.Image,
|
||||||
contentDescription = "Has images",
|
contentDescription = "Has images",
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,7 +260,7 @@ fun ProblemCard(
|
|||||||
imageVector = Icons.Default.CheckCircle,
|
imageVector = Icons.Default.CheckCircle,
|
||||||
contentDescription = "Completed",
|
contentDescription = "Completed",
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
tint = MaterialTheme.colorScheme.tertiary
|
tint = MaterialTheme.colorScheme.tertiary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,14 +268,14 @@ fun ProblemCard(
|
|||||||
text = problem.difficulty.grade,
|
text = problem.difficulty.grade,
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
color = MaterialTheme.colorScheme.primary
|
color = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
text = problem.climbType.displayName,
|
text = problem.climbType.displayName,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -278,7 +285,7 @@ fun ProblemCard(
|
|||||||
Text(
|
Text(
|
||||||
text = "Location: $location",
|
text = "Location: $location",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,7 +296,7 @@ fun ProblemCard(
|
|||||||
AssistChip(
|
AssistChip(
|
||||||
onClick = {},
|
onClick = {},
|
||||||
label = { Text(tag) },
|
label = { Text(tag) },
|
||||||
modifier = Modifier.padding(end = 4.dp)
|
modifier = Modifier.padding(end = 4.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -301,7 +308,7 @@ fun ProblemCard(
|
|||||||
text = "Reset / No Longer Set",
|
text = "Reset / No Longer Set",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.tertiary,
|
color = MaterialTheme.colorScheme.tertiary,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -313,15 +320,17 @@ fun ProblemCard(
|
|||||||
colors =
|
colors =
|
||||||
ButtonDefaults.outlinedButtonColors(
|
ButtonDefaults.outlinedButtonColors(
|
||||||
contentColor =
|
contentColor =
|
||||||
if (problem.isActive)
|
if (problem.isActive) {
|
||||||
MaterialTheme.colorScheme.tertiary
|
MaterialTheme.colorScheme.tertiary
|
||||||
else MaterialTheme.colorScheme.primary
|
} else {
|
||||||
|
MaterialTheme.colorScheme.primary
|
||||||
|
},
|
||||||
),
|
),
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = if (problem.isActive) "Mark as Reset" else "Mark as Active",
|
text = if (problem.isActive) "Mark as Reset" else "Mark as Active",
|
||||||
style = MaterialTheme.typography.bodySmall
|
style = MaterialTheme.typography.bodySmall,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import androidx.compose.foundation.background
|
|||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.grid.GridCells
|
|
||||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
@@ -26,6 +24,7 @@ import androidx.compose.ui.res.painterResource
|
|||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.core.content.edit
|
||||||
import com.atridad.ascently.R
|
import com.atridad.ascently.R
|
||||||
import com.atridad.ascently.data.model.ClimbSession
|
import com.atridad.ascently.data.model.ClimbSession
|
||||||
import com.atridad.ascently.data.model.SessionStatus
|
import com.atridad.ascently.data.model.SessionStatus
|
||||||
@@ -41,7 +40,7 @@ import java.util.Locale
|
|||||||
|
|
||||||
enum class ViewMode {
|
enum class ViewMode {
|
||||||
LIST,
|
LIST,
|
||||||
CALENDAR
|
CALENDAR,
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@@ -60,7 +59,7 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
mutableStateOf(if (savedViewMode == "CALENDAR") ViewMode.CALENDAR else ViewMode.LIST)
|
mutableStateOf(if (savedViewMode == "CALENDAR") ViewMode.CALENDAR else ViewMode.LIST)
|
||||||
}
|
}
|
||||||
var selectedMonth by remember { mutableStateOf(YearMonth.now()) }
|
var selectedMonth by remember { mutableStateOf(YearMonth.now()) }
|
||||||
var selectedDate by remember { mutableStateOf<LocalDate?>(null) }
|
var selectedDate by remember { mutableStateOf<LocalDate?>(LocalDate.now()) }
|
||||||
|
|
||||||
val completedSessions = sessions.filter { it.status == SessionStatus.COMPLETED }
|
val completedSessions = sessions.filter { it.status == SessionStatus.COMPLETED }
|
||||||
val activeSessionGym = activeSession?.let { session -> gyms.find { it.id == session.gymId } }
|
val activeSessionGym = activeSession?.let { session -> gyms.find { it.id == session.gymId } }
|
||||||
@@ -69,19 +68,19 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(id = R.drawable.ic_mountains),
|
painter = painterResource(id = R.drawable.ic_mountains),
|
||||||
contentDescription = "Ascently Logo",
|
contentDescription = "Ascently Logo",
|
||||||
modifier = Modifier.size(32.dp),
|
modifier = Modifier.size(32.dp),
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "Climbing Sessions",
|
text = "Climbing Sessions",
|
||||||
style = MaterialTheme.typography.headlineMedium,
|
style = MaterialTheme.typography.headlineMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
|
|
||||||
IconButton(
|
IconButton(
|
||||||
@@ -89,16 +88,19 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
viewMode =
|
viewMode =
|
||||||
if (viewMode == ViewMode.LIST) ViewMode.CALENDAR else ViewMode.LIST
|
if (viewMode == ViewMode.LIST) ViewMode.CALENDAR else ViewMode.LIST
|
||||||
selectedDate = null
|
selectedDate = null
|
||||||
sharedPreferences.edit().putString("view_mode", viewMode.name).apply()
|
sharedPreferences.edit { putString("view_mode", viewMode.name) }
|
||||||
}
|
},
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector =
|
imageVector =
|
||||||
if (viewMode == ViewMode.LIST) Icons.Default.CalendarMonth
|
if (viewMode == ViewMode.LIST) {
|
||||||
else Icons.AutoMirrored.Filled.List,
|
Icons.Default.CalendarMonth
|
||||||
|
} else {
|
||||||
|
Icons.AutoMirrored.Filled.List
|
||||||
|
},
|
||||||
contentDescription =
|
contentDescription =
|
||||||
if (viewMode == ViewMode.LIST) "Calendar View" else "List View",
|
if (viewMode == ViewMode.LIST) "Calendar View" else "List View",
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +113,7 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
activeSession = activeSession,
|
activeSession = activeSession,
|
||||||
gym = activeSessionGym,
|
gym = activeSessionGym,
|
||||||
onSessionClick = { activeSession?.let { onNavigateToSessionDetail(it.id) } },
|
onSessionClick = { activeSession?.let { onNavigateToSessionDetail(it.id) } },
|
||||||
onEndSession = { activeSession?.let { viewModel.endSession(context, it.id) } }
|
onEndSession = { activeSession?.let { viewModel.endSession(context, it.id) } },
|
||||||
)
|
)
|
||||||
|
|
||||||
if (activeSession != null) {
|
if (activeSession != null) {
|
||||||
@@ -122,11 +124,13 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
EmptyStateMessage(
|
EmptyStateMessage(
|
||||||
title = if (gyms.isEmpty()) "No Gyms Available" else "No Sessions Yet",
|
title = if (gyms.isEmpty()) "No Gyms Available" else "No Sessions Yet",
|
||||||
message =
|
message =
|
||||||
if (gyms.isEmpty())
|
if (gyms.isEmpty()) {
|
||||||
"Add a gym first to start tracking your climbing sessions!"
|
"Add a gym first to start tracking your climbing sessions!"
|
||||||
else "Start your first climbing session!",
|
} else {
|
||||||
|
"Start your first climbing session!"
|
||||||
|
},
|
||||||
onActionClick = {},
|
onActionClick = {},
|
||||||
actionText = ""
|
actionText = "",
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
when (viewMode) {
|
when (viewMode) {
|
||||||
@@ -137,7 +141,7 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
session = session,
|
session = session,
|
||||||
gymName = gyms.find { it.id == session.gymId }?.name
|
gymName = gyms.find { it.id == session.gymId }?.name
|
||||||
?: "Unknown Gym",
|
?: "Unknown Gym",
|
||||||
onClick = { onNavigateToSessionDetail(session.id) }
|
onClick = { onNavigateToSessionDetail(session.id) },
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
}
|
}
|
||||||
@@ -147,16 +151,11 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
CalendarView(
|
CalendarView(
|
||||||
sessions = completedSessions,
|
sessions = completedSessions,
|
||||||
gyms = gyms,
|
gyms = gyms,
|
||||||
activeSession = activeSession,
|
|
||||||
activeSessionGym = activeSessionGym,
|
|
||||||
selectedMonth = selectedMonth,
|
selectedMonth = selectedMonth,
|
||||||
onMonthChange = { selectedMonth = it },
|
onMonthChange = { selectedMonth = it },
|
||||||
selectedDate = selectedDate,
|
selectedDate = selectedDate,
|
||||||
onDateSelected = { selectedDate = it },
|
onDateSelected = { selectedDate = it },
|
||||||
onNavigateToSessionDetail = onNavigateToSessionDetail,
|
onNavigateToSessionDetail = onNavigateToSessionDetail,
|
||||||
onEndSession = {
|
|
||||||
activeSession?.let { viewModel.endSession(context, it.id) }
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -173,24 +172,24 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.primaryContainer
|
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||||
),
|
),
|
||||||
shape = RoundedCornerShape(12.dp)
|
shape = RoundedCornerShape(12.dp),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.CheckCircle,
|
Icons.Default.CheckCircle,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = message,
|
text = message,
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -206,24 +205,24 @@ fun SessionsScreen(viewModel: ClimbViewModel, onNavigateToSessionDetail: (String
|
|||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.errorContainer
|
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||||
),
|
),
|
||||||
shape = RoundedCornerShape(12.dp)
|
shape = RoundedCornerShape(12.dp),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Warning,
|
Icons.Default.Warning,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = error,
|
text = error,
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onErrorContainer
|
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -237,17 +236,17 @@ fun SessionCard(session: ClimbSession, gymName: String, onClick: () -> Unit) {
|
|||||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceBetween
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = gymName,
|
text = gymName,
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = formatDate(session.date),
|
text = formatDate(session.date),
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,7 +255,7 @@ fun SessionCard(session: ClimbSession, gymName: String, onClick: () -> Unit) {
|
|||||||
session.duration?.let { duration ->
|
session.duration?.let { duration ->
|
||||||
Text(
|
Text(
|
||||||
text = "Duration: $duration minutes",
|
text = "Duration: $duration minutes",
|
||||||
style = MaterialTheme.typography.bodyMedium
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,7 +266,7 @@ fun SessionCard(session: ClimbSession, gymName: String, onClick: () -> Unit) {
|
|||||||
text = notes,
|
text = notes,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
maxLines = 2
|
maxLines = 2,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -280,18 +279,18 @@ fun EmptyStateMessage(
|
|||||||
title: String,
|
title: String,
|
||||||
message: String,
|
message: String,
|
||||||
onActionClick: () -> Unit,
|
onActionClick: () -> Unit,
|
||||||
actionText: String
|
actionText: String,
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
verticalArrangement = Arrangement.Center
|
verticalArrangement = Arrangement.Center,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = title,
|
text = title,
|
||||||
style = MaterialTheme.typography.headlineSmall,
|
style = MaterialTheme.typography.headlineSmall,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
textAlign = TextAlign.Center
|
textAlign = TextAlign.Center,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -300,7 +299,7 @@ fun EmptyStateMessage(
|
|||||||
text = message,
|
text = message,
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
textAlign = TextAlign.Center
|
textAlign = TextAlign.Center,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (actionText.isNotEmpty()) {
|
if (actionText.isNotEmpty()) {
|
||||||
@@ -315,14 +314,11 @@ fun EmptyStateMessage(
|
|||||||
fun CalendarView(
|
fun CalendarView(
|
||||||
sessions: List<ClimbSession>,
|
sessions: List<ClimbSession>,
|
||||||
gyms: List<com.atridad.ascently.data.model.Gym>,
|
gyms: List<com.atridad.ascently.data.model.Gym>,
|
||||||
activeSession: ClimbSession?,
|
|
||||||
activeSessionGym: com.atridad.ascently.data.model.Gym?,
|
|
||||||
selectedMonth: YearMonth,
|
selectedMonth: YearMonth,
|
||||||
onMonthChange: (YearMonth) -> Unit,
|
onMonthChange: (YearMonth) -> Unit,
|
||||||
selectedDate: LocalDate?,
|
selectedDate: LocalDate?,
|
||||||
onDateSelected: (LocalDate?) -> Unit,
|
onDateSelected: (LocalDate?) -> Unit,
|
||||||
onNavigateToSessionDetail: (String) -> Unit,
|
onNavigateToSessionDetail: (String) -> Unit,
|
||||||
onEndSession: () -> Unit
|
|
||||||
) {
|
) {
|
||||||
val sessionsByDate =
|
val sessionsByDate =
|
||||||
remember(sessions) {
|
remember(sessions) {
|
||||||
@@ -331,28 +327,39 @@ fun CalendarView(
|
|||||||
java.time.Instant.parse(it.date)
|
java.time.Instant.parse(it.date)
|
||||||
.atZone(java.time.ZoneId.systemDefault())
|
.atZone(java.time.ZoneId.systemDefault())
|
||||||
.toLocalDate()
|
.toLocalDate()
|
||||||
} catch (e: Exception) {
|
} catch (_: Exception) {
|
||||||
LocalDate.parse(it.date, DateTimeFormatter.ISO_LOCAL_DATE)
|
LocalDate.parse(it.date, DateTimeFormatter.ISO_LOCAL_DATE)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(modifier = Modifier.fillMaxSize()) {
|
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(
|
Card(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),
|
modifier =
|
||||||
horizontalAlignment = Alignment.CenterHorizontally
|
Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
IconButton(onClick = { onMonthChange(selectedMonth.minusMonths(1)) }) {
|
IconButton(onClick = { onMonthChange(selectedMonth.minusMonths(1)) }) {
|
||||||
Text("‹", style = MaterialTheme.typography.headlineMedium)
|
Text("‹", style = MaterialTheme.typography.headlineMedium)
|
||||||
@@ -362,7 +369,7 @@ fun CalendarView(
|
|||||||
text =
|
text =
|
||||||
"${selectedMonth.month.getDisplayName(TextStyle.FULL, Locale.getDefault())} ${selectedMonth.year}",
|
"${selectedMonth.month.getDisplayName(TextStyle.FULL, Locale.getDefault())} ${selectedMonth.year}",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
IconButton(onClick = { onMonthChange(selectedMonth.plusMonths(1)) }) {
|
IconButton(onClick = { onMonthChange(selectedMonth.plusMonths(1)) }) {
|
||||||
@@ -381,14 +388,14 @@ fun CalendarView(
|
|||||||
shape = RoundedCornerShape(50),
|
shape = RoundedCornerShape(50),
|
||||||
colors =
|
colors =
|
||||||
ButtonDefaults.buttonColors(
|
ButtonDefaults.buttonColors(
|
||||||
containerColor = MaterialTheme.colorScheme.primary
|
containerColor = MaterialTheme.colorScheme.primary,
|
||||||
),
|
),
|
||||||
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp)
|
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp),
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "Today",
|
text = "Today",
|
||||||
style = MaterialTheme.typography.labelLarge,
|
style = MaterialTheme.typography.labelLarge,
|
||||||
fontWeight = FontWeight.SemiBold
|
fontWeight = FontWeight.SemiBold,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -404,25 +411,21 @@ fun CalendarView(
|
|||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
LazyVerticalGrid(columns = GridCells.Fixed(7), modifier = Modifier.fillMaxWidth()) {
|
items(numRows) { rowIndex ->
|
||||||
items(totalCells) { index ->
|
Row(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
for (colIndex in 0 until 7) {
|
||||||
|
val index = rowIndex * 7 + colIndex
|
||||||
val dayNumber = index - firstDayOfWeek + 1
|
val dayNumber = index - firstDayOfWeek + 1
|
||||||
|
|
||||||
|
Box(modifier = Modifier.weight(1f)) {
|
||||||
if (dayNumber in 1..daysInMonth) {
|
if (dayNumber in 1..daysInMonth) {
|
||||||
val date = selectedMonth.atDay(dayNumber)
|
val date = selectedMonth.atDay(dayNumber)
|
||||||
val sessionsOnDate = sessionsByDate[date] ?: emptyList()
|
val sessionsOnDate = sessionsByDate[date] ?: emptyList()
|
||||||
@@ -438,17 +441,20 @@ fun CalendarView(
|
|||||||
if (sessionsOnDate.isNotEmpty()) {
|
if (sessionsOnDate.isNotEmpty()) {
|
||||||
onDateSelected(if (isSelected) null else date)
|
onDateSelected(if (isSelected) null else date)
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Spacer(modifier = Modifier.aspectRatio(1f))
|
Spacer(modifier = Modifier.aspectRatio(1f))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (selectedDate != null) {
|
if (selectedDate != null) {
|
||||||
val sessionsOnSelectedDate = sessionsByDate[selectedDate] ?: emptyList()
|
val sessionsOnSelectedDate = sessionsByDate[selectedDate] ?: emptyList()
|
||||||
|
|
||||||
|
item {
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
@@ -456,19 +462,20 @@ fun CalendarView(
|
|||||||
"Sessions on ${selectedDate.format(DateTimeFormatter.ofPattern("MMMM d, yyyy"))}",
|
"Sessions on ${selectedDate.format(DateTimeFormatter.ofPattern("MMMM d, yyyy"))}",
|
||||||
style = MaterialTheme.typography.titleSmall,
|
style = MaterialTheme.typography.titleSmall,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
modifier = Modifier.padding(vertical = 8.dp)
|
modifier = Modifier.padding(vertical = 8.dp),
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
LazyColumn(modifier = Modifier.fillMaxWidth()) {
|
|
||||||
items(sessionsOnSelectedDate) { session ->
|
items(sessionsOnSelectedDate) { session ->
|
||||||
SessionCard(
|
SessionCard(
|
||||||
session = session,
|
session = session,
|
||||||
gymName = gyms.find { it.id == session.gymId }?.name ?: "Unknown Gym",
|
gymName = gyms.find { it.id == session.gymId }?.name ?: "Unknown Gym",
|
||||||
onClick = { onNavigateToSessionDetail(session.id) }
|
onClick = { onNavigateToSessionDetail(session.id) },
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
item { Spacer(modifier = Modifier.height(16.dp)) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -479,7 +486,7 @@ fun CalendarDay(
|
|||||||
hasSession: Boolean,
|
hasSession: Boolean,
|
||||||
isSelected: Boolean,
|
isSelected: Boolean,
|
||||||
isToday: Boolean,
|
isToday: Boolean,
|
||||||
onClick: () -> Unit
|
onClick: () -> Unit,
|
||||||
) {
|
) {
|
||||||
Box(
|
Box(
|
||||||
modifier =
|
modifier =
|
||||||
@@ -491,14 +498,14 @@ fun CalendarDay(
|
|||||||
isSelected -> MaterialTheme.colorScheme.primaryContainer
|
isSelected -> MaterialTheme.colorScheme.primaryContainer
|
||||||
isToday -> MaterialTheme.colorScheme.secondaryContainer
|
isToday -> MaterialTheme.colorScheme.secondaryContainer
|
||||||
else -> Color.Transparent
|
else -> Color.Transparent
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
.clickable(enabled = hasSession, onClick = onClick),
|
.clickable(enabled = hasSession, onClick = onClick),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
verticalArrangement = Arrangement.Center
|
verticalArrangement = Arrangement.Center,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = day.toString(),
|
text = day.toString(),
|
||||||
@@ -510,7 +517,7 @@ fun CalendarDay(
|
|||||||
!hasSession -> MaterialTheme.colorScheme.onSurfaceVariant
|
!hasSession -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
else -> MaterialTheme.colorScheme.onSurface
|
else -> MaterialTheme.colorScheme.onSurface
|
||||||
},
|
},
|
||||||
fontWeight = if (hasSession || isToday) FontWeight.Bold else FontWeight.Normal
|
fontWeight = if (hasSession || isToday) FontWeight.Bold else FontWeight.Normal,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (hasSession) {
|
if (hasSession) {
|
||||||
@@ -519,12 +526,14 @@ fun CalendarDay(
|
|||||||
Modifier.size(6.dp)
|
Modifier.size(6.dp)
|
||||||
.clip(CircleShape)
|
.clip(CircleShape)
|
||||||
.background(
|
.background(
|
||||||
if (isSelected) MaterialTheme.colorScheme.primary
|
if (isSelected) {
|
||||||
else
|
MaterialTheme.colorScheme.primary
|
||||||
|
} else {
|
||||||
MaterialTheme.colorScheme.primary.copy(
|
MaterialTheme.colorScheme.primary.copy(
|
||||||
alpha = 0.7f
|
alpha = 0.7f,
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
},
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,9 +19,9 @@ import com.atridad.ascently.R
|
|||||||
import com.atridad.ascently.ui.components.SyncIndicator
|
import com.atridad.ascently.ui.components.SyncIndicator
|
||||||
import com.atridad.ascently.ui.health.HealthConnectCard
|
import com.atridad.ascently.ui.health.HealthConnectCard
|
||||||
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -64,7 +64,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
|
|
||||||
// File picker launcher for import - only accepts ZIP files
|
// File picker launcher for import - only accepts ZIP files
|
||||||
val importLauncher =
|
val importLauncher =
|
||||||
rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri
|
rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri,
|
||||||
->
|
->
|
||||||
uri?.let {
|
uri?.let {
|
||||||
try {
|
try {
|
||||||
@@ -75,18 +75,20 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
cursor ->
|
cursor ->
|
||||||
val nameIndex =
|
val nameIndex =
|
||||||
cursor.getColumnIndex(
|
cursor.getColumnIndex(
|
||||||
android.provider.OpenableColumns.DISPLAY_NAME
|
android.provider.OpenableColumns.DISPLAY_NAME,
|
||||||
)
|
)
|
||||||
if (nameIndex >= 0 && cursor.moveToFirst()) {
|
if (nameIndex >= 0 && cursor.moveToFirst()) {
|
||||||
cursor.getString(nameIndex)
|
cursor.getString(nameIndex)
|
||||||
} else null
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
?: "import_file"
|
?: "import_file"
|
||||||
|
|
||||||
// Only allow ZIP files
|
// Only allow ZIP files
|
||||||
if (!fileName.lowercase().endsWith(".zip")) {
|
if (!fileName.lowercase().endsWith(".zip")) {
|
||||||
viewModel.setError(
|
viewModel.setError(
|
||||||
"Only ZIP files are supported for import. Please use a ZIP file exported from Ascently."
|
"Only ZIP files are supported for import. Please use a ZIP file exported from Ascently.",
|
||||||
)
|
)
|
||||||
return@let
|
return@let
|
||||||
}
|
}
|
||||||
@@ -106,7 +108,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
// File picker launcher for export - ZIP format with images
|
// File picker launcher for export - ZIP format with images
|
||||||
val exportZipLauncher =
|
val exportZipLauncher =
|
||||||
rememberLauncherForActivityResult(
|
rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.CreateDocument("application/zip")
|
contract = ActivityResultContracts.CreateDocument("application/zip"),
|
||||||
) { uri ->
|
) { uri ->
|
||||||
uri?.let {
|
uri?.let {
|
||||||
try {
|
try {
|
||||||
@@ -119,25 +121,25 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
|
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
item {
|
item {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(id = R.drawable.ic_mountains),
|
painter = painterResource(id = R.drawable.ic_mountains),
|
||||||
contentDescription = "Ascently Logo",
|
contentDescription = "Ascently Logo",
|
||||||
modifier = Modifier.size(32.dp),
|
modifier = Modifier.size(32.dp),
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "Settings",
|
text = "Settings",
|
||||||
style = MaterialTheme.typography.headlineMedium,
|
style = MaterialTheme.typography.headlineMedium,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
|
||||||
}
|
}
|
||||||
@@ -150,7 +152,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
Text(
|
Text(
|
||||||
text = "Sync",
|
text = "Sync",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(12.dp))
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
@@ -162,23 +164,27 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
if (isConnected)
|
if (isConnected) {
|
||||||
MaterialTheme.colorScheme
|
MaterialTheme.colorScheme
|
||||||
.primaryContainer.copy(
|
.primaryContainer.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
)
|
||||||
else
|
} else {
|
||||||
MaterialTheme.colorScheme
|
MaterialTheme.colorScheme
|
||||||
.surfaceVariant.copy(
|
.surfaceVariant.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
},
|
||||||
|
),
|
||||||
) {
|
) {
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = {
|
headlineContent = {
|
||||||
Text(
|
Text(
|
||||||
if (isConnected) "Connected to Server"
|
if (isConnected) {
|
||||||
else "Server Configured"
|
"Connected to Server"
|
||||||
|
} else {
|
||||||
|
"Server Configured"
|
||||||
|
},
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
supportingContent = {
|
supportingContent = {
|
||||||
@@ -193,22 +199,26 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
time
|
time
|
||||||
}
|
}
|
||||||
}",
|
}",
|
||||||
style = MaterialTheme.typography.bodySmall
|
style = MaterialTheme.typography.bodySmall,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
leadingContent = {
|
leadingContent = {
|
||||||
Icon(
|
Icon(
|
||||||
if (isConnected) Icons.Default.CloudDone
|
if (isConnected) {
|
||||||
else Icons.Default.Cloud,
|
Icons.Default.CloudDone
|
||||||
|
} else {
|
||||||
|
Icons.Default.Cloud
|
||||||
|
},
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint =
|
tint =
|
||||||
if (isConnected)
|
if (isConnected) {
|
||||||
MaterialTheme.colorScheme.primary
|
MaterialTheme.colorScheme.primary
|
||||||
else
|
} else {
|
||||||
MaterialTheme.colorScheme
|
MaterialTheme.colorScheme
|
||||||
.onSurfaceVariant
|
.onSurfaceVariant
|
||||||
|
},
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
trailingContent = {
|
trailingContent = {
|
||||||
@@ -216,16 +226,14 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
// Manual Sync Button
|
// Manual Sync Button
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
coroutineScope.launch {
|
|
||||||
viewModel.performManualSync()
|
viewModel.performManualSync()
|
||||||
}
|
|
||||||
},
|
},
|
||||||
enabled = isConnected && !isSyncing
|
enabled = isConnected && !isSyncing,
|
||||||
) {
|
) {
|
||||||
if (isSyncing) {
|
if (isSyncing) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Text("Sync")
|
Text("Sync")
|
||||||
@@ -237,7 +245,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
Text("Configure")
|
Text("Configure")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,21 +258,21 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.surfaceVariant
|
MaterialTheme.colorScheme.surfaceVariant
|
||||||
.copy(alpha = 0.3f)
|
.copy(alpha = 0.3f),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.padding(16.dp)) {
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
Text(
|
Text(
|
||||||
text = "Sync Mode",
|
text = "Sync Mode",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text("Auto-sync")
|
Text("Auto-sync")
|
||||||
@@ -274,9 +282,9 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color =
|
color =
|
||||||
MaterialTheme.colorScheme.onSurface.copy(
|
MaterialTheme.colorScheme.onSurface.copy(
|
||||||
alpha = 0.7f
|
alpha = 0.7f,
|
||||||
),
|
),
|
||||||
maxLines = 2
|
maxLines = 2,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(modifier = Modifier.width(16.dp))
|
Spacer(modifier = Modifier.width(16.dp))
|
||||||
@@ -284,7 +292,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
checked = isAutoSyncEnabled,
|
checked = isAutoSyncEnabled,
|
||||||
onCheckedChange = { enabled ->
|
onCheckedChange = { enabled ->
|
||||||
syncService.setAutoSyncEnabled(enabled)
|
syncService.setAutoSyncEnabled(enabled)
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -299,8 +307,8 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.errorContainer
|
MaterialTheme.colorScheme.errorContainer
|
||||||
.copy(alpha = 0.3f)
|
.copy(alpha = 0.3f),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text("Disconnect") },
|
headlineContent = { Text("Disconnect") },
|
||||||
@@ -309,17 +317,17 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
Icon(
|
Icon(
|
||||||
Icons.Default.CloudOff,
|
Icons.Default.CloudOff,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
trailingContent = {
|
trailingContent = {
|
||||||
TextButton(onClick = { showDisconnectDialog = true }) {
|
TextButton(onClick = { showDisconnectDialog = true }) {
|
||||||
Text(
|
Text(
|
||||||
"Disconnect",
|
"Disconnect",
|
||||||
color = MaterialTheme.colorScheme.error
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -330,8 +338,8 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.surfaceVariant
|
MaterialTheme.colorScheme.surfaceVariant
|
||||||
.copy(alpha = 0.3f)
|
.copy(alpha = 0.3f),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text("Setup Sync") },
|
headlineContent = { Text("Setup Sync") },
|
||||||
@@ -345,7 +353,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
TextButton(onClick = { showSyncConfigDialog = true }) {
|
TextButton(onClick = { showSyncConfigDialog = true }) {
|
||||||
Text("Setup")
|
Text("Setup")
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -358,23 +366,23 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.errorContainer
|
MaterialTheme.colorScheme.errorContainer,
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
modifier = Modifier.fillMaxWidth().padding(12.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Warning,
|
Icons.Default.Warning,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = error,
|
text = error,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onErrorContainer
|
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -391,7 +399,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
Text(
|
Text(
|
||||||
text = "Data Management",
|
text = "Data Management",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(12.dp))
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
@@ -403,15 +411,15 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text("Export Data with Images") },
|
headlineContent = { Text("Export Data with Images") },
|
||||||
supportingContent = {
|
supportingContent = {
|
||||||
Text(
|
Text(
|
||||||
"Export all your climbing data and images to ZIP file (recommended)"
|
"Export all your climbing data and images to ZIP file (recommended)",
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
leadingContent = {
|
leadingContent = {
|
||||||
@@ -429,18 +437,18 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
}.zip"
|
}.zip"
|
||||||
exportZipLauncher.launch(defaultFileName)
|
exportZipLauncher.launch(defaultFileName)
|
||||||
},
|
},
|
||||||
enabled = !uiState.isLoading
|
enabled = !uiState.isLoading,
|
||||||
) {
|
) {
|
||||||
if (uiState.isLoading) {
|
if (uiState.isLoading) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Text("Export ZIP")
|
Text("Export ZIP")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -452,9 +460,9 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text("Import Data") },
|
headlineContent = { Text("Import Data") },
|
||||||
@@ -467,18 +475,18 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
trailingContent = {
|
trailingContent = {
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = { importLauncher.launch("application/zip") },
|
onClick = { importLauncher.launch("application/zip") },
|
||||||
enabled = !uiState.isLoading
|
enabled = !uiState.isLoading,
|
||||||
) {
|
) {
|
||||||
if (uiState.isLoading) {
|
if (uiState.isLoading) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Text("Import")
|
Text("Import")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -490,9 +498,9 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.errorContainer.copy(
|
MaterialTheme.colorScheme.errorContainer.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text("Delete All Images") },
|
headlineContent = { Text("Delete All Images") },
|
||||||
@@ -503,24 +511,24 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Delete,
|
Icons.Default.Delete,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
trailingContent = {
|
trailingContent = {
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = { showDeleteImagesDialog = true },
|
onClick = { showDeleteImagesDialog = true },
|
||||||
enabled = !isDeletingImages && !uiState.isLoading
|
enabled = !isDeletingImages && !uiState.isLoading,
|
||||||
) {
|
) {
|
||||||
if (isDeletingImages) {
|
if (isDeletingImages) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Text("Delete", color = MaterialTheme.colorScheme.error)
|
Text("Delete", color = MaterialTheme.colorScheme.error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -532,39 +540,39 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.errorContainer.copy(
|
MaterialTheme.colorScheme.errorContainer.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
),
|
||||||
)
|
),
|
||||||
) {
|
) {
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text("Reset All Data") },
|
headlineContent = { Text("Reset All Data") },
|
||||||
supportingContent = {
|
supportingContent = {
|
||||||
Text(
|
Text(
|
||||||
"Permanently delete all gyms, problems, sessions, attempts, and images"
|
"Permanently delete all gyms, problems, sessions, attempts, and images",
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
leadingContent = {
|
leadingContent = {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Delete,
|
Icons.Default.Delete,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
trailingContent = {
|
trailingContent = {
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = { showResetDialog = true },
|
onClick = { showResetDialog = true },
|
||||||
enabled = !uiState.isLoading
|
enabled = !uiState.isLoading,
|
||||||
) {
|
) {
|
||||||
if (uiState.isLoading) {
|
if (uiState.isLoading) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Text("Reset", color = MaterialTheme.colorScheme.error)
|
Text("Reset", color = MaterialTheme.colorScheme.error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -578,7 +586,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
Text(
|
Text(
|
||||||
text = "App Information",
|
text = "App Information",
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.Bold
|
fontWeight = FontWeight.Bold,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(12.dp))
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
@@ -589,51 +597,16 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor =
|
containerColor =
|
||||||
MaterialTheme.colorScheme.surfaceVariant.copy(
|
MaterialTheme.colorScheme.surfaceVariant.copy(
|
||||||
alpha = 0.3f
|
alpha = 0.3f,
|
||||||
)
|
),
|
||||||
)
|
|
||||||
) {
|
|
||||||
ListItem(
|
|
||||||
headlineContent = {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
painter =
|
|
||||||
painterResource(
|
|
||||||
id = R.drawable.ic_mountains
|
|
||||||
),
|
),
|
||||||
contentDescription = "Ascently Logo",
|
|
||||||
modifier = Modifier.size(24.dp),
|
|
||||||
tint = MaterialTheme.colorScheme.primary
|
|
||||||
)
|
|
||||||
Text("Ascently")
|
|
||||||
}
|
|
||||||
},
|
|
||||||
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(
|
ListItem(
|
||||||
headlineContent = { Text("Version") },
|
headlineContent = { Text("Version") },
|
||||||
supportingContent = { Text(appVersion ?: "Unknown") },
|
supportingContent = { Text(appVersion ?: "Unknown") },
|
||||||
leadingContent = {
|
leadingContent = {
|
||||||
Icon(Icons.Default.Info, contentDescription = null)
|
Icon(Icons.Default.Info, contentDescription = null)
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -658,24 +631,24 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.primaryContainer
|
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||||
),
|
),
|
||||||
shape = RoundedCornerShape(12.dp)
|
shape = RoundedCornerShape(12.dp),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.CheckCircle,
|
Icons.Default.CheckCircle,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = message,
|
text = message,
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -691,24 +664,24 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
colors =
|
colors =
|
||||||
CardDefaults.cardColors(
|
CardDefaults.cardColors(
|
||||||
containerColor = MaterialTheme.colorScheme.errorContainer
|
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||||
),
|
),
|
||||||
shape = RoundedCornerShape(12.dp)
|
shape = RoundedCornerShape(12.dp),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Warning,
|
Icons.Default.Warning,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.error
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = error,
|
text = error,
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onErrorContainer
|
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -726,14 +699,14 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
Text(
|
Text(
|
||||||
text = "This will permanently delete:",
|
text = "This will permanently delete:",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
Text(
|
Text(
|
||||||
text =
|
text =
|
||||||
"• All gyms and their information\n• All problems and their images\n• All climbing sessions\n• All attempts and progress data",
|
"• 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,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.error
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
Text(
|
Text(
|
||||||
@@ -741,7 +714,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
"This action cannot be undone. Consider exporting your data first.",
|
"This action cannot be undone. Consider exporting your data first.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
fontWeight = FontWeight.Medium,
|
fontWeight = FontWeight.Medium,
|
||||||
color = MaterialTheme.colorScheme.error
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -750,12 +723,12 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
onClick = {
|
onClick = {
|
||||||
viewModel.resetAllData()
|
viewModel.resetAllData()
|
||||||
showResetDialog = false
|
showResetDialog = false
|
||||||
}
|
},
|
||||||
) { Text("Reset All Data", color = MaterialTheme.colorScheme.error) }
|
) { Text("Reset All Data", color = MaterialTheme.colorScheme.error) }
|
||||||
},
|
},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
TextButton(onClick = { showResetDialog = false }) { Text("Cancel") }
|
TextButton(onClick = { showResetDialog = false }) { Text("Cancel") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -772,7 +745,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
label = { Text("Server URL") },
|
label = { Text("Server URL") },
|
||||||
placeholder = { Text("https://your-server.com") },
|
placeholder = { Text("https://your-server.com") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true
|
singleLine = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
@@ -783,7 +756,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
label = { Text("Auth Token") },
|
label = { Text("Auth Token") },
|
||||||
placeholder = { Text("your-secret-token") },
|
placeholder = { Text("your-secret-token") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true
|
singleLine = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
@@ -792,66 +765,66 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
if (isTesting) {
|
if (isTesting) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Testing connection...",
|
text = "Testing connection...",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.primary
|
color = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else if (isConnected && isConfigured) {
|
} else if (isConnected && isConfigured) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.CheckCircle,
|
Icons.Default.CheckCircle,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier.size(16.dp)
|
modifier = Modifier.size(16.dp),
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Connection successful",
|
text = "Connection successful",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.primary
|
color = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else if (syncError != null && isConfigured) {
|
} else if (syncError != null && isConfigured) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Error,
|
Icons.Default.Error,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.error,
|
tint = MaterialTheme.colorScheme.error,
|
||||||
modifier = Modifier.size(16.dp)
|
modifier = Modifier.size(16.dp),
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Connection failed: $syncError",
|
text = "Connection failed: $syncError",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.error
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else if (isConfigured) {
|
} else if (isConfigured) {
|
||||||
Text(
|
Text(
|
||||||
text = "Test connection before enabling sync features",
|
text = "Test connection before enabling sync features",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Text(
|
Text(
|
||||||
text = "Enter your server URL and auth token to enable sync",
|
text = "Enter your server URL and auth token to enable sync",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -872,7 +845,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
showSyncConfigDialog = false
|
showSyncConfigDialog = false
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
viewModel.setError(
|
viewModel.setError(
|
||||||
"Failed to save and test: ${e.message}"
|
"Failed to save and test: ${e.message}",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -880,14 +853,14 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
enabled =
|
enabled =
|
||||||
!isTesting &&
|
!isTesting &&
|
||||||
serverUrl.isNotBlank() &&
|
serverUrl.isNotBlank() &&
|
||||||
authToken.isNotBlank()
|
authToken.isNotBlank(),
|
||||||
) {
|
) {
|
||||||
if (isTesting) {
|
if (isTesting) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
strokeWidth = 2.dp,
|
strokeWidth = 2.dp,
|
||||||
color = MaterialTheme.colorScheme.onPrimary
|
color = MaterialTheme.colorScheme.onPrimary,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text("Save & Test")
|
Text("Save & Test")
|
||||||
@@ -916,7 +889,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
viewModel.setError(
|
viewModel.setError(
|
||||||
"Connection test failed: ${e.message}"
|
"Connection test failed: ${e.message}",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -924,7 +897,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
enabled =
|
enabled =
|
||||||
!isTesting &&
|
!isTesting &&
|
||||||
serverUrl.isNotBlank() &&
|
serverUrl.isNotBlank() &&
|
||||||
authToken.isNotBlank()
|
authToken.isNotBlank(),
|
||||||
) { Text("Test Only") }
|
) { Text("Test Only") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -935,9 +908,9 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
serverUrl = syncService.serverUrl
|
serverUrl = syncService.serverUrl
|
||||||
authToken = syncService.authToken
|
authToken = syncService.authToken
|
||||||
showSyncConfigDialog = false
|
showSyncConfigDialog = false
|
||||||
}
|
},
|
||||||
) { Text("Cancel") }
|
) { Text("Cancel") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -948,7 +921,7 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
title = { Text("Disconnect from Sync") },
|
title = { Text("Disconnect from Sync") },
|
||||||
text = {
|
text = {
|
||||||
Text(
|
Text(
|
||||||
"Are you sure you want to disconnect from the sync server? This will clear your server configuration and disable auto-sync."
|
"Are you sure you want to disconnect from the sync server? This will clear your server configuration and disable auto-sync.",
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
@@ -956,12 +929,12 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
onClick = {
|
onClick = {
|
||||||
viewModel.syncService.clearConfiguration()
|
viewModel.syncService.clearConfiguration()
|
||||||
showDisconnectDialog = false
|
showDisconnectDialog = false
|
||||||
}
|
},
|
||||||
) { Text("Disconnect") }
|
) { Text("Disconnect") }
|
||||||
},
|
},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
TextButton(onClick = { showDisconnectDialog = false }) { Text("Cancel") }
|
TextButton(onClick = { showDisconnectDialog = false }) { Text("Cancel") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -972,7 +945,10 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
title = { Text("Delete All Images") },
|
title = { Text("Delete All Images") },
|
||||||
text = {
|
text = {
|
||||||
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."
|
"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 = {
|
confirmButton = {
|
||||||
@@ -985,12 +961,12 @@ fun SettingsScreen(viewModel: ClimbViewModel) {
|
|||||||
isDeletingImages = false
|
isDeletingImages = false
|
||||||
viewModel.setMessage("All images deleted successfully!")
|
viewModel.setMessage("All images deleted successfully!")
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
) { Text("Delete", color = MaterialTheme.colorScheme.error) }
|
) { Text("Delete", color = MaterialTheme.colorScheme.error) }
|
||||||
},
|
},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
TextButton(onClick = { showDeleteImagesDialog = false }) { Text("Cancel") }
|
TextButton(onClick = { showDeleteImagesDialog = false }) { Text("Cancel") }
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ object CustomIcons {
|
|||||||
defaultWidth = 24.dp,
|
defaultWidth = 24.dp,
|
||||||
defaultHeight = 24.dp,
|
defaultHeight = 24.dp,
|
||||||
viewportWidth = 24f,
|
viewportWidth = 24f,
|
||||||
viewportHeight = 24f
|
viewportHeight = 24f,
|
||||||
).path(
|
).path(
|
||||||
fill = SolidColor(color)
|
fill = SolidColor(color),
|
||||||
) {
|
) {
|
||||||
moveTo(6f, 6f)
|
moveTo(6f, 6f)
|
||||||
horizontalLineTo(18f)
|
horizontalLineTo(18f)
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ private val DarkColorScheme = darkColorScheme(
|
|||||||
surfaceContainerLow = ClimbNeutral10,
|
surfaceContainerLow = ClimbNeutral10,
|
||||||
surfaceContainer = ClimbNeutral12,
|
surfaceContainer = ClimbNeutral12,
|
||||||
surfaceContainerHigh = ClimbNeutral17,
|
surfaceContainerHigh = ClimbNeutral17,
|
||||||
surfaceContainerHighest = ClimbNeutral22
|
surfaceContainerHighest = ClimbNeutral22,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Climbing-themed light color scheme with full Material You compatibility
|
// Climbing-themed light color scheme with full Material You compatibility
|
||||||
@@ -84,7 +84,7 @@ private val LightColorScheme = lightColorScheme(
|
|||||||
surfaceContainerLow = ClimbNeutral96,
|
surfaceContainerLow = ClimbNeutral96,
|
||||||
surfaceContainer = ClimbNeutral94,
|
surfaceContainer = ClimbNeutral94,
|
||||||
surfaceContainerHigh = ClimbNeutral92,
|
surfaceContainerHigh = ClimbNeutral92,
|
||||||
surfaceContainerHighest = ClimbNeutral90
|
surfaceContainerHighest = ClimbNeutral90,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -93,7 +93,7 @@ fun AscentlyTheme(
|
|||||||
// Dynamic color is available on Android 12+ and provides full Material You theming
|
// Dynamic color is available on Android 12+ and provides full Material You theming
|
||||||
// When enabled, it adapts to the user's system wallpaper colors
|
// When enabled, it adapts to the user's system wallpaper colors
|
||||||
dynamicColor: Boolean = true,
|
dynamicColor: Boolean = true,
|
||||||
content: @Composable () -> Unit
|
content: @Composable () -> Unit,
|
||||||
) {
|
) {
|
||||||
val colorScheme = when {
|
val colorScheme = when {
|
||||||
dynamicColor && true -> {
|
dynamicColor && true -> {
|
||||||
@@ -116,6 +116,6 @@ fun AscentlyTheme(
|
|||||||
MaterialTheme(
|
MaterialTheme(
|
||||||
colorScheme = colorScheme,
|
colorScheme = colorScheme,
|
||||||
typography = Typography,
|
typography = Typography,
|
||||||
content = content
|
content = content,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,6 @@ val Typography = Typography(
|
|||||||
fontWeight = FontWeight.Normal,
|
fontWeight = FontWeight.Normal,
|
||||||
fontSize = 16.sp,
|
fontSize = 16.sp,
|
||||||
lineHeight = 24.sp,
|
lineHeight = 24.sp,
|
||||||
letterSpacing = 0.5.sp
|
letterSpacing = 0.5.sp,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
@@ -8,16 +8,17 @@ import com.atridad.ascently.data.model.*
|
|||||||
import com.atridad.ascently.data.repository.ClimbRepository
|
import com.atridad.ascently.data.repository.ClimbRepository
|
||||||
import com.atridad.ascently.data.sync.SyncService
|
import com.atridad.ascently.data.sync.SyncService
|
||||||
import com.atridad.ascently.service.SessionTrackingService
|
import com.atridad.ascently.service.SessionTrackingService
|
||||||
|
import com.atridad.ascently.utils.AppLogger
|
||||||
import com.atridad.ascently.utils.ImageUtils
|
import com.atridad.ascently.utils.ImageUtils
|
||||||
import com.atridad.ascently.widget.ClimbStatsWidgetProvider
|
import com.atridad.ascently.widget.ClimbStatsWidgetProvider
|
||||||
import java.io.File
|
|
||||||
import kotlinx.coroutines.flow.*
|
import kotlinx.coroutines.flow.*
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
class ClimbViewModel(
|
class ClimbViewModel(
|
||||||
private val repository: ClimbRepository,
|
private val repository: ClimbRepository,
|
||||||
val syncService: SyncService,
|
val syncService: SyncService,
|
||||||
private val context: Context
|
private val context: Context,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
// Health Connect manager
|
// Health Connect manager
|
||||||
@@ -34,7 +35,7 @@ class ClimbViewModel(
|
|||||||
.stateIn(
|
.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(),
|
started = SharingStarted.WhileSubscribed(),
|
||||||
initialValue = emptyList()
|
initialValue = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
val problems =
|
val problems =
|
||||||
@@ -43,7 +44,7 @@ class ClimbViewModel(
|
|||||||
.stateIn(
|
.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(),
|
started = SharingStarted.WhileSubscribed(),
|
||||||
initialValue = emptyList()
|
initialValue = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
val sessions =
|
val sessions =
|
||||||
@@ -52,7 +53,7 @@ class ClimbViewModel(
|
|||||||
.stateIn(
|
.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(),
|
started = SharingStarted.WhileSubscribed(),
|
||||||
initialValue = emptyList()
|
initialValue = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
val activeSession =
|
val activeSession =
|
||||||
@@ -61,7 +62,7 @@ class ClimbViewModel(
|
|||||||
.stateIn(
|
.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(),
|
started = SharingStarted.WhileSubscribed(),
|
||||||
initialValue = null
|
initialValue = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
val attempts =
|
val attempts =
|
||||||
@@ -70,7 +71,7 @@ class ClimbViewModel(
|
|||||||
.stateIn(
|
.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(),
|
started = SharingStarted.WhileSubscribed(),
|
||||||
initialValue = emptyList()
|
initialValue = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Gym operations
|
// Gym operations
|
||||||
@@ -192,7 +193,7 @@ class ClimbViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
println("Deleted $deletedCount image files and cleared image references")
|
AppLogger.i("ClimbViewModel") { "Deleted $deletedCount image files and cleared image references" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,41 +234,35 @@ class ClimbViewModel(
|
|||||||
// Active session management
|
// Active session management
|
||||||
fun startSession(context: Context, gymId: String, notes: String? = null) {
|
fun startSession(context: Context, gymId: String, notes: String? = null) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
android.util.Log.d("ClimbViewModel", "startSession called with gymId: $gymId")
|
AppLogger.d("ClimbViewModel") { "startSession called with gymId: $gymId" }
|
||||||
|
|
||||||
if (!com.atridad.ascently.utils.NotificationPermissionUtils
|
if (!com.atridad.ascently.utils.NotificationPermissionUtils
|
||||||
.isNotificationPermissionGranted(context)
|
.isNotificationPermissionGranted(context)
|
||||||
) {
|
) {
|
||||||
android.util.Log.d("ClimbViewModel", "Notification permission not granted")
|
AppLogger.d("ClimbViewModel") { "Notification permission not granted" }
|
||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
error =
|
error =
|
||||||
"Notification permission is required to track your climbing session. Please enable notifications in settings."
|
"Notification permission is required to track your climbing session. Please enable notifications in settings.",
|
||||||
)
|
)
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
|
||||||
val existingActive = repository.getActiveSession()
|
val existingActive = repository.getActiveSession()
|
||||||
if (existingActive != null) {
|
if (existingActive != null) {
|
||||||
android.util.Log.d(
|
AppLogger.d("ClimbViewModel") { "Active session already exists: ${existingActive.id}" }
|
||||||
"ClimbViewModel",
|
|
||||||
"Active session already exists: ${existingActive.id}"
|
|
||||||
)
|
|
||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
error = "There's already an active session. Please end it first."
|
error = "There's already an active session. Please end it first.",
|
||||||
)
|
)
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
|
||||||
android.util.Log.d("ClimbViewModel", "Creating new session")
|
AppLogger.d("ClimbViewModel") { "Creating new session" }
|
||||||
val newSession = ClimbSession.create(gymId = gymId, notes = notes)
|
val newSession = ClimbSession.create(gymId = gymId, notes = notes)
|
||||||
repository.insertSession(newSession)
|
repository.insertSession(newSession)
|
||||||
|
|
||||||
android.util.Log.d(
|
AppLogger.d("ClimbViewModel") { "Starting tracking service for session: ${newSession.id}" }
|
||||||
"ClimbViewModel",
|
|
||||||
"Starting tracking service for session: ${newSession.id}"
|
|
||||||
)
|
|
||||||
// Start the tracking service
|
// Start the tracking service
|
||||||
val serviceIntent = SessionTrackingService.createStartIntent(context, newSession.id)
|
val serviceIntent = SessionTrackingService.createStartIntent(context, newSession.id)
|
||||||
context.startForegroundService(serviceIntent)
|
context.startForegroundService(serviceIntent)
|
||||||
@@ -286,7 +281,7 @@ class ClimbViewModel(
|
|||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
error =
|
error =
|
||||||
"Notification permission is required to manage your climbing session. Please enable notifications in settings."
|
"Notification permission is required to manage your climbing session. Please enable notifications in settings.",
|
||||||
)
|
)
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
@@ -359,20 +354,20 @@ class ClimbViewModel(
|
|||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
isLoading = true,
|
isLoading = true,
|
||||||
message = "Creating ZIP file with images..."
|
message = "Creating ZIP file with images...",
|
||||||
)
|
)
|
||||||
repository.exportAllDataToZipUri(context, uri)
|
repository.exportAllDataToZipUri(context, uri)
|
||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
message =
|
message =
|
||||||
"Export complete! Your climbing data and images have been saved."
|
"Export complete! Your climbing data and images have been saved.",
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
error = "Export failed: ${e.message}"
|
error = "Export failed: ${e.message}",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -385,7 +380,7 @@ class ClimbViewModel(
|
|||||||
|
|
||||||
if (!file.name.lowercase().endsWith(".zip")) {
|
if (!file.name.lowercase().endsWith(".zip")) {
|
||||||
throw Exception(
|
throw Exception(
|
||||||
"Only ZIP files are supported for import. Please use a ZIP file exported from Ascently."
|
"Only ZIP files are supported for import. Please use a ZIP file exported from Ascently.",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -394,13 +389,13 @@ class ClimbViewModel(
|
|||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
message = "Data imported successfully from ${file.name}"
|
message = "Data imported successfully from ${file.name}",
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
error = "Import failed: ${e.message}"
|
error = "Import failed: ${e.message}",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -416,13 +411,15 @@ class ClimbViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sync-related methods
|
// Sync-related methods
|
||||||
suspend fun performManualSync() {
|
fun performManualSync() {
|
||||||
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
syncService.syncWithServer()
|
syncService.syncWithServer()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
setError("Sync failed: ${e.message}")
|
setError("Sync failed: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun testSyncConnection() {
|
suspend fun testSyncConnection() {
|
||||||
try {
|
try {
|
||||||
@@ -450,7 +447,7 @@ class ClimbViewModel(
|
|||||||
_uiState.value =
|
_uiState.value =
|
||||||
_uiState.value.copy(
|
_uiState.value.copy(
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
message = "All data has been reset successfully"
|
message = "All data has been reset successfully",
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value =
|
_uiState.value =
|
||||||
@@ -472,20 +469,17 @@ class ClimbViewModel(
|
|||||||
healthConnectManager.autoSyncCompletedSession(
|
healthConnectManager.autoSyncCompletedSession(
|
||||||
session,
|
session,
|
||||||
gymName,
|
gymName,
|
||||||
attemptCount
|
attemptCount,
|
||||||
)
|
)
|
||||||
|
|
||||||
result.onFailure { error ->
|
result.onFailure { error ->
|
||||||
if (healthConnectManager.isReadySync()) {
|
if (healthConnectManager.isReadySync()) {
|
||||||
android.util.Log.w(
|
AppLogger.w("ClimbViewModel") { "Health Connect sync failed: ${error.message}" }
|
||||||
"ClimbViewModel",
|
|
||||||
"Health Connect sync failed: ${error.message}"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
if (healthConnectManager.isReadySync()) {
|
if (healthConnectManager.isReadySync()) {
|
||||||
android.util.Log.w("ClimbViewModel", "Health Connect sync error: ${e.message}")
|
AppLogger.w("ClimbViewModel") { "Health Connect sync error: ${e.message}" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -495,5 +489,5 @@ class ClimbViewModel(
|
|||||||
data class ClimbUiState(
|
data class ClimbUiState(
|
||||||
val isLoading: Boolean = false,
|
val isLoading: Boolean = false,
|
||||||
val message: String? = null,
|
val message: String? = null,
|
||||||
val error: String? = null
|
val error: String? = null,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import com.atridad.ascently.data.sync.SyncService
|
|||||||
class ClimbViewModelFactory(
|
class ClimbViewModelFactory(
|
||||||
private val repository: ClimbRepository,
|
private val repository: ClimbRepository,
|
||||||
private val syncService: SyncService,
|
private val syncService: SyncService,
|
||||||
private val context: Context
|
private val context: Context,
|
||||||
) : ViewModelProvider.Factory {
|
) : ViewModelProvider.Factory {
|
||||||
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
@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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,7 +22,6 @@ object DateFormatUtils {
|
|||||||
return try {
|
return try {
|
||||||
Instant.from(ISO_FORMATTER.parse(dateString))
|
Instant.from(ISO_FORMATTER.parse(dateString))
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Instant.parse(dateString)
|
Instant.parse(dateString)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ object ImageNamingUtils {
|
|||||||
|
|
||||||
/** Generates a deterministic filename for a problem image */
|
/** Generates a deterministic filename for a problem image */
|
||||||
fun generateImageFilename(problemId: String, imageIndex: Int): String {
|
fun generateImageFilename(problemId: String, imageIndex: Int): String {
|
||||||
val input = "${problemId}_${imageIndex}"
|
val input = "${problemId}_$imageIndex"
|
||||||
val hash = createHash(input)
|
val hash = createHash(input)
|
||||||
|
|
||||||
return "problem_${hash}_${imageIndex}${IMAGE_EXTENSION}"
|
return "problem_${hash}_${imageIndex}${IMAGE_EXTENSION}"
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import android.graphics.Bitmap
|
|||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
import android.graphics.ImageDecoder
|
import android.graphics.ImageDecoder
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.util.Log
|
|
||||||
import androidx.core.graphics.scale
|
import androidx.core.graphics.scale
|
||||||
import androidx.exifinterface.media.ExifInterface
|
import androidx.exifinterface.media.ExifInterface
|
||||||
import java.io.File
|
import java.io.File
|
||||||
@@ -33,7 +32,7 @@ object ImageUtils {
|
|||||||
context: Context,
|
context: Context,
|
||||||
imageUri: Uri,
|
imageUri: Uri,
|
||||||
originalBitmap: Bitmap,
|
originalBitmap: Bitmap,
|
||||||
outputFile: File
|
outputFile: File,
|
||||||
): Boolean {
|
): Boolean {
|
||||||
return try {
|
return try {
|
||||||
// Get EXIF data from original image
|
// Get EXIF data from original image
|
||||||
@@ -73,7 +72,7 @@ object ImageUtils {
|
|||||||
compressedBitmap.recycle()
|
compressedBitmap.recycle()
|
||||||
true
|
true
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e("ImageUtils", e) { "Error saving image with EXIF data" }
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,7 +118,7 @@ object ImageUtils {
|
|||||||
val file = getImageFile(context, relativePath)
|
val file = getImageFile(context, relativePath)
|
||||||
file.delete()
|
file.delete()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e("ImageUtils", e) { "Failed to delete image: $relativePath" }
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,7 +136,7 @@ object ImageUtils {
|
|||||||
sourceFile.copyTo(destFile, overwrite = true)
|
sourceFile.copyTo(destFile, overwrite = true)
|
||||||
"$IMAGES_DIR/$filename"
|
"$IMAGES_DIR/$filename"
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e("ImageUtils", e) { "Failed to import image from source: ${sourceFile.name}" }
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -148,16 +147,20 @@ object ImageUtils {
|
|||||||
val imagesDir = getImagesDirectory(context)
|
val imagesDir = getImagesDirectory(context)
|
||||||
imagesDir.listFiles()?.mapNotNull { file ->
|
imagesDir.listFiles()?.mapNotNull { file ->
|
||||||
if (file.isFile &&
|
if (file.isFile &&
|
||||||
(file.extension == "jpg" ||
|
(
|
||||||
|
file.extension == "jpg" ||
|
||||||
file.extension == "jpeg" ||
|
file.extension == "jpeg" ||
|
||||||
file.extension == "png")
|
file.extension == "png"
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
"$IMAGES_DIR/${file.name}"
|
"$IMAGES_DIR/${file.name}"
|
||||||
} else null
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
?: emptyList()
|
?: emptyList()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e("ImageUtils", e) { "Failed to enumerate images directory" }
|
||||||
emptyList()
|
emptyList()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,7 +181,7 @@ object ImageUtils {
|
|||||||
|
|
||||||
tempFilename
|
tempFilename
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e("ImageUtils", "Error saving temporary image from URI", e)
|
AppLogger.e("ImageUtils", e) { "Error saving temporary image from URI" }
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,12 +191,12 @@ object ImageUtils {
|
|||||||
context: Context,
|
context: Context,
|
||||||
tempFilename: String,
|
tempFilename: String,
|
||||||
problemId: String,
|
problemId: String,
|
||||||
imageIndex: Int
|
imageIndex: Int,
|
||||||
): String? {
|
): String? {
|
||||||
return try {
|
return try {
|
||||||
val tempFile = File(getImagesDirectory(context), tempFilename)
|
val tempFile = File(getImagesDirectory(context), tempFilename)
|
||||||
if (!tempFile.exists()) {
|
if (!tempFile.exists()) {
|
||||||
Log.e("ImageUtils", "Temporary file does not exist: $tempFilename")
|
AppLogger.e("ImageUtils") { "Temporary file does not exist: $tempFilename" }
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,17 +205,14 @@ object ImageUtils {
|
|||||||
val finalFile = File(getImagesDirectory(context), deterministicFilename)
|
val finalFile = File(getImagesDirectory(context), deterministicFilename)
|
||||||
|
|
||||||
if (tempFile.renameTo(finalFile)) {
|
if (tempFile.renameTo(finalFile)) {
|
||||||
Log.d(
|
AppLogger.d("ImageUtils") { "Renamed temporary image: $tempFilename -> $deterministicFilename" }
|
||||||
"ImageUtils",
|
|
||||||
"Renamed temporary image: $tempFilename -> $deterministicFilename"
|
|
||||||
)
|
|
||||||
deterministicFilename
|
deterministicFilename
|
||||||
} else {
|
} else {
|
||||||
Log.e("ImageUtils", "Failed to rename temporary image: $tempFilename")
|
AppLogger.e("ImageUtils") { "Failed to rename temporary image: $tempFilename" }
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e("ImageUtils", "Error renaming temporary image", e)
|
AppLogger.e("ImageUtils", e) { "Error renaming temporary image" }
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -221,7 +221,7 @@ object ImageUtils {
|
|||||||
fun saveImageFromBytesWithFilename(
|
fun saveImageFromBytesWithFilename(
|
||||||
context: Context,
|
context: Context,
|
||||||
imageData: ByteArray,
|
imageData: ByteArray,
|
||||||
filename: String
|
filename: String,
|
||||||
): String? {
|
): String? {
|
||||||
return try {
|
return try {
|
||||||
val imageFile = File(getImagesDirectory(context), filename)
|
val imageFile = File(getImagesDirectory(context), filename)
|
||||||
@@ -249,7 +249,7 @@ object ImageUtils {
|
|||||||
destExif.saveAttributes()
|
destExif.saveAttributes()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// If EXIF preservation fails, continue without it
|
// If EXIF preservation fails, continue without it
|
||||||
Log.w("ImageUtils", "Failed to preserve EXIF data: ${e.message}")
|
AppLogger.w("ImageUtils") { "Failed to preserve EXIF data: ${e.message}" }
|
||||||
}
|
}
|
||||||
|
|
||||||
bitmap.recycle()
|
bitmap.recycle()
|
||||||
@@ -262,7 +262,7 @@ object ImageUtils {
|
|||||||
// Return relative path
|
// Return relative path
|
||||||
"$IMAGES_DIR/$filename"
|
"$IMAGES_DIR/$filename"
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e("ImageUtils", e) { "Failed to save image from bytes: $filename" }
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -275,7 +275,7 @@ object ImageUtils {
|
|||||||
|
|
||||||
orphanedImages.forEach { path -> deleteImage(context, path) }
|
orphanedImages.forEach { path -> deleteImage(context, path) }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
AppLogger.e("ImageUtils", e) { "Failed to clean up orphaned images" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package com.atridad.ascently.utils
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import android.util.Log
|
|
||||||
import androidx.core.content.edit
|
import androidx.core.content.edit
|
||||||
|
|
||||||
class MigrationManager(private val context: Context) {
|
class MigrationManager(private val context: Context) {
|
||||||
@@ -22,11 +21,11 @@ class MigrationManager(private val context: Context) {
|
|||||||
*/
|
*/
|
||||||
fun migrateIfNeeded() {
|
fun migrateIfNeeded() {
|
||||||
if (migrationPrefs.getBoolean(MIGRATION_COMPLETED_KEY, false)) {
|
if (migrationPrefs.getBoolean(MIGRATION_COMPLETED_KEY, false)) {
|
||||||
Log.d(TAG, "Migration already completed, skipping")
|
AppLogger.d(TAG) { "Migration already completed, skipping" }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.i(TAG, "🔄 Starting migration from OpenClimb to Ascently...")
|
AppLogger.i(TAG) { "🔄 Starting migration from OpenClimb to Ascently..." }
|
||||||
var migrationCount = 0
|
var migrationCount = 0
|
||||||
|
|
||||||
// Migrate SharedPreferences
|
// Migrate SharedPreferences
|
||||||
@@ -36,12 +35,9 @@ class MigrationManager(private val context: Context) {
|
|||||||
migrationPrefs.edit { putBoolean(MIGRATION_COMPLETED_KEY, true) }
|
migrationPrefs.edit { putBoolean(MIGRATION_COMPLETED_KEY, true) }
|
||||||
|
|
||||||
if (migrationCount > 0) {
|
if (migrationCount > 0) {
|
||||||
Log.i(
|
AppLogger.i(TAG) { "🎉 Migration completed! Migrated $migrationCount items from OpenClimb to Ascently" }
|
||||||
TAG,
|
|
||||||
"🎉 Migration completed! Migrated $migrationCount items from OpenClimb to Ascently"
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
Log.i(TAG, "ℹ️ No OpenClimb data found to migrate")
|
AppLogger.i(TAG) { "ℹ️ No OpenClimb data found to migrate" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +51,7 @@ class MigrationManager(private val context: Context) {
|
|||||||
"openclimb_data_state" to "ascently_data_state",
|
"openclimb_data_state" to "ascently_data_state",
|
||||||
"health_connect_prefs" to "health_connect_prefs", // Keep same name
|
"health_connect_prefs" to "health_connect_prefs", // Keep same name
|
||||||
"deleted_items" to "deleted_items", // Keep same name
|
"deleted_items" to "deleted_items", // Keep same name
|
||||||
"sync_preferences" to "sync_preferences" // Keep same name
|
"sync_preferences" to "sync_preferences", // Keep same name
|
||||||
)
|
)
|
||||||
|
|
||||||
for ((oldFileName, newFileName) in preferenceFileMigrations) {
|
for ((oldFileName, newFileName) in preferenceFileMigrations) {
|
||||||
@@ -86,7 +82,8 @@ class MigrationManager(private val context: Context) {
|
|||||||
is Float -> putFloat(key, value)
|
is Float -> putFloat(key, value)
|
||||||
is Boolean -> putBoolean(key, value)
|
is Boolean -> putBoolean(key, value)
|
||||||
is Set<*> -> {
|
is Set<*> -> {
|
||||||
@Suppress("UNCHECKED_CAST") putStringSet(key, value as Set<String>)
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
putStringSet(key, value as Set<String>)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,10 +92,7 @@ class MigrationManager(private val context: Context) {
|
|||||||
// Clear old preferences
|
// Clear old preferences
|
||||||
oldPrefs.edit { clear() }
|
oldPrefs.edit { clear() }
|
||||||
|
|
||||||
Log.d(
|
AppLogger.d(TAG) { "Migrated preference file: $oldFileName → $newFileName (${oldPrefs.all.size} keys)" }
|
||||||
TAG,
|
|
||||||
"✅ Migrated preference file: $oldFileName → $newFileName (${oldPrefs.all.size} keys)"
|
|
||||||
)
|
|
||||||
return oldPrefs.all.size
|
return oldPrefs.all.size
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +109,7 @@ class MigrationManager(private val context: Context) {
|
|||||||
"ascently_data_state",
|
"ascently_data_state",
|
||||||
"health_connect_prefs",
|
"health_connect_prefs",
|
||||||
"deleted_items",
|
"deleted_items",
|
||||||
"sync_preferences"
|
"sync_preferences",
|
||||||
)
|
)
|
||||||
|
|
||||||
for (prefFileName in preferencesToCheck) {
|
for (prefFileName in preferencesToCheck) {
|
||||||
@@ -150,7 +144,7 @@ class MigrationManager(private val context: Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d(TAG, "✅ Migrated ${keysToMigrate.size} keys in $prefFileName")
|
AppLogger.d(TAG) { "Migrated ${keysToMigrate.size} keys in $prefFileName" }
|
||||||
count += keysToMigrate.size
|
count += keysToMigrate.size
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,6 +160,6 @@ class MigrationManager(private val context: Context) {
|
|||||||
/** Reset migration state (for testing purposes) */
|
/** Reset migration state (for testing purposes) */
|
||||||
fun resetMigrationState() {
|
fun resetMigrationState() {
|
||||||
migrationPrefs.edit { putBoolean(MIGRATION_COMPLETED_KEY, false) }
|
migrationPrefs.edit { putBoolean(MIGRATION_COMPLETED_KEY, false) }
|
||||||
Log.d(TAG, "Migration state reset")
|
AppLogger.d(TAG) { "Migration state reset" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ object NotificationPermissionUtils {
|
|||||||
fun isNotificationPermissionGranted(context: Context): Boolean {
|
fun isNotificationPermissionGranted(context: Context): Boolean {
|
||||||
return ContextCompat.checkSelfPermission(
|
return ContextCompat.checkSelfPermission(
|
||||||
context,
|
context,
|
||||||
Manifest.permission.POST_NOTIFICATIONS
|
Manifest.permission.POST_NOTIFICATIONS,
|
||||||
) == PackageManager.PERMISSION_GRANTED
|
) == PackageManager.PERMISSION_GRANTED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ object AppShortcutManager {
|
|||||||
context: Context,
|
context: Context,
|
||||||
hasActiveSession: Boolean,
|
hasActiveSession: Boolean,
|
||||||
hasGyms: Boolean,
|
hasGyms: Boolean,
|
||||||
lastUsedGym: com.atridad.ascently.data.model.Gym? = null
|
lastUsedGym: com.atridad.ascently.data.model.Gym? = null,
|
||||||
) {
|
) {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
|
||||||
val shortcutManager = context.getSystemService(ShortcutManager::class.java)
|
val shortcutManager = context.getSystemService(ShortcutManager::class.java)
|
||||||
@@ -45,7 +45,7 @@ object AppShortcutManager {
|
|||||||
@RequiresApi(Build.VERSION_CODES.N_MR1)
|
@RequiresApi(Build.VERSION_CODES.N_MR1)
|
||||||
private fun createStartSessionShortcut(
|
private fun createStartSessionShortcut(
|
||||||
context: Context,
|
context: Context,
|
||||||
lastUsedGym: com.atridad.ascently.data.model.Gym? = null
|
lastUsedGym: com.atridad.ascently.data.model.Gym? = null,
|
||||||
): ShortcutInfo {
|
): ShortcutInfo {
|
||||||
val startIntent =
|
val startIntent =
|
||||||
Intent(context, MainActivity::class.java).apply {
|
Intent(context, MainActivity::class.java).apply {
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package com.atridad.ascently.utils
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.atridad.ascently.data.format.BackupProblem
|
import com.atridad.ascently.data.format.BackupProblem
|
||||||
import com.atridad.ascently.data.format.ClimbDataBackup
|
import com.atridad.ascently.data.format.ClimbDataBackup
|
||||||
|
import kotlinx.serialization.encodeToString
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileInputStream
|
import java.io.FileInputStream
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
@@ -11,8 +13,6 @@ import java.time.LocalDateTime
|
|||||||
import java.util.zip.ZipEntry
|
import java.util.zip.ZipEntry
|
||||||
import java.util.zip.ZipInputStream
|
import java.util.zip.ZipInputStream
|
||||||
import java.util.zip.ZipOutputStream
|
import java.util.zip.ZipOutputStream
|
||||||
import kotlinx.serialization.encodeToString
|
|
||||||
import kotlinx.serialization.json.Json
|
|
||||||
|
|
||||||
object ZipExportImportUtils {
|
object ZipExportImportUtils {
|
||||||
|
|
||||||
@@ -25,15 +25,15 @@ object ZipExportImportUtils {
|
|||||||
context: Context,
|
context: Context,
|
||||||
exportData: ClimbDataBackup,
|
exportData: ClimbDataBackup,
|
||||||
referencedImagePaths: Set<String>,
|
referencedImagePaths: Set<String>,
|
||||||
directory: File? = null
|
directory: File? = null,
|
||||||
): File {
|
): File {
|
||||||
val exportDir =
|
val exportDir =
|
||||||
directory
|
directory
|
||||||
?: File(
|
?: File(
|
||||||
context.getExternalFilesDir(
|
context.getExternalFilesDir(
|
||||||
android.os.Environment.DIRECTORY_DOCUMENTS
|
android.os.Environment.DIRECTORY_DOCUMENTS,
|
||||||
),
|
),
|
||||||
"Ascently"
|
"Ascently",
|
||||||
)
|
)
|
||||||
if (!exportDir.exists()) {
|
if (!exportDir.exists()) {
|
||||||
exportDir.mkdirs()
|
exportDir.mkdirs()
|
||||||
@@ -52,7 +52,8 @@ object ZipExportImportUtils {
|
|||||||
zipOut.closeEntry()
|
zipOut.closeEntry()
|
||||||
|
|
||||||
// Add JSON data file
|
// Add JSON data file
|
||||||
val json = Json {
|
val json =
|
||||||
|
Json {
|
||||||
prettyPrint = true
|
prettyPrint = true
|
||||||
ignoreUnknownKeys = true
|
ignoreUnknownKeys = true
|
||||||
}
|
}
|
||||||
@@ -78,24 +79,21 @@ object ZipExportImportUtils {
|
|||||||
zipOut.closeEntry()
|
zipOut.closeEntry()
|
||||||
successfulImages++
|
successfulImages++
|
||||||
} else {
|
} else {
|
||||||
android.util.Log.w(
|
AppLogger.w("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Image file not found or empty: $imagePath"
|
"Image file not found or empty: $imagePath"
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e(
|
AppLogger.e("ZipExportImportUtils", e) {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Failed to add image $imagePath: ${e.message}"
|
"Failed to add image $imagePath: ${e.message}"
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log export summary
|
// Log export summary
|
||||||
android.util.Log.i(
|
AppLogger.i("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
"Export completed: $successfulImages/${referencedImagePaths.size} images included"
|
||||||
"Export completed: ${successfulImages}/${referencedImagePaths.size} images included"
|
}
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate the created ZIP file
|
// Validate the created ZIP file
|
||||||
@@ -118,7 +116,7 @@ object ZipExportImportUtils {
|
|||||||
context: Context,
|
context: Context,
|
||||||
uri: android.net.Uri,
|
uri: android.net.Uri,
|
||||||
exportData: ClimbDataBackup,
|
exportData: ClimbDataBackup,
|
||||||
referencedImagePaths: Set<String>
|
referencedImagePaths: Set<String>,
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
context.contentResolver.openOutputStream(uri)?.use { outputStream ->
|
context.contentResolver.openOutputStream(uri)?.use { outputStream ->
|
||||||
@@ -131,7 +129,8 @@ object ZipExportImportUtils {
|
|||||||
zipOut.closeEntry()
|
zipOut.closeEntry()
|
||||||
|
|
||||||
// Add JSON data file
|
// Add JSON data file
|
||||||
val json = Json {
|
val json =
|
||||||
|
Json {
|
||||||
prettyPrint = true
|
prettyPrint = true
|
||||||
ignoreUnknownKeys = true
|
ignoreUnknownKeys = true
|
||||||
}
|
}
|
||||||
@@ -158,17 +157,15 @@ object ZipExportImportUtils {
|
|||||||
successfulImages++
|
successfulImages++
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e(
|
AppLogger.e("ZipExportImportUtils", e) {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Failed to add image $imagePath: ${e.message}"
|
"Failed to add image $imagePath: ${e.message}"
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
android.util.Log.i(
|
AppLogger.i("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
"Export to URI completed: $successfulImages/${referencedImagePaths.size} images included"
|
||||||
"Export to URI completed: ${successfulImages}/${referencedImagePaths.size} images included"
|
}
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
?: throw IOException("Could not open output stream")
|
?: throw IOException("Could not open output stream")
|
||||||
@@ -179,7 +176,7 @@ object ZipExportImportUtils {
|
|||||||
|
|
||||||
private fun createMetadata(
|
private fun createMetadata(
|
||||||
exportData: ClimbDataBackup,
|
exportData: ClimbDataBackup,
|
||||||
referencedImagePaths: Set<String>
|
referencedImagePaths: Set<String>,
|
||||||
): String {
|
): String {
|
||||||
return buildString {
|
return buildString {
|
||||||
appendLine("Ascently Export Metadata")
|
appendLine("Ascently Export Metadata")
|
||||||
@@ -198,7 +195,7 @@ object ZipExportImportUtils {
|
|||||||
/** Data class to hold extraction results */
|
/** Data class to hold extraction results */
|
||||||
data class ImportResult(
|
data class ImportResult(
|
||||||
val jsonContent: String,
|
val jsonContent: String,
|
||||||
val importedImagePaths: Map<String, String> // original filename -> new relative path
|
val importedImagePaths: Map<String, String>, // original filename -> new relative path
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Extracts a ZIP file and returns the JSON content and imported image paths */
|
/** Extracts a ZIP file and returns the JSON content and imported image paths */
|
||||||
@@ -217,16 +214,17 @@ object ZipExportImportUtils {
|
|||||||
// Read metadata for validation
|
// Read metadata for validation
|
||||||
val metadataContent = zipIn.readBytes().toString(Charsets.UTF_8)
|
val metadataContent = zipIn.readBytes().toString(Charsets.UTF_8)
|
||||||
foundRequiredFiles.add("metadata")
|
foundRequiredFiles.add("metadata")
|
||||||
android.util.Log.i(
|
AppLogger.i("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Found metadata: ${metadataContent.lines().take(3).joinToString()}"
|
"Found metadata: ${metadataContent.lines().take(3).joinToString()}"
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
entry.name == DATA_JSON_FILENAME -> {
|
entry.name == DATA_JSON_FILENAME -> {
|
||||||
// Read JSON data
|
// Read JSON data
|
||||||
jsonContent = zipIn.readBytes().toString(Charsets.UTF_8)
|
jsonContent = zipIn.readBytes().toString(Charsets.UTF_8)
|
||||||
foundRequiredFiles.add("data")
|
foundRequiredFiles.add("data")
|
||||||
}
|
}
|
||||||
|
|
||||||
entry.name.startsWith("$IMAGES_DIR_NAME/") && !entry.isDirectory -> {
|
entry.name.startsWith("$IMAGES_DIR_NAME/") && !entry.isDirectory -> {
|
||||||
// Extract image file
|
// Extract image file
|
||||||
val originalFilename = entry.name.substringAfter("$IMAGES_DIR_NAME/")
|
val originalFilename = entry.name.substringAfter("$IMAGES_DIR_NAME/")
|
||||||
@@ -237,7 +235,7 @@ object ZipExportImportUtils {
|
|||||||
File.createTempFile(
|
File.createTempFile(
|
||||||
"import_image_",
|
"import_image_",
|
||||||
"_$originalFilename",
|
"_$originalFilename",
|
||||||
context.cacheDir
|
context.cacheDir,
|
||||||
)
|
)
|
||||||
|
|
||||||
FileOutputStream(tempFile).use { output -> zipIn.copyTo(output) }
|
FileOutputStream(tempFile).use { output -> zipIn.copyTo(output) }
|
||||||
@@ -248,37 +246,33 @@ object ZipExportImportUtils {
|
|||||||
val newPath = ImageUtils.importImageFile(context, tempFile)
|
val newPath = ImageUtils.importImageFile(context, tempFile)
|
||||||
if (newPath != null) {
|
if (newPath != null) {
|
||||||
importedImagePaths[originalFilename] = newPath
|
importedImagePaths[originalFilename] = newPath
|
||||||
android.util.Log.d(
|
AppLogger.d("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Successfully imported image: $originalFilename -> $newPath"
|
"Successfully imported image: $originalFilename -> $newPath"
|
||||||
)
|
|
||||||
} else {
|
|
||||||
android.util.Log.w(
|
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Failed to import image: $originalFilename"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
android.util.Log.w(
|
AppLogger.w("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
"Failed to import image: $originalFilename"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
AppLogger.w("ZipExportImportUtils") {
|
||||||
"Extracted image is empty: $originalFilename"
|
"Extracted image is empty: $originalFilename"
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean up temp file
|
// Clean up temp file
|
||||||
tempFile.delete()
|
tempFile.delete()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e(
|
AppLogger.e("ZipExportImportUtils", e) {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Failed to process image $originalFilename: ${e.message}"
|
"Failed to process image $originalFilename: ${e.message}"
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
android.util.Log.d(
|
AppLogger.d("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Skipping ZIP entry: ${entry.name}"
|
"Skipping ZIP entry: ${entry.name}"
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,10 +290,9 @@ object ZipExportImportUtils {
|
|||||||
throw IOException("Invalid ZIP file: data.json is empty")
|
throw IOException("Invalid ZIP file: data.json is empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
android.util.Log.i(
|
AppLogger.i("ZipExportImportUtils") {
|
||||||
"ZipExportImportUtils",
|
|
||||||
"Import extraction completed: ${importedImagePaths.size} images processed"
|
"Import extraction completed: ${importedImagePaths.size} images processed"
|
||||||
)
|
}
|
||||||
|
|
||||||
return ImportResult(jsonContent, importedImagePaths)
|
return ImportResult(jsonContent, importedImagePaths)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -313,7 +306,7 @@ object ZipExportImportUtils {
|
|||||||
*/
|
*/
|
||||||
fun updateProblemImagePaths(
|
fun updateProblemImagePaths(
|
||||||
problems: List<BackupProblem>,
|
problems: List<BackupProblem>,
|
||||||
imagePathMapping: Map<String, String>
|
imagePathMapping: Map<String, String>,
|
||||||
): List<BackupProblem> {
|
): List<BackupProblem> {
|
||||||
return problems.map { problem ->
|
return problems.map { problem ->
|
||||||
val updatedImagePaths =
|
val updatedImagePaths =
|
||||||
|
|||||||
@@ -11,12 +11,12 @@ import com.atridad.ascently.MainActivity
|
|||||||
import com.atridad.ascently.R
|
import com.atridad.ascently.R
|
||||||
import com.atridad.ascently.data.database.AscentlyDatabase
|
import com.atridad.ascently.data.database.AscentlyDatabase
|
||||||
import com.atridad.ascently.data.repository.ClimbRepository
|
import com.atridad.ascently.data.repository.ClimbRepository
|
||||||
import java.time.LocalDate
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import java.time.LocalDate
|
||||||
|
|
||||||
class ClimbStatsWidgetProvider : AppWidgetProvider() {
|
class ClimbStatsWidgetProvider : AppWidgetProvider() {
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ class ClimbStatsWidgetProvider : AppWidgetProvider() {
|
|||||||
override fun onUpdate(
|
override fun onUpdate(
|
||||||
context: Context,
|
context: Context,
|
||||||
appWidgetManager: AppWidgetManager,
|
appWidgetManager: AppWidgetManager,
|
||||||
appWidgetIds: IntArray
|
appWidgetIds: IntArray,
|
||||||
) {
|
) {
|
||||||
for (appWidgetId in appWidgetIds) {
|
for (appWidgetId in appWidgetIds) {
|
||||||
updateAppWidget(context, appWidgetManager, appWidgetId)
|
updateAppWidget(context, appWidgetManager, appWidgetId)
|
||||||
@@ -42,7 +42,7 @@ class ClimbStatsWidgetProvider : AppWidgetProvider() {
|
|||||||
private fun updateAppWidget(
|
private fun updateAppWidget(
|
||||||
context: Context,
|
context: Context,
|
||||||
appWidgetManager: AppWidgetManager,
|
appWidgetManager: AppWidgetManager,
|
||||||
appWidgetId: Int
|
appWidgetId: Int,
|
||||||
) {
|
) {
|
||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
try {
|
try {
|
||||||
@@ -96,7 +96,7 @@ class ClimbStatsWidgetProvider : AppWidgetProvider() {
|
|||||||
0,
|
0,
|
||||||
intent,
|
intent,
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or
|
PendingIntent.FLAG_UPDATE_CURRENT or
|
||||||
PendingIntent.FLAG_IMMUTABLE
|
PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
views.setOnClickPendingIntent(R.id.widget_container, pendingIntent)
|
views.setOnClickPendingIntent(R.id.widget_container, pendingIntent)
|
||||||
|
|
||||||
@@ -115,7 +115,7 @@ class ClimbStatsWidgetProvider : AppWidgetProvider() {
|
|||||||
0,
|
0,
|
||||||
intent,
|
intent,
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or
|
PendingIntent.FLAG_UPDATE_CURRENT or
|
||||||
PendingIntent.FLAG_IMMUTABLE
|
PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
views.setOnClickPendingIntent(R.id.widget_container, pendingIntent)
|
views.setOnClickPendingIntent(R.id.widget_container, pendingIntent)
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,6 @@
|
|||||||
-->
|
-->
|
||||||
<data-extraction-rules>
|
<data-extraction-rules>
|
||||||
<cloud-backup>
|
<cloud-backup>
|
||||||
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
|
||||||
<include .../>
|
|
||||||
<exclude .../>
|
|
||||||
-->
|
|
||||||
</cloud-backup>
|
</cloud-backup>
|
||||||
<!--
|
<!--
|
||||||
<device-transfer>
|
<device-transfer>
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ package com.atridad.ascently
|
|||||||
|
|
||||||
import com.atridad.ascently.data.format.*
|
import com.atridad.ascently.data.format.*
|
||||||
import com.atridad.ascently.data.model.*
|
import com.atridad.ascently.data.model.*
|
||||||
import java.time.LocalDateTime
|
|
||||||
import java.time.format.DateTimeFormatter
|
|
||||||
import org.junit.Assert.*
|
import org.junit.Assert.*
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
|
||||||
class BusinessLogicTests {
|
class BusinessLogicTests {
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ class BusinessLogicTests {
|
|||||||
session.copy(
|
session.copy(
|
||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
endTime = getCurrentTimestamp(),
|
endTime = getCurrentTimestamp(),
|
||||||
duration = 7200L
|
duration = 7200L,
|
||||||
)
|
)
|
||||||
assertEquals(SessionStatus.COMPLETED, completedSession.status)
|
assertEquals(SessionStatus.COMPLETED, completedSession.status)
|
||||||
assertNotNull(completedSession.endTime)
|
assertNotNull(completedSession.endTime)
|
||||||
@@ -42,7 +42,7 @@ class BusinessLogicTests {
|
|||||||
sessionId = session.id,
|
sessionId = session.id,
|
||||||
problemId = problem.id,
|
problemId = problem.id,
|
||||||
result = AttemptResult.SUCCESS,
|
result = AttemptResult.SUCCESS,
|
||||||
notes = "Clean send!"
|
notes = "Clean send!",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals(session.id, attempt.sessionId)
|
assertEquals(session.id, attempt.sessionId)
|
||||||
@@ -80,7 +80,7 @@ class BusinessLogicTests {
|
|||||||
Attempt.create(session.id, problem1.id, AttemptResult.SUCCESS),
|
Attempt.create(session.id, problem1.id, AttemptResult.SUCCESS),
|
||||||
Attempt.create(session.id, problem1.id, AttemptResult.FALL),
|
Attempt.create(session.id, problem1.id, AttemptResult.FALL),
|
||||||
Attempt.create(session.id, problem2.id, AttemptResult.FLASH),
|
Attempt.create(session.id, problem2.id, AttemptResult.FLASH),
|
||||||
Attempt.create(session.id, problem2.id, AttemptResult.SUCCESS)
|
Attempt.create(session.id, problem2.id, AttemptResult.SUCCESS),
|
||||||
)
|
)
|
||||||
|
|
||||||
val sessionStats = calculateSessionStatistics(session, attempts)
|
val sessionStats = calculateSessionStatistics(session, attempts)
|
||||||
@@ -101,7 +101,7 @@ class BusinessLogicTests {
|
|||||||
createTestProblemWithGrade(gym.id, "V3"),
|
createTestProblemWithGrade(gym.id, "V3"),
|
||||||
createTestProblemWithGrade(gym.id, "V4"),
|
createTestProblemWithGrade(gym.id, "V4"),
|
||||||
createTestProblemWithGrade(gym.id, "V5"),
|
createTestProblemWithGrade(gym.id, "V5"),
|
||||||
createTestProblemWithGrade(gym.id, "V6")
|
createTestProblemWithGrade(gym.id, "V6"),
|
||||||
)
|
)
|
||||||
|
|
||||||
val attempts =
|
val attempts =
|
||||||
@@ -132,7 +132,7 @@ class BusinessLogicTests {
|
|||||||
gyms = listOf(gym),
|
gyms = listOf(gym),
|
||||||
problems = problems,
|
problems = problems,
|
||||||
sessions = listOf(session),
|
sessions = listOf(session),
|
||||||
attempts = attempts
|
attempts = attempts,
|
||||||
)
|
)
|
||||||
|
|
||||||
validateBackupIntegrity(backup)
|
validateBackupIntegrity(backup)
|
||||||
@@ -155,7 +155,7 @@ class BusinessLogicTests {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = getCurrentTimestamp(),
|
createdAt = getCurrentTimestamp(),
|
||||||
updatedAt = getCurrentTimestamp()
|
updatedAt = getCurrentTimestamp(),
|
||||||
)
|
)
|
||||||
|
|
||||||
val ropeGym =
|
val ropeGym =
|
||||||
@@ -168,7 +168,7 @@ class BusinessLogicTests {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = getCurrentTimestamp(),
|
createdAt = getCurrentTimestamp(),
|
||||||
updatedAt = getCurrentTimestamp()
|
updatedAt = getCurrentTimestamp(),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Boulder gym should support boulder problems with V-Scale
|
// Boulder gym should support boulder problems with V-Scale
|
||||||
@@ -202,20 +202,20 @@ class BusinessLogicTests {
|
|||||||
session.id,
|
session.id,
|
||||||
problem.id,
|
problem.id,
|
||||||
"2024-01-01T10:00:00Z",
|
"2024-01-01T10:00:00Z",
|
||||||
AttemptResult.FALL
|
AttemptResult.FALL,
|
||||||
),
|
),
|
||||||
createAttemptWithTimestamp(
|
createAttemptWithTimestamp(
|
||||||
session.id,
|
session.id,
|
||||||
problem.id,
|
problem.id,
|
||||||
"2024-01-01T10:05:00Z",
|
"2024-01-01T10:05:00Z",
|
||||||
AttemptResult.FALL
|
AttemptResult.FALL,
|
||||||
),
|
),
|
||||||
createAttemptWithTimestamp(
|
createAttemptWithTimestamp(
|
||||||
session.id,
|
session.id,
|
||||||
problem.id,
|
problem.id,
|
||||||
"2024-01-01T10:10:00Z",
|
"2024-01-01T10:10:00Z",
|
||||||
AttemptResult.SUCCESS
|
AttemptResult.SUCCESS,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val sequence = AttemptSequence(attempts)
|
val sequence = AttemptSequence(attempts)
|
||||||
@@ -235,27 +235,27 @@ class BusinessLogicTests {
|
|||||||
Pair(ClimbType.BOULDER, DifficultySystem.FONT),
|
Pair(ClimbType.BOULDER, DifficultySystem.FONT),
|
||||||
Pair(ClimbType.ROPE, DifficultySystem.YDS),
|
Pair(ClimbType.ROPE, DifficultySystem.YDS),
|
||||||
Pair(ClimbType.BOULDER, DifficultySystem.CUSTOM),
|
Pair(ClimbType.BOULDER, DifficultySystem.CUSTOM),
|
||||||
Pair(ClimbType.ROPE, DifficultySystem.CUSTOM)
|
Pair(ClimbType.ROPE, DifficultySystem.CUSTOM),
|
||||||
)
|
)
|
||||||
|
|
||||||
val invalidCombinations =
|
val invalidCombinations =
|
||||||
listOf(
|
listOf(
|
||||||
Pair(ClimbType.BOULDER, DifficultySystem.YDS),
|
Pair(ClimbType.BOULDER, DifficultySystem.YDS),
|
||||||
Pair(ClimbType.ROPE, DifficultySystem.V_SCALE),
|
Pair(ClimbType.ROPE, DifficultySystem.V_SCALE),
|
||||||
Pair(ClimbType.ROPE, DifficultySystem.FONT)
|
Pair(ClimbType.ROPE, DifficultySystem.FONT),
|
||||||
)
|
)
|
||||||
|
|
||||||
validCombinations.forEach { (climbType, difficultySystem) ->
|
validCombinations.forEach { (climbType, difficultySystem) ->
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"$climbType should be compatible with $difficultySystem",
|
"$climbType should be compatible with $difficultySystem",
|
||||||
isValidGradeCombination(climbType, difficultySystem)
|
isValidGradeCombination(climbType, difficultySystem),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
invalidCombinations.forEach { (climbType, difficultySystem) ->
|
invalidCombinations.forEach { (climbType, difficultySystem) ->
|
||||||
assertFalse(
|
assertFalse(
|
||||||
"$climbType should not be compatible with $difficultySystem",
|
"$climbType should not be compatible with $difficultySystem",
|
||||||
isValidGradeCombination(climbType, difficultySystem)
|
isValidGradeCombination(climbType, difficultySystem),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -279,7 +279,7 @@ class BusinessLogicTests {
|
|||||||
listOf(
|
listOf(
|
||||||
"/storage/images/problem1.jpg",
|
"/storage/images/problem1.jpg",
|
||||||
"/data/cache/problem2.png",
|
"/data/cache/problem2.png",
|
||||||
"relative/path/problem3.jpeg"
|
"relative/path/problem3.jpeg",
|
||||||
)
|
)
|
||||||
|
|
||||||
val relativePaths = convertToRelativePaths(originalPaths)
|
val relativePaths = convertToRelativePaths(originalPaths)
|
||||||
@@ -303,13 +303,13 @@ class BusinessLogicTests {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = "Test gym for unit testing",
|
notes = "Test gym for unit testing",
|
||||||
createdAt = getCurrentTimestamp(),
|
createdAt = getCurrentTimestamp(),
|
||||||
updatedAt = getCurrentTimestamp()
|
updatedAt = getCurrentTimestamp(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun createTestProblem(
|
private fun createTestProblem(
|
||||||
gymId: String,
|
gymId: String,
|
||||||
climbType: ClimbType = ClimbType.BOULDER
|
climbType: ClimbType = ClimbType.BOULDER,
|
||||||
): Problem {
|
): Problem {
|
||||||
val difficulty =
|
val difficulty =
|
||||||
when (climbType) {
|
when (climbType) {
|
||||||
@@ -331,7 +331,7 @@ class BusinessLogicTests {
|
|||||||
dateSet = "2024-01-01",
|
dateSet = "2024-01-01",
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = getCurrentTimestamp(),
|
createdAt = getCurrentTimestamp(),
|
||||||
updatedAt = getCurrentTimestamp()
|
updatedAt = getCurrentTimestamp(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,7 +350,7 @@ class BusinessLogicTests {
|
|||||||
dateSet = null,
|
dateSet = null,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = getCurrentTimestamp(),
|
createdAt = getCurrentTimestamp(),
|
||||||
updatedAt = getCurrentTimestamp()
|
updatedAt = getCurrentTimestamp(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,13 +358,13 @@ class BusinessLogicTests {
|
|||||||
sessionId: String,
|
sessionId: String,
|
||||||
problemId: String,
|
problemId: String,
|
||||||
timestamp: String,
|
timestamp: String,
|
||||||
result: AttemptResult
|
result: AttemptResult,
|
||||||
): Attempt {
|
): Attempt {
|
||||||
return Attempt.create(
|
return Attempt.create(
|
||||||
sessionId = sessionId,
|
sessionId = sessionId,
|
||||||
problemId = problemId,
|
problemId = problemId,
|
||||||
result = result,
|
result = result,
|
||||||
timestamp = timestamp
|
timestamp = timestamp,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -374,7 +374,7 @@ class BusinessLogicTests {
|
|||||||
|
|
||||||
private fun calculateSessionStatistics(
|
private fun calculateSessionStatistics(
|
||||||
session: ClimbSession,
|
session: ClimbSession,
|
||||||
attempts: List<Attempt>
|
attempts: List<Attempt>,
|
||||||
): SessionStatistics {
|
): SessionStatistics {
|
||||||
val successful =
|
val successful =
|
||||||
attempts.count {
|
attempts.count {
|
||||||
@@ -387,13 +387,13 @@ class BusinessLogicTests {
|
|||||||
totalAttempts = attempts.size,
|
totalAttempts = attempts.size,
|
||||||
successfulAttempts = successful,
|
successfulAttempts = successful,
|
||||||
uniqueProblems = uniqueProblems,
|
uniqueProblems = uniqueProblems,
|
||||||
successRate = successRate
|
successRate = successRate,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun calculateDifficultyProgression(
|
private fun calculateDifficultyProgression(
|
||||||
attempts: List<Attempt>,
|
attempts: List<Attempt>,
|
||||||
problems: List<Problem>
|
problems: List<Problem>,
|
||||||
): DifficultyProgression {
|
): DifficultyProgression {
|
||||||
val problemMap = problems.associateBy { it.id }
|
val problemMap = problems.associateBy { it.id }
|
||||||
val grades =
|
val grades =
|
||||||
@@ -423,7 +423,7 @@ class BusinessLogicTests {
|
|||||||
gyms: List<Gym>,
|
gyms: List<Gym>,
|
||||||
problems: List<Problem>,
|
problems: List<Problem>,
|
||||||
sessions: List<ClimbSession>,
|
sessions: List<ClimbSession>,
|
||||||
attempts: List<Attempt>
|
attempts: List<Attempt>,
|
||||||
): ClimbDataBackup {
|
): ClimbDataBackup {
|
||||||
return ClimbDataBackup(
|
return ClimbDataBackup(
|
||||||
exportedAt = getCurrentTimestamp(),
|
exportedAt = getCurrentTimestamp(),
|
||||||
@@ -440,7 +440,7 @@ class BusinessLogicTests {
|
|||||||
customDifficultyGrades = gym.customDifficultyGrades,
|
customDifficultyGrades = gym.customDifficultyGrades,
|
||||||
notes = gym.notes,
|
notes = gym.notes,
|
||||||
createdAt = gym.createdAt,
|
createdAt = gym.createdAt,
|
||||||
updatedAt = gym.updatedAt
|
updatedAt = gym.updatedAt,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
problems =
|
problems =
|
||||||
@@ -459,7 +459,7 @@ class BusinessLogicTests {
|
|||||||
dateSet = problem.dateSet,
|
dateSet = problem.dateSet,
|
||||||
notes = problem.notes,
|
notes = problem.notes,
|
||||||
createdAt = problem.createdAt,
|
createdAt = problem.createdAt,
|
||||||
updatedAt = problem.updatedAt
|
updatedAt = problem.updatedAt,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
sessions =
|
sessions =
|
||||||
@@ -474,7 +474,7 @@ class BusinessLogicTests {
|
|||||||
status = session.status,
|
status = session.status,
|
||||||
notes = session.notes,
|
notes = session.notes,
|
||||||
createdAt = session.createdAt,
|
createdAt = session.createdAt,
|
||||||
updatedAt = session.updatedAt
|
updatedAt = session.updatedAt,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
attempts =
|
attempts =
|
||||||
@@ -492,7 +492,7 @@ class BusinessLogicTests {
|
|||||||
createdAt = attempt.createdAt,
|
createdAt = attempt.createdAt,
|
||||||
updatedAt = attempt.updatedAt,
|
updatedAt = attempt.updatedAt,
|
||||||
)
|
)
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -502,7 +502,7 @@ class BusinessLogicTests {
|
|||||||
backup.problems.forEach { problem ->
|
backup.problems.forEach { problem ->
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Problem ${problem.id} references non-existent gym ${problem.gymId}",
|
"Problem ${problem.id} references non-existent gym ${problem.gymId}",
|
||||||
gymIds.contains(problem.gymId)
|
gymIds.contains(problem.gymId),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -511,7 +511,7 @@ class BusinessLogicTests {
|
|||||||
backup.attempts.forEach { attempt ->
|
backup.attempts.forEach { attempt ->
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Attempt ${attempt.id} references non-existent session ${attempt.sessionId}",
|
"Attempt ${attempt.id} references non-existent session ${attempt.sessionId}",
|
||||||
sessionIds.contains(attempt.sessionId)
|
sessionIds.contains(attempt.sessionId),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -520,7 +520,7 @@ class BusinessLogicTests {
|
|||||||
backup.attempts.forEach { attempt ->
|
backup.attempts.forEach { attempt ->
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Attempt ${attempt.id} references non-existent problem ${attempt.problemId}",
|
"Attempt ${attempt.id} references non-existent problem ${attempt.problemId}",
|
||||||
problemIds.contains(attempt.problemId)
|
problemIds.contains(attempt.problemId),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -528,7 +528,7 @@ class BusinessLogicTests {
|
|||||||
private fun isCompatibleClimbType(
|
private fun isCompatibleClimbType(
|
||||||
gym: Gym,
|
gym: Gym,
|
||||||
climbType: ClimbType,
|
climbType: ClimbType,
|
||||||
difficultySystem: DifficultySystem
|
difficultySystem: DifficultySystem,
|
||||||
): Boolean {
|
): Boolean {
|
||||||
return gym.supportedClimbTypes.contains(climbType) &&
|
return gym.supportedClimbTypes.contains(climbType) &&
|
||||||
gym.difficultySystems.contains(difficultySystem)
|
gym.difficultySystems.contains(difficultySystem)
|
||||||
@@ -542,7 +542,7 @@ class BusinessLogicTests {
|
|||||||
|
|
||||||
private fun isValidGradeCombination(
|
private fun isValidGradeCombination(
|
||||||
climbType: ClimbType,
|
climbType: ClimbType,
|
||||||
difficultySystem: DifficultySystem
|
difficultySystem: DifficultySystem,
|
||||||
): Boolean {
|
): Boolean {
|
||||||
return when (climbType) {
|
return when (climbType) {
|
||||||
ClimbType.BOULDER ->
|
ClimbType.BOULDER ->
|
||||||
@@ -550,7 +550,7 @@ class BusinessLogicTests {
|
|||||||
listOf(
|
listOf(
|
||||||
DifficultySystem.V_SCALE,
|
DifficultySystem.V_SCALE,
|
||||||
DifficultySystem.FONT,
|
DifficultySystem.FONT,
|
||||||
DifficultySystem.CUSTOM
|
DifficultySystem.CUSTOM,
|
||||||
)
|
)
|
||||||
ClimbType.ROPE ->
|
ClimbType.ROPE ->
|
||||||
difficultySystem in listOf(DifficultySystem.YDS, DifficultySystem.CUSTOM)
|
difficultySystem in listOf(DifficultySystem.YDS, DifficultySystem.CUSTOM)
|
||||||
@@ -571,14 +571,14 @@ class BusinessLogicTests {
|
|||||||
val totalAttempts: Int,
|
val totalAttempts: Int,
|
||||||
val successfulAttempts: Int,
|
val successfulAttempts: Int,
|
||||||
val uniqueProblems: Int,
|
val uniqueProblems: Int,
|
||||||
val successRate: Double
|
val successRate: Double,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class DifficultyProgression(
|
data class DifficultyProgression(
|
||||||
val minGrade: String,
|
val minGrade: String,
|
||||||
val maxGrade: String,
|
val maxGrade: String,
|
||||||
val averageGrade: Double,
|
val averageGrade: Double,
|
||||||
val showsProgression: Boolean
|
val showsProgression: Boolean,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class AttemptSequence(val attempts: List<Attempt>) {
|
data class AttemptSequence(val attempts: List<Attempt>) {
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ package com.atridad.ascently
|
|||||||
|
|
||||||
import com.atridad.ascently.data.format.*
|
import com.atridad.ascently.data.format.*
|
||||||
import com.atridad.ascently.data.model.*
|
import com.atridad.ascently.data.model.*
|
||||||
import java.time.Instant
|
|
||||||
import java.time.format.DateTimeFormatter
|
|
||||||
import org.junit.Assert.*
|
import org.junit.Assert.*
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
|
||||||
class DataModelTests {
|
class DataModelTests {
|
||||||
|
|
||||||
@@ -150,7 +150,7 @@ class DataModelTests {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = "Great gym for beginners",
|
notes = "Great gym for beginners",
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals("gym123", gym.id)
|
assertEquals("gym123", gym.id)
|
||||||
@@ -181,7 +181,7 @@ class DataModelTests {
|
|||||||
dateSet = "2024-01-01",
|
dateSet = "2024-01-01",
|
||||||
notes = "Watch the start holds",
|
notes = "Watch the start holds",
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals("problem123", problem.id)
|
assertEquals("problem123", problem.id)
|
||||||
@@ -190,7 +190,7 @@ class DataModelTests {
|
|||||||
assertEquals(ClimbType.BOULDER, problem.climbType)
|
assertEquals(ClimbType.BOULDER, problem.climbType)
|
||||||
assertEquals("V5", problem.difficulty.grade)
|
assertEquals("V5", problem.difficulty.grade)
|
||||||
assertTrue(problem.isActive)
|
assertTrue(problem.isActive)
|
||||||
assertEquals(2, problem.tags.size)
|
assertEquals(2, problem.tags?.size ?: 0)
|
||||||
assertEquals(2, problem.imagePaths?.size ?: 0)
|
assertEquals(2, problem.imagePaths?.size ?: 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,7 +207,7 @@ class DataModelTests {
|
|||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
notes = "Great session today",
|
notes = "Great session today",
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T12:00:00Z"
|
updatedAt = "2024-01-01T12:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals("session123", session.id)
|
assertEquals("session123", session.id)
|
||||||
@@ -231,7 +231,7 @@ class DataModelTests {
|
|||||||
restTime = 120,
|
restTime = 120,
|
||||||
timestamp = "2024-01-01T10:30:00Z",
|
timestamp = "2024-01-01T10:30:00Z",
|
||||||
createdAt = "2024-01-01T10:30:00Z",
|
createdAt = "2024-01-01T10:30:00Z",
|
||||||
updatedAt = "2024-01-01T10:30:00Z"
|
updatedAt = "2024-01-01T10:30:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals("attempt123", attempt.id)
|
assertEquals("attempt123", attempt.id)
|
||||||
@@ -253,7 +253,7 @@ class DataModelTests {
|
|||||||
gyms = emptyList(),
|
gyms = emptyList(),
|
||||||
problems = emptyList(),
|
problems = emptyList(),
|
||||||
sessions = emptyList(),
|
sessions = emptyList(),
|
||||||
attempts = emptyList()
|
attempts = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals("2.0", backup.version)
|
assertEquals("2.0", backup.version)
|
||||||
@@ -290,7 +290,7 @@ class DataModelTests {
|
|||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T12:00:00Z"
|
updatedAt = "2024-01-01T12:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals(7200L, session.duration)
|
assertEquals(7200L, session.duration)
|
||||||
@@ -310,12 +310,12 @@ class DataModelTests {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertTrue(gym.supportedClimbTypes.isEmpty())
|
assertTrue(gym.supportedClimbTypes?.isEmpty() ?: true)
|
||||||
assertTrue(gym.difficultySystems.isEmpty())
|
assertTrue(gym.difficultySystems?.isEmpty() ?: true)
|
||||||
assertTrue(gym.customDifficultyGrades.isEmpty())
|
assertTrue(gym.customDifficultyGrades?.isEmpty() ?: true)
|
||||||
assertNull(gym.location)
|
assertNull(gym.location)
|
||||||
assertNull(gym.notes)
|
assertNull(gym.notes)
|
||||||
}
|
}
|
||||||
@@ -337,7 +337,7 @@ class DataModelTests {
|
|||||||
dateSet = null,
|
dateSet = null,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertNull(problem.name)
|
assertNull(problem.name)
|
||||||
@@ -345,7 +345,7 @@ class DataModelTests {
|
|||||||
assertNull(problem.location)
|
assertNull(problem.location)
|
||||||
assertNull(problem.dateSet)
|
assertNull(problem.dateSet)
|
||||||
assertNull(problem.notes)
|
assertNull(problem.notes)
|
||||||
assertTrue(problem.tags.isEmpty())
|
assertTrue(problem.tags?.isEmpty() ?: true)
|
||||||
assertNull(problem.imagePaths)
|
assertNull(problem.imagePaths)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,7 +411,7 @@ class DataModelTests {
|
|||||||
dateSet = null,
|
dateSet = null,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals(ClimbType.BOULDER, boulderProblem.climbType)
|
assertEquals(ClimbType.BOULDER, boulderProblem.climbType)
|
||||||
@@ -433,7 +433,7 @@ class DataModelTests {
|
|||||||
dateSet = null,
|
dateSet = null,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals(ClimbType.ROPE, ropeProblem.climbType)
|
assertEquals(ClimbType.ROPE, ropeProblem.climbType)
|
||||||
@@ -477,7 +477,7 @@ class DataModelTests {
|
|||||||
AttemptResult.SUCCESS,
|
AttemptResult.SUCCESS,
|
||||||
AttemptResult.FALL,
|
AttemptResult.FALL,
|
||||||
AttemptResult.NO_PROGRESS,
|
AttemptResult.NO_PROGRESS,
|
||||||
AttemptResult.FLASH
|
AttemptResult.FLASH,
|
||||||
)
|
)
|
||||||
|
|
||||||
assertEquals(4, validResults.size)
|
assertEquals(4, validResults.size)
|
||||||
@@ -510,7 +510,7 @@ class DataModelTests {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
val problem =
|
val problem =
|
||||||
@@ -528,7 +528,7 @@ class DataModelTests {
|
|||||||
dateSet = null,
|
dateSet = null,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T10:00:00Z"
|
updatedAt = "2024-01-01T10:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
val session =
|
val session =
|
||||||
@@ -542,7 +542,7 @@ class DataModelTests {
|
|||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00Z",
|
createdAt = "2024-01-01T10:00:00Z",
|
||||||
updatedAt = "2024-01-01T11:00:00Z"
|
updatedAt = "2024-01-01T11:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
val attempt =
|
val attempt =
|
||||||
@@ -557,7 +557,7 @@ class DataModelTests {
|
|||||||
restTime = null,
|
restTime = null,
|
||||||
timestamp = "2024-01-01T10:30:00Z",
|
timestamp = "2024-01-01T10:30:00Z",
|
||||||
createdAt = "2024-01-01T10:30:00Z",
|
createdAt = "2024-01-01T10:30:00Z",
|
||||||
updatedAt = "2024-01-01T10:30:00Z"
|
updatedAt = "2024-01-01T10:30:00Z",
|
||||||
)
|
)
|
||||||
|
|
||||||
// Verify referential integrity
|
// Verify referential integrity
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ class SyncMergeLogicTest {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00",
|
createdAt = "2024-01-01T10:00:00",
|
||||||
updatedAt = "2024-01-01T10:00:00"
|
updatedAt = "2024-01-01T10:00:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val localProblems =
|
val localProblems =
|
||||||
@@ -41,8 +41,8 @@ class SyncMergeLogicTest {
|
|||||||
dateSet = null,
|
dateSet = null,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00",
|
createdAt = "2024-01-01T10:00:00",
|
||||||
updatedAt = "2024-01-01T10:00:00"
|
updatedAt = "2024-01-01T10:00:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val localSessions =
|
val localSessions =
|
||||||
@@ -57,8 +57,8 @@ class SyncMergeLogicTest {
|
|||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00",
|
createdAt = "2024-01-01T10:00:00",
|
||||||
updatedAt = "2024-01-01T10:00:00"
|
updatedAt = "2024-01-01T10:00:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val localAttempts =
|
val localAttempts =
|
||||||
@@ -74,8 +74,8 @@ class SyncMergeLogicTest {
|
|||||||
restTime = null,
|
restTime = null,
|
||||||
timestamp = "2024-01-01T10:30:00",
|
timestamp = "2024-01-01T10:30:00",
|
||||||
createdAt = "2024-01-01T10:30:00",
|
createdAt = "2024-01-01T10:30:00",
|
||||||
updatedAt = "2024-01-01T10:30:00"
|
updatedAt = "2024-01-01T10:30:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val localBackup =
|
val localBackup =
|
||||||
@@ -86,7 +86,7 @@ class SyncMergeLogicTest {
|
|||||||
gyms = localGyms,
|
gyms = localGyms,
|
||||||
problems = localProblems,
|
problems = localProblems,
|
||||||
sessions = localSessions,
|
sessions = localSessions,
|
||||||
attempts = localAttempts
|
attempts = localAttempts,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Create server data with some overlapping and some unique data
|
// Create server data with some overlapping and some unique data
|
||||||
@@ -103,7 +103,7 @@ class SyncMergeLogicTest {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = "Updated notes",
|
notes = "Updated notes",
|
||||||
createdAt = "2024-01-01T10:00:00",
|
createdAt = "2024-01-01T10:00:00",
|
||||||
updatedAt = "2024-01-01T12:00:00" // Newer update
|
updatedAt = "2024-01-01T12:00:00", // Newer update
|
||||||
),
|
),
|
||||||
// Unique server gym
|
// Unique server gym
|
||||||
BackupGym(
|
BackupGym(
|
||||||
@@ -115,8 +115,8 @@ class SyncMergeLogicTest {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T11:00:00",
|
createdAt = "2024-01-01T11:00:00",
|
||||||
updatedAt = "2024-01-01T11:00:00"
|
updatedAt = "2024-01-01T11:00:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val serverProblems =
|
val serverProblems =
|
||||||
@@ -136,7 +136,7 @@ class SyncMergeLogicTest {
|
|||||||
dateSet = "2024-01-01",
|
dateSet = "2024-01-01",
|
||||||
notes = "Updated notes",
|
notes = "Updated notes",
|
||||||
createdAt = "2024-01-01T10:00:00",
|
createdAt = "2024-01-01T10:00:00",
|
||||||
updatedAt = "2024-01-01T11:00:00" // Newer update
|
updatedAt = "2024-01-01T11:00:00", // Newer update
|
||||||
),
|
),
|
||||||
// Unique server problem
|
// Unique server problem
|
||||||
BackupProblem(
|
BackupProblem(
|
||||||
@@ -153,8 +153,8 @@ class SyncMergeLogicTest {
|
|||||||
dateSet = null,
|
dateSet = null,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T11:00:00",
|
createdAt = "2024-01-01T11:00:00",
|
||||||
updatedAt = "2024-01-01T11:00:00"
|
updatedAt = "2024-01-01T11:00:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val serverSessions =
|
val serverSessions =
|
||||||
@@ -170,8 +170,8 @@ class SyncMergeLogicTest {
|
|||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
notes = "Server session",
|
notes = "Server session",
|
||||||
createdAt = "2024-01-02T14:00:00",
|
createdAt = "2024-01-02T14:00:00",
|
||||||
updatedAt = "2024-01-02T14:00:00"
|
updatedAt = "2024-01-02T14:00:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val serverAttempts =
|
val serverAttempts =
|
||||||
@@ -188,8 +188,8 @@ class SyncMergeLogicTest {
|
|||||||
restTime = 60,
|
restTime = 60,
|
||||||
timestamp = "2024-01-02T14:30:00",
|
timestamp = "2024-01-02T14:30:00",
|
||||||
createdAt = "2024-01-02T14:30:00",
|
createdAt = "2024-01-02T14:30:00",
|
||||||
updatedAt = "2024-01-02T14:30:00"
|
updatedAt = "2024-01-02T14:30:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val serverBackup =
|
val serverBackup =
|
||||||
@@ -200,7 +200,7 @@ class SyncMergeLogicTest {
|
|||||||
gyms = serverGyms,
|
gyms = serverGyms,
|
||||||
problems = serverProblems,
|
problems = serverProblems,
|
||||||
sessions = serverSessions,
|
sessions = serverSessions,
|
||||||
attempts = serverAttempts
|
attempts = serverAttempts,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Simulate merge logic
|
// Simulate merge logic
|
||||||
@@ -232,11 +232,11 @@ class SyncMergeLogicTest {
|
|||||||
// Images should be merged (both local and server images preserved)
|
// Images should be merged (both local and server images preserved)
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Should contain local image",
|
"Should contain local image",
|
||||||
mergedProblem1.imagePaths!!.contains("local_image.jpg")
|
mergedProblem1.imagePaths!!.contains("local_image.jpg"),
|
||||||
)
|
)
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Should contain server image",
|
"Should contain server image",
|
||||||
mergedProblem1.imagePaths!!.contains("server_image.jpg")
|
mergedProblem1.imagePaths!!.contains("server_image.jpg"),
|
||||||
)
|
)
|
||||||
assertEquals("Should have 2 images total", 2, mergedProblem1.imagePaths!!.size)
|
assertEquals("Should have 2 images total", 2, mergedProblem1.imagePaths!!.size)
|
||||||
|
|
||||||
@@ -247,21 +247,21 @@ class SyncMergeLogicTest {
|
|||||||
// Verify all sessions are preserved
|
// Verify all sessions are preserved
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Should contain local session",
|
"Should contain local session",
|
||||||
mergedBackup.sessions.any { it.id == "session1" }
|
mergedBackup.sessions.any { it.id == "session1" },
|
||||||
)
|
)
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Should contain server session",
|
"Should contain server session",
|
||||||
mergedBackup.sessions.any { it.id == "session2" }
|
mergedBackup.sessions.any { it.id == "session2" },
|
||||||
)
|
)
|
||||||
|
|
||||||
// Verify all attempts are preserved
|
// Verify all attempts are preserved
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Should contain local attempt",
|
"Should contain local attempt",
|
||||||
mergedBackup.attempts.any { it.id == "attempt1" }
|
mergedBackup.attempts.any { it.id == "attempt1" },
|
||||||
)
|
)
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"Should contain server attempt",
|
"Should contain server attempt",
|
||||||
mergedBackup.attempts.any { it.id == "attempt2" }
|
mergedBackup.attempts.any { it.id == "attempt2" },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,15 +269,15 @@ class SyncMergeLogicTest {
|
|||||||
fun `test date comparison logic`() {
|
fun `test date comparison logic`() {
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"ISO instant should be newer",
|
"ISO instant should be newer",
|
||||||
isNewerThan("2024-01-01T12:00:00Z", "2024-01-01T10:00:00Z")
|
isNewerThan("2024-01-01T12:00:00Z", "2024-01-01T10:00:00Z"),
|
||||||
)
|
)
|
||||||
assertFalse(
|
assertFalse(
|
||||||
"ISO instant should be older",
|
"ISO instant should be older",
|
||||||
isNewerThan("2024-01-01T10:00:00Z", "2024-01-01T12:00:00Z")
|
isNewerThan("2024-01-01T10:00:00Z", "2024-01-01T12:00:00Z"),
|
||||||
)
|
)
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"String comparison should work as fallback",
|
"String comparison should work as fallback",
|
||||||
isNewerThan("2024-01-02T10:00:00", "2024-01-01T10:00:00")
|
isNewerThan("2024-01-02T10:00:00", "2024-01-01T10:00:00"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,7 +291,7 @@ class SyncMergeLogicTest {
|
|||||||
gyms = emptyList(),
|
gyms = emptyList(),
|
||||||
problems = emptyList(),
|
problems = emptyList(),
|
||||||
sessions = emptyList(),
|
sessions = emptyList(),
|
||||||
attempts = emptyList()
|
attempts = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
val dataBackup =
|
val dataBackup =
|
||||||
@@ -311,12 +311,12 @@ class SyncMergeLogicTest {
|
|||||||
customDifficultyGrades = emptyList(),
|
customDifficultyGrades = emptyList(),
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00",
|
createdAt = "2024-01-01T10:00:00",
|
||||||
updatedAt = "2024-01-01T10:00:00"
|
updatedAt = "2024-01-01T10:00:00",
|
||||||
)
|
),
|
||||||
),
|
),
|
||||||
problems = emptyList(),
|
problems = emptyList(),
|
||||||
sessions = emptyList(),
|
sessions = emptyList(),
|
||||||
attempts = emptyList()
|
attempts = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Test merging empty with data
|
// Test merging empty with data
|
||||||
@@ -335,7 +335,7 @@ class SyncMergeLogicTest {
|
|||||||
// Helper methods that simulate the merge logic from SyncService
|
// Helper methods that simulate the merge logic from SyncService
|
||||||
private fun performIntelligentMerge(
|
private fun performIntelligentMerge(
|
||||||
local: ClimbDataBackup,
|
local: ClimbDataBackup,
|
||||||
server: ClimbDataBackup
|
server: ClimbDataBackup,
|
||||||
): ClimbDataBackup {
|
): ClimbDataBackup {
|
||||||
val mergedGyms = mergeGyms(local.gyms, server.gyms)
|
val mergedGyms = mergeGyms(local.gyms, server.gyms)
|
||||||
val mergedProblems = mergeProblems(local.problems, server.problems)
|
val mergedProblems = mergeProblems(local.problems, server.problems)
|
||||||
@@ -349,7 +349,7 @@ class SyncMergeLogicTest {
|
|||||||
gyms = mergedGyms,
|
gyms = mergedGyms,
|
||||||
problems = mergedProblems,
|
problems = mergedProblems,
|
||||||
sessions = mergedSessions,
|
sessions = mergedSessions,
|
||||||
attempts = mergedAttempts
|
attempts = mergedAttempts,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -372,7 +372,7 @@ class SyncMergeLogicTest {
|
|||||||
|
|
||||||
private fun mergeProblems(
|
private fun mergeProblems(
|
||||||
local: List<BackupProblem>,
|
local: List<BackupProblem>,
|
||||||
server: List<BackupProblem>
|
server: List<BackupProblem>,
|
||||||
): List<BackupProblem> {
|
): List<BackupProblem> {
|
||||||
val merged = mutableMapOf<String, BackupProblem>()
|
val merged = mutableMapOf<String, BackupProblem>()
|
||||||
|
|
||||||
@@ -399,7 +399,7 @@ class SyncMergeLogicTest {
|
|||||||
|
|
||||||
private fun mergeSessions(
|
private fun mergeSessions(
|
||||||
local: List<BackupClimbSession>,
|
local: List<BackupClimbSession>,
|
||||||
server: List<BackupClimbSession>
|
server: List<BackupClimbSession>,
|
||||||
): List<BackupClimbSession> {
|
): List<BackupClimbSession> {
|
||||||
val merged = mutableMapOf<String, BackupClimbSession>()
|
val merged = mutableMapOf<String, BackupClimbSession>()
|
||||||
|
|
||||||
@@ -420,7 +420,7 @@ class SyncMergeLogicTest {
|
|||||||
|
|
||||||
private fun mergeAttempts(
|
private fun mergeAttempts(
|
||||||
local: List<BackupAttempt>,
|
local: List<BackupAttempt>,
|
||||||
server: List<BackupAttempt>
|
server: List<BackupAttempt>,
|
||||||
): List<BackupAttempt> {
|
): List<BackupAttempt> {
|
||||||
val merged = mutableMapOf<String, BackupAttempt>()
|
val merged = mutableMapOf<String, BackupAttempt>()
|
||||||
|
|
||||||
@@ -433,7 +433,7 @@ class SyncMergeLogicTest {
|
|||||||
if (localAttempt == null ||
|
if (localAttempt == null ||
|
||||||
isNewerThan(
|
isNewerThan(
|
||||||
serverAttempt.updatedAt ?: serverAttempt.createdAt,
|
serverAttempt.updatedAt ?: serverAttempt.createdAt,
|
||||||
localAttempt.updatedAt ?: localAttempt.createdAt
|
localAttempt.updatedAt ?: localAttempt.createdAt,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
merged[serverAttempt.id] = serverAttempt
|
merged[serverAttempt.id] = serverAttempt
|
||||||
@@ -469,7 +469,7 @@ class SyncMergeLogicTest {
|
|||||||
status = SessionStatus.ACTIVE,
|
status = SessionStatus.ACTIVE,
|
||||||
notes = null,
|
notes = null,
|
||||||
createdAt = "2024-01-01T10:00:00",
|
createdAt = "2024-01-01T10:00:00",
|
||||||
updatedAt = "2024-01-01T10:00:00"
|
updatedAt = "2024-01-01T10:00:00",
|
||||||
),
|
),
|
||||||
BackupClimbSession(
|
BackupClimbSession(
|
||||||
id = "completed_session_1",
|
id = "completed_session_1",
|
||||||
@@ -481,8 +481,8 @@ class SyncMergeLogicTest {
|
|||||||
status = SessionStatus.COMPLETED,
|
status = SessionStatus.COMPLETED,
|
||||||
notes = "Previous session",
|
notes = "Previous session",
|
||||||
createdAt = "2023-12-31T15:00:00",
|
createdAt = "2023-12-31T15:00:00",
|
||||||
updatedAt = "2023-12-31T17:00:00"
|
updatedAt = "2023-12-31T17:00:00",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Simulate filtering that would happen in createBackupFromRepository
|
// Simulate filtering that would happen in createBackupFromRepository
|
||||||
@@ -496,7 +496,7 @@ class SyncMergeLogicTest {
|
|||||||
"Should not contain active session in sync",
|
"Should not contain active session in sync",
|
||||||
sessionsForSync.any {
|
sessionsForSync.any {
|
||||||
it.id == "active_session_1" && it.status == SessionStatus.ACTIVE
|
it.id == "active_session_1" && it.status == SessionStatus.ACTIVE
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
// Completed session should be included
|
// Completed session should be included
|
||||||
@@ -504,7 +504,7 @@ class SyncMergeLogicTest {
|
|||||||
"Should contain completed session in sync",
|
"Should contain completed session in sync",
|
||||||
sessionsForSync.any {
|
sessionsForSync.any {
|
||||||
it.id == "completed_session_1" && it.status == SessionStatus.COMPLETED
|
it.id == "completed_session_1" && it.status == SessionStatus.COMPLETED
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
package com.atridad.ascently
|
package com.atridad.ascently
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
import java.time.LocalDateTime
|
import java.time.LocalDateTime
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
import org.junit.Assert.*
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class UtilityTests {
|
class UtilityTests {
|
||||||
|
|
||||||
@@ -80,7 +80,7 @@ class UtilityTests {
|
|||||||
AttemptData("FALL", 90),
|
AttemptData("FALL", 90),
|
||||||
AttemptData("SUCCESS", 150),
|
AttemptData("SUCCESS", 150),
|
||||||
AttemptData("FLASH", 60),
|
AttemptData("FLASH", 60),
|
||||||
AttemptData("FALL", 110)
|
AttemptData("FALL", 110),
|
||||||
)
|
)
|
||||||
|
|
||||||
val stats = calculateAttemptStatistics(attempts)
|
val stats = calculateAttemptStatistics(attempts)
|
||||||
@@ -169,7 +169,7 @@ class UtilityTests {
|
|||||||
"Crimpy Problem",
|
"Crimpy Problem",
|
||||||
"BOULDER",
|
"BOULDER",
|
||||||
"V5",
|
"V5",
|
||||||
listOf("crimpy", "overhang")
|
listOf("crimpy", "overhang"),
|
||||||
),
|
),
|
||||||
ProblemData("id2", "Easy Route", "ROPE", "5.6", listOf("beginner", "slab")),
|
ProblemData("id2", "Easy Route", "ROPE", "5.6", listOf("beginner", "slab")),
|
||||||
ProblemData(
|
ProblemData(
|
||||||
@@ -177,8 +177,8 @@ class UtilityTests {
|
|||||||
"Hard Boulder",
|
"Hard Boulder",
|
||||||
"BOULDER",
|
"BOULDER",
|
||||||
"V10",
|
"V10",
|
||||||
listOf("powerful", "roof")
|
listOf("powerful", "roof"),
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val boulderProblems = filterByClimbType(problems, "BOULDER")
|
val boulderProblems = filterByClimbType(problems, "BOULDER")
|
||||||
@@ -211,7 +211,7 @@ class UtilityTests {
|
|||||||
version = "2.0",
|
version = "2.0",
|
||||||
formatVersion = "2.0",
|
formatVersion = "2.0",
|
||||||
exportedAt = "2024-01-01T10:00:00Z",
|
exportedAt = "2024-01-01T10:00:00Z",
|
||||||
dataCount = 5
|
dataCount = 5,
|
||||||
)
|
)
|
||||||
|
|
||||||
val invalidBackup =
|
val invalidBackup =
|
||||||
@@ -219,7 +219,7 @@ class UtilityTests {
|
|||||||
version = "1.0",
|
version = "1.0",
|
||||||
formatVersion = "2.0",
|
formatVersion = "2.0",
|
||||||
exportedAt = "invalid-date",
|
exportedAt = "invalid-date",
|
||||||
dataCount = -1
|
dataCount = -1,
|
||||||
)
|
)
|
||||||
|
|
||||||
assertTrue(isValidBackup(validBackup))
|
assertTrue(isValidBackup(validBackup))
|
||||||
@@ -261,7 +261,7 @@ class UtilityTests {
|
|||||||
totalAttempts = attempts.size,
|
totalAttempts = attempts.size,
|
||||||
successfulAttempts = successful,
|
successfulAttempts = successful,
|
||||||
successRate = successRate,
|
successRate = successRate,
|
||||||
averageDuration = avgDuration
|
averageDuration = avgDuration,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,7 +302,7 @@ class UtilityTests {
|
|||||||
|
|
||||||
private fun filterByClimbType(
|
private fun filterByClimbType(
|
||||||
problems: List<ProblemData>,
|
problems: List<ProblemData>,
|
||||||
climbType: String
|
climbType: String,
|
||||||
): List<ProblemData> {
|
): List<ProblemData> {
|
||||||
return problems.filter { it.climbType == climbType }
|
return problems.filter { it.climbType == climbType }
|
||||||
}
|
}
|
||||||
@@ -314,7 +314,7 @@ class UtilityTests {
|
|||||||
private fun filterByDifficultyRange(
|
private fun filterByDifficultyRange(
|
||||||
problems: List<ProblemData>,
|
problems: List<ProblemData>,
|
||||||
minGrade: String,
|
minGrade: String,
|
||||||
maxGrade: String
|
maxGrade: String,
|
||||||
): List<ProblemData> {
|
): List<ProblemData> {
|
||||||
return problems.filter { problem ->
|
return problems.filter { problem ->
|
||||||
if (problem.climbType == "BOULDER" && problem.difficulty.startsWith("V")) {
|
if (problem.climbType == "BOULDER" && problem.difficulty.startsWith("V")) {
|
||||||
@@ -330,7 +330,7 @@ class UtilityTests {
|
|||||||
|
|
||||||
private fun mergeData(
|
private fun mergeData(
|
||||||
local: Map<String, String>,
|
local: Map<String, String>,
|
||||||
server: Map<String, String>
|
server: Map<String, String>,
|
||||||
): Map<String, String> {
|
): Map<String, String> {
|
||||||
return (local.keys + server.keys).associateWith { key -> server[key] ?: local[key]!! }
|
return (local.keys + server.keys).associateWith { key -> server[key] ?: local[key]!! }
|
||||||
}
|
}
|
||||||
@@ -350,7 +350,7 @@ class UtilityTests {
|
|||||||
val totalAttempts: Int,
|
val totalAttempts: Int,
|
||||||
val successfulAttempts: Int,
|
val successfulAttempts: Int,
|
||||||
val successRate: Double,
|
val successRate: Double,
|
||||||
val averageDuration: Double
|
val averageDuration: Double,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class ProblemData(
|
data class ProblemData(
|
||||||
@@ -358,13 +358,13 @@ class UtilityTests {
|
|||||||
val name: String,
|
val name: String,
|
||||||
val climbType: String,
|
val climbType: String,
|
||||||
val difficulty: String,
|
val difficulty: String,
|
||||||
val tags: List<String>
|
val tags: List<String>,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class BackupData(
|
data class BackupData(
|
||||||
val version: String,
|
val version: String,
|
||||||
val formatVersion: String,
|
val formatVersion: String,
|
||||||
val exportedAt: String,
|
val exportedAt: String,
|
||||||
val dataCount: Int
|
val dataCount: Int,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,4 +3,6 @@ plugins {
|
|||||||
alias(libs.plugins.android.application) apply false
|
alias(libs.plugins.android.application) apply false
|
||||||
alias(libs.plugins.kotlin.android) apply false
|
alias(libs.plugins.kotlin.android) apply false
|
||||||
alias(libs.plugins.kotlin.compose) apply false
|
alias(libs.plugins.kotlin.compose) apply false
|
||||||
|
alias(libs.plugins.detekt) apply false
|
||||||
|
alias(libs.plugins.spotless) apply false
|
||||||
}
|
}
|
||||||
584
android/detekt.yml
Normal file
584
android/detekt.yml
Normal file
@@ -0,0 +1,584 @@
|
|||||||
|
build:
|
||||||
|
maxIssues: -1
|
||||||
|
excludeCorrectable: false
|
||||||
|
|
||||||
|
config:
|
||||||
|
validation: true
|
||||||
|
warningsAsErrors: false
|
||||||
|
|
||||||
|
processors:
|
||||||
|
active: true
|
||||||
|
exclude:
|
||||||
|
- 'DetektProgressListener'
|
||||||
|
|
||||||
|
console-reports:
|
||||||
|
active: true
|
||||||
|
|
||||||
|
output-reports:
|
||||||
|
active: true
|
||||||
|
exclude:
|
||||||
|
- 'TxtOutputReport'
|
||||||
|
|
||||||
|
complexity:
|
||||||
|
active: true
|
||||||
|
ComplexCondition:
|
||||||
|
active: true
|
||||||
|
threshold: 5
|
||||||
|
CyclomaticComplexMethod:
|
||||||
|
active: true
|
||||||
|
threshold: 50
|
||||||
|
ignoreSingleWhenExpression: true
|
||||||
|
ignoreSimpleWhenEntries: true
|
||||||
|
ignoreNestingFunctions: false
|
||||||
|
nestingFunctions:
|
||||||
|
- 'also'
|
||||||
|
- 'apply'
|
||||||
|
- 'let'
|
||||||
|
- 'run'
|
||||||
|
- 'with'
|
||||||
|
LabeledExpression:
|
||||||
|
active: false
|
||||||
|
LargeClass:
|
||||||
|
active: true
|
||||||
|
threshold: 800
|
||||||
|
LongMethod:
|
||||||
|
active: true
|
||||||
|
threshold: 120
|
||||||
|
ignoreAnnotated:
|
||||||
|
- 'Composable'
|
||||||
|
- 'Test'
|
||||||
|
LongParameterList:
|
||||||
|
active: true
|
||||||
|
functionThreshold: 15
|
||||||
|
constructorThreshold: 15
|
||||||
|
ignoreDefaultParameters: true
|
||||||
|
ignoreDataClasses: true
|
||||||
|
ignoreAnnotatedParameter:
|
||||||
|
- 'Composable'
|
||||||
|
MethodOverloading:
|
||||||
|
active: false
|
||||||
|
NamedArguments:
|
||||||
|
active: false
|
||||||
|
NestedBlockDepth:
|
||||||
|
active: true
|
||||||
|
threshold: 8
|
||||||
|
NestedScopeFunctions:
|
||||||
|
active: true
|
||||||
|
threshold: 2
|
||||||
|
functions:
|
||||||
|
- 'also'
|
||||||
|
- 'apply'
|
||||||
|
- 'let'
|
||||||
|
- 'run'
|
||||||
|
- 'with'
|
||||||
|
ReplaceSafeCallChainWithRun:
|
||||||
|
active: false
|
||||||
|
StringLiteralDuplication:
|
||||||
|
active: false
|
||||||
|
threshold: 4
|
||||||
|
ignoreAnnotation: true
|
||||||
|
excludeStringsWithLessThan5Characters: true
|
||||||
|
ignoreStringsRegex: '$^'
|
||||||
|
TooManyFunctions:
|
||||||
|
active: true
|
||||||
|
thresholdInFiles: 40
|
||||||
|
thresholdInClasses: 40
|
||||||
|
thresholdInInterfaces: 25
|
||||||
|
thresholdInObjects: 25
|
||||||
|
thresholdInEnums: 15
|
||||||
|
ignoreDeprecated: true
|
||||||
|
ignorePrivate: true
|
||||||
|
ignoreOverridden: true
|
||||||
|
|
||||||
|
coroutines:
|
||||||
|
active: true
|
||||||
|
GlobalCoroutineUsage:
|
||||||
|
active: true
|
||||||
|
InjectDispatcher:
|
||||||
|
active: true
|
||||||
|
dispatcherNames:
|
||||||
|
- 'IO'
|
||||||
|
- 'Default'
|
||||||
|
- 'Unconfined'
|
||||||
|
RedundantSuspendModifier:
|
||||||
|
active: true
|
||||||
|
SleepInsteadOfDelay:
|
||||||
|
active: true
|
||||||
|
SuspendFunSwallowedCancellation:
|
||||||
|
active: true
|
||||||
|
SuspendFunWithCoroutineScopeReceiver:
|
||||||
|
active: true
|
||||||
|
SuspendFunWithFlowReturnType:
|
||||||
|
active: true
|
||||||
|
|
||||||
|
empty-blocks:
|
||||||
|
active: true
|
||||||
|
EmptyCatchBlock:
|
||||||
|
active: true
|
||||||
|
allowedExceptionNameRegex: '_|(ignore|expected).*'
|
||||||
|
EmptyClassBlock:
|
||||||
|
active: true
|
||||||
|
EmptyDefaultConstructor:
|
||||||
|
active: true
|
||||||
|
EmptyDoWhileBlock:
|
||||||
|
active: true
|
||||||
|
EmptyElseBlock:
|
||||||
|
active: true
|
||||||
|
EmptyFinallyBlock:
|
||||||
|
active: true
|
||||||
|
EmptyForBlock:
|
||||||
|
active: true
|
||||||
|
EmptyFunctionBlock:
|
||||||
|
active: true
|
||||||
|
ignoreOverridden: true
|
||||||
|
EmptyIfBlock:
|
||||||
|
active: true
|
||||||
|
EmptyInitBlock:
|
||||||
|
active: true
|
||||||
|
EmptyKtFile:
|
||||||
|
active: true
|
||||||
|
EmptySecondaryConstructor:
|
||||||
|
active: true
|
||||||
|
EmptyTryBlock:
|
||||||
|
active: true
|
||||||
|
EmptyWhenBlock:
|
||||||
|
active: true
|
||||||
|
EmptyWhileBlock:
|
||||||
|
active: true
|
||||||
|
|
||||||
|
exceptions:
|
||||||
|
active: true
|
||||||
|
ExceptionRaisedInUnexpectedLocation:
|
||||||
|
active: true
|
||||||
|
methodNames:
|
||||||
|
- 'equals'
|
||||||
|
- 'finalize'
|
||||||
|
- 'hashCode'
|
||||||
|
- 'toString'
|
||||||
|
InstanceOfCheckForException:
|
||||||
|
active: true
|
||||||
|
NotImplementedDeclaration:
|
||||||
|
active: false
|
||||||
|
ObjectExtendsThrowable:
|
||||||
|
active: false
|
||||||
|
PrintStackTrace:
|
||||||
|
active: true
|
||||||
|
RethrowCaughtException:
|
||||||
|
active: true
|
||||||
|
ReturnFromFinally:
|
||||||
|
active: true
|
||||||
|
SwallowedException:
|
||||||
|
active: false
|
||||||
|
ignoredExceptionTypes:
|
||||||
|
- 'InterruptedException'
|
||||||
|
- 'MalformedURLException'
|
||||||
|
- 'NumberFormatException'
|
||||||
|
- 'ParseException'
|
||||||
|
allowedExceptionNameRegex: '_|(ignore|expected).*'
|
||||||
|
ThrowingExceptionFromFinally:
|
||||||
|
active: true
|
||||||
|
ThrowingExceptionInMain:
|
||||||
|
active: false
|
||||||
|
ThrowingExceptionsWithoutMessageOrCause:
|
||||||
|
active: true
|
||||||
|
excludes: ['**/test/**', '**/androidTest/**', '**/*.Test.kt', '**/*.Spec.kt', '**/*.Spek.kt']
|
||||||
|
exceptions:
|
||||||
|
- 'ArrayIndexOutOfBoundsException'
|
||||||
|
- 'Exception'
|
||||||
|
- 'IllegalArgumentException'
|
||||||
|
- 'IllegalMonitorStateException'
|
||||||
|
- 'IllegalStateException'
|
||||||
|
- 'IndexOutOfBoundsException'
|
||||||
|
- 'NullPointerException'
|
||||||
|
- 'RuntimeException'
|
||||||
|
- 'Throwable'
|
||||||
|
ThrowingNewInstanceOfSameException:
|
||||||
|
active: true
|
||||||
|
TooGenericExceptionCaught:
|
||||||
|
active: false
|
||||||
|
excludes: ['**/test/**', '**/androidTest/**', '**/*.Test.kt', '**/*.Spec.kt', '**/*.Spek.kt']
|
||||||
|
exceptionNames:
|
||||||
|
- 'ArrayIndexOutOfBoundsException'
|
||||||
|
- 'Error'
|
||||||
|
- 'Exception'
|
||||||
|
- 'IllegalMonitorStateException'
|
||||||
|
- 'IndexOutOfBoundsException'
|
||||||
|
- 'NullPointerException'
|
||||||
|
- 'RuntimeException'
|
||||||
|
- 'Throwable'
|
||||||
|
allowedExceptionNameRegex: '_|(ignore|expected).*'
|
||||||
|
TooGenericExceptionThrown:
|
||||||
|
active: false
|
||||||
|
exceptionNames:
|
||||||
|
- 'Error'
|
||||||
|
- 'Exception'
|
||||||
|
- 'RuntimeException'
|
||||||
|
- 'Throwable'
|
||||||
|
|
||||||
|
naming:
|
||||||
|
active: true
|
||||||
|
BooleanPropertyNaming:
|
||||||
|
active: true
|
||||||
|
allowedPattern: '^(is|has|are|should|can|will|does|did)'
|
||||||
|
ClassNaming:
|
||||||
|
active: true
|
||||||
|
classPattern: '[A-Z][a-zA-Z0-9]*'
|
||||||
|
ConstructorParameterNaming:
|
||||||
|
active: true
|
||||||
|
parameterPattern: '[a-z][A-Za-z0-9]*'
|
||||||
|
privateParameterPattern: '[a-z][A-Za-z0-9]*'
|
||||||
|
excludeClassPattern: '$^'
|
||||||
|
EnumNaming:
|
||||||
|
active: true
|
||||||
|
enumEntryPattern: '[A-Z][_a-zA-Z0-9]*'
|
||||||
|
ForbiddenClassName:
|
||||||
|
active: false
|
||||||
|
FunctionMaxLength:
|
||||||
|
active: false
|
||||||
|
FunctionMinLength:
|
||||||
|
active: false
|
||||||
|
FunctionNaming:
|
||||||
|
active: true
|
||||||
|
functionPattern: '[a-zA-Z][a-zA-Z0-9]*'
|
||||||
|
excludeClassPattern: '$^'
|
||||||
|
ignoreAnnotated:
|
||||||
|
- 'Composable'
|
||||||
|
FunctionParameterNaming:
|
||||||
|
active: true
|
||||||
|
parameterPattern: '[a-z][A-Za-z0-9]*'
|
||||||
|
excludeClassPattern: '$^'
|
||||||
|
InvalidPackageDeclaration:
|
||||||
|
active: true
|
||||||
|
rootPackage: 'com.atridad.ascently'
|
||||||
|
LambdaParameterNaming:
|
||||||
|
active: true
|
||||||
|
parameterPattern: '[a-z][A-Za-z0-9]*|_'
|
||||||
|
MatchingDeclarationName:
|
||||||
|
active: false
|
||||||
|
mustBeFirst: true
|
||||||
|
MemberNameEqualsClassName:
|
||||||
|
active: true
|
||||||
|
ignoreOverridden: true
|
||||||
|
NoNameShadowing:
|
||||||
|
active: true
|
||||||
|
NonBooleanPropertyPrefixedWithIs:
|
||||||
|
active: true
|
||||||
|
ObjectPropertyNaming:
|
||||||
|
active: false
|
||||||
|
PackageNaming:
|
||||||
|
active: true
|
||||||
|
packagePattern: '[a-z]+(\.[a-z][A-Za-z0-9]*)*'
|
||||||
|
TopLevelPropertyNaming:
|
||||||
|
active: true
|
||||||
|
constantPattern: '[A-Z][_A-Z0-9]*'
|
||||||
|
propertyPattern: '[A-Za-z][_A-Za-z0-9]*'
|
||||||
|
privatePropertyPattern: '_?[A-Za-z][A-Za-z0-9]*'
|
||||||
|
VariableMaxLength:
|
||||||
|
active: false
|
||||||
|
VariableMinLength:
|
||||||
|
active: false
|
||||||
|
VariableNaming:
|
||||||
|
active: true
|
||||||
|
variablePattern: '[a-z][A-Za-z0-9]*'
|
||||||
|
privateVariablePattern: '[_a-z][A-Za-z0-9]*'
|
||||||
|
excludeClassPattern: '$^'
|
||||||
|
|
||||||
|
performance:
|
||||||
|
active: true
|
||||||
|
ArrayPrimitive:
|
||||||
|
active: true
|
||||||
|
CouldBeSequence:
|
||||||
|
active: false
|
||||||
|
ForEachOnRange:
|
||||||
|
active: true
|
||||||
|
SpreadOperator:
|
||||||
|
active: false
|
||||||
|
UnnecessaryPartOfBinaryExpression:
|
||||||
|
active: true
|
||||||
|
UnnecessaryTemporaryInstantiation:
|
||||||
|
active: true
|
||||||
|
|
||||||
|
potential-bugs:
|
||||||
|
active: true
|
||||||
|
AvoidReferentialEquality:
|
||||||
|
active: true
|
||||||
|
CastNullableToNonNullableType:
|
||||||
|
active: true
|
||||||
|
CastToNullableType:
|
||||||
|
active: false
|
||||||
|
Deprecation:
|
||||||
|
active: false
|
||||||
|
DontDowncastCollectionTypes:
|
||||||
|
active: true
|
||||||
|
DoubleMutabilityForCollection:
|
||||||
|
active: true
|
||||||
|
ElseCaseInsteadOfExhaustiveWhen:
|
||||||
|
active: false
|
||||||
|
EqualsAlwaysReturnsTrueOrFalse:
|
||||||
|
active: true
|
||||||
|
EqualsWithHashCodeExist:
|
||||||
|
active: true
|
||||||
|
ExitOutsideMain:
|
||||||
|
active: false
|
||||||
|
ExplicitGarbageCollectionCall:
|
||||||
|
active: true
|
||||||
|
HasPlatformType:
|
||||||
|
active: true
|
||||||
|
IgnoredReturnValue:
|
||||||
|
active: true
|
||||||
|
ImplicitDefaultLocale:
|
||||||
|
active: true
|
||||||
|
ImplicitUnitReturnType:
|
||||||
|
active: true
|
||||||
|
allowExplicitReturnType: true
|
||||||
|
InvalidRange:
|
||||||
|
active: true
|
||||||
|
IteratorHasNextCallsNextMethod:
|
||||||
|
active: true
|
||||||
|
IteratorNotThrowingNoSuchElementException:
|
||||||
|
active: true
|
||||||
|
LateinitUsage:
|
||||||
|
active: false
|
||||||
|
MapGetWithNotNullAssertionOperator:
|
||||||
|
active: true
|
||||||
|
MissingPackageDeclaration:
|
||||||
|
active: true
|
||||||
|
NullCheckOnMutableProperty:
|
||||||
|
active: true
|
||||||
|
NullableToStringCall:
|
||||||
|
active: true
|
||||||
|
PropertyUsedBeforeDeclaration:
|
||||||
|
active: false
|
||||||
|
UnconditionalJumpStatementInLoop:
|
||||||
|
active: true
|
||||||
|
UnnecessaryNotNullCheck:
|
||||||
|
active: true
|
||||||
|
UnnecessaryNotNullOperator:
|
||||||
|
active: true
|
||||||
|
UnnecessarySafeCall:
|
||||||
|
active: true
|
||||||
|
UnreachableCatchBlock:
|
||||||
|
active: true
|
||||||
|
UnreachableCode:
|
||||||
|
active: true
|
||||||
|
UnsafeCallOnNullableType:
|
||||||
|
active: true
|
||||||
|
UnsafeCast:
|
||||||
|
active: true
|
||||||
|
UnusedUnaryOperator:
|
||||||
|
active: true
|
||||||
|
UselessPostfixExpression:
|
||||||
|
active: true
|
||||||
|
WrongEqualsTypeParameter:
|
||||||
|
active: true
|
||||||
|
|
||||||
|
style:
|
||||||
|
active: true
|
||||||
|
AlsoCouldBeApply:
|
||||||
|
active: false
|
||||||
|
BracesOnIfStatements:
|
||||||
|
active: false
|
||||||
|
singleLine: 'never'
|
||||||
|
multiLine: 'always'
|
||||||
|
BracesOnWhenStatements:
|
||||||
|
active: false
|
||||||
|
singleLine: 'necessary'
|
||||||
|
multiLine: 'necessary'
|
||||||
|
CanBeNonNullable:
|
||||||
|
active: true
|
||||||
|
CascadingCallWrapping:
|
||||||
|
active: false
|
||||||
|
ClassOrdering:
|
||||||
|
active: false
|
||||||
|
CollapsibleIfStatements:
|
||||||
|
active: false
|
||||||
|
DataClassContainsFunctions:
|
||||||
|
active: false
|
||||||
|
DataClassShouldBeImmutable:
|
||||||
|
active: true
|
||||||
|
DestructuringDeclarationWithTooManyEntries:
|
||||||
|
active: true
|
||||||
|
maxDestructuringEntries: 5
|
||||||
|
EqualsNullCall:
|
||||||
|
active: true
|
||||||
|
EqualsOnSignatureLine:
|
||||||
|
active: true
|
||||||
|
ExplicitCollectionElementAccessMethod:
|
||||||
|
active: true
|
||||||
|
ExplicitItLambdaParameter:
|
||||||
|
active: false
|
||||||
|
ExpressionBodySyntax:
|
||||||
|
active: false
|
||||||
|
includeLineWrapping: false
|
||||||
|
ForbiddenAnnotation:
|
||||||
|
active: false
|
||||||
|
ForbiddenComment:
|
||||||
|
active: false
|
||||||
|
ForbiddenImport:
|
||||||
|
active: false
|
||||||
|
ForbiddenMethodCall:
|
||||||
|
active: false
|
||||||
|
ForbiddenSuppress:
|
||||||
|
active: false
|
||||||
|
ForbiddenVoid:
|
||||||
|
active: true
|
||||||
|
ignoreOverridden: true
|
||||||
|
ignoreUsageInGenerics: true
|
||||||
|
FunctionOnlyReturningConstant:
|
||||||
|
active: false
|
||||||
|
ignoreOverridableFunction: true
|
||||||
|
ignoreActualFunction: true
|
||||||
|
excludedFunctions: []
|
||||||
|
LoopWithTooManyJumpStatements:
|
||||||
|
active: true
|
||||||
|
maxJumpCount: 2
|
||||||
|
MagicNumber:
|
||||||
|
active: false
|
||||||
|
MandatoryBracesLoops:
|
||||||
|
active: true
|
||||||
|
MaxChainedCallsOnSameLine:
|
||||||
|
active: true
|
||||||
|
maxChainedCalls: 5
|
||||||
|
MaxLineLength:
|
||||||
|
active: true
|
||||||
|
maxLineLength: 220
|
||||||
|
excludePackageStatements: true
|
||||||
|
excludeImportStatements: true
|
||||||
|
excludeCommentStatements: true
|
||||||
|
excludeRawStrings: true
|
||||||
|
MayBeConst:
|
||||||
|
active: true
|
||||||
|
ModifierOrder:
|
||||||
|
active: true
|
||||||
|
MultilineRawStringIndentation:
|
||||||
|
active: false
|
||||||
|
indentSize: 4
|
||||||
|
MultilineLambdaItParameter:
|
||||||
|
active: true
|
||||||
|
NestedClassesVisibility:
|
||||||
|
active: true
|
||||||
|
NewLineAtEndOfFile:
|
||||||
|
active: false
|
||||||
|
NoTabs:
|
||||||
|
active: true
|
||||||
|
NullableBooleanCheck:
|
||||||
|
active: true
|
||||||
|
ObjectLiteralToLambda:
|
||||||
|
active: true
|
||||||
|
OptionalAbstractKeyword:
|
||||||
|
active: true
|
||||||
|
OptionalUnit:
|
||||||
|
active: true
|
||||||
|
PreferToOverPairSyntax:
|
||||||
|
active: true
|
||||||
|
ProtectedMemberInFinalClass:
|
||||||
|
active: true
|
||||||
|
RedundantExplicitType:
|
||||||
|
active: true
|
||||||
|
RedundantHigherOrderMapUsage:
|
||||||
|
active: true
|
||||||
|
RedundantVisibilityModifierRule:
|
||||||
|
active: false
|
||||||
|
ReturnCount:
|
||||||
|
active: true
|
||||||
|
max: 6
|
||||||
|
excludedFunctions:
|
||||||
|
- 'equals'
|
||||||
|
excludeLabeled: true
|
||||||
|
excludeReturnFromLambda: true
|
||||||
|
excludeGuardClauses: true
|
||||||
|
SafeCast:
|
||||||
|
active: true
|
||||||
|
SerialVersionUIDInSerializableClass:
|
||||||
|
active: false
|
||||||
|
SpacingBetweenPackageAndImports:
|
||||||
|
active: true
|
||||||
|
StringShouldBeRawString:
|
||||||
|
active: false
|
||||||
|
ThrowsCount:
|
||||||
|
active: true
|
||||||
|
max: 10
|
||||||
|
excludeGuardClauses: true
|
||||||
|
TrailingWhitespace:
|
||||||
|
active: false
|
||||||
|
TrimMultilineRawString:
|
||||||
|
active: true
|
||||||
|
UnderscoresInNumericLiterals:
|
||||||
|
active: false
|
||||||
|
acceptableLength: 4
|
||||||
|
allowNonStandardGrouping: false
|
||||||
|
UnnecessaryAbstractClass:
|
||||||
|
active: true
|
||||||
|
UnnecessaryAnnotationUseSiteTarget:
|
||||||
|
active: true
|
||||||
|
UnnecessaryApply:
|
||||||
|
active: true
|
||||||
|
UnnecessaryBackticks:
|
||||||
|
active: true
|
||||||
|
UnnecessaryBracesAroundTrailingLambda:
|
||||||
|
active: true
|
||||||
|
UnnecessaryFilter:
|
||||||
|
active: true
|
||||||
|
UnnecessaryInheritance:
|
||||||
|
active: true
|
||||||
|
UnnecessaryInnerClass:
|
||||||
|
active: true
|
||||||
|
UnnecessaryLet:
|
||||||
|
active: true
|
||||||
|
UnnecessaryParentheses:
|
||||||
|
active: false
|
||||||
|
allowForUnclearPrecedence: true
|
||||||
|
UntilInsteadOfRangeTo:
|
||||||
|
active: true
|
||||||
|
UnusedImports:
|
||||||
|
active: true
|
||||||
|
UnusedParameter:
|
||||||
|
active: true
|
||||||
|
allowedNames: 'ignored|expected|_|session|startTime|endTime|xAxisFormatter'
|
||||||
|
UnusedPrivateClass:
|
||||||
|
active: true
|
||||||
|
UnusedPrivateMember:
|
||||||
|
active: true
|
||||||
|
allowedNames: '(_|ignored|expected|serialVersionUID)'
|
||||||
|
UnusedPrivateProperty:
|
||||||
|
active: true
|
||||||
|
allowedNames: '_|ignored|expected|serialVersionUID'
|
||||||
|
UseAnyOrNoneInsteadOfFind:
|
||||||
|
active: true
|
||||||
|
UseArrayLiteralsInAnnotations:
|
||||||
|
active: true
|
||||||
|
UseCheckNotNull:
|
||||||
|
active: true
|
||||||
|
UseCheckOrError:
|
||||||
|
active: true
|
||||||
|
UseDataClass:
|
||||||
|
active: false
|
||||||
|
UseEmptyCounterpart:
|
||||||
|
active: true
|
||||||
|
UseIfEmptyOrIfBlank:
|
||||||
|
active: true
|
||||||
|
UseIfInsteadOfWhen:
|
||||||
|
active: false
|
||||||
|
UseIsNullOrEmpty:
|
||||||
|
active: true
|
||||||
|
UseLet:
|
||||||
|
active: false
|
||||||
|
UseOrEmpty:
|
||||||
|
active: true
|
||||||
|
UseRequire:
|
||||||
|
active: true
|
||||||
|
UseRequireNotNull:
|
||||||
|
active: true
|
||||||
|
UseSumOfInsteadOfFlatMapSize:
|
||||||
|
active: true
|
||||||
|
UselessCallOnNotNull:
|
||||||
|
active: true
|
||||||
|
UtilityClassWithPublicConstructor:
|
||||||
|
active: true
|
||||||
|
VarCouldBeVal:
|
||||||
|
active: true
|
||||||
|
WildcardImport:
|
||||||
|
active: false
|
||||||
|
excludeImports:
|
||||||
|
- 'java.util.*'
|
||||||
|
- 'kotlinx.android.synthetic.*'
|
||||||
@@ -10,7 +10,11 @@ org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
|||||||
# When configured, Gradle will run in incubating parallel mode.
|
# When configured, Gradle will run in incubating parallel mode.
|
||||||
# This option should only be used with decoupled projects. For more details, visit
|
# This option should only be used with decoupled projects. For more details, visit
|
||||||
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
|
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
|
||||||
# org.gradle.parallel=true
|
org.gradle.parallel=true
|
||||||
|
# Enable Gradle build caching for faster incremental builds
|
||||||
|
org.gradle.caching=true
|
||||||
|
# Enable configuration caching for faster configuration phase
|
||||||
|
org.gradle.configuration-cache=true
|
||||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||||
# Android operating system, and which are packaged with your app's APK
|
# Android operating system, and which are packaged with your app's APK
|
||||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[versions]
|
[versions]
|
||||||
agp = "8.12.3"
|
agp = "8.12.3"
|
||||||
kotlin = "2.2.20"
|
kotlin = "2.2.21"
|
||||||
coreKtx = "1.17.0"
|
coreKtx = "1.17.0"
|
||||||
junit = "4.13.2"
|
junit = "4.13.2"
|
||||||
junitVersion = "1.3.0"
|
junitVersion = "1.3.0"
|
||||||
@@ -9,17 +9,20 @@ androidxTestCore = "1.7.0"
|
|||||||
androidxTestExt = "1.3.0"
|
androidxTestExt = "1.3.0"
|
||||||
androidxTestRunner = "1.7.0"
|
androidxTestRunner = "1.7.0"
|
||||||
androidxTestRules = "1.7.0"
|
androidxTestRules = "1.7.0"
|
||||||
lifecycleRuntimeKtx = "2.9.4"
|
lifecycleRuntimeKtx = "2.10.0"
|
||||||
activityCompose = "1.11.0"
|
activityCompose = "1.12.0"
|
||||||
composeBom = "2025.10.00"
|
composeBom = "2025.11.01"
|
||||||
room = "2.8.2"
|
room = "2.8.4"
|
||||||
navigation = "2.9.5"
|
navigation = "2.9.6"
|
||||||
viewmodel = "2.9.4"
|
viewmodel = "2.10.0"
|
||||||
kotlinxSerialization = "1.9.0"
|
kotlinxSerialization = "1.9.0"
|
||||||
kotlinxCoroutines = "1.10.2"
|
kotlinxCoroutines = "1.10.2"
|
||||||
coil = "2.7.0"
|
coil = "2.7.0"
|
||||||
ksp = "2.2.20-2.0.3"
|
ksp = "2.2.20-2.0.3"
|
||||||
exifinterface = "1.3.6"
|
exifinterface = "1.4.1"
|
||||||
|
healthConnect = "1.1.0-alpha07"
|
||||||
|
detekt = "1.23.7"
|
||||||
|
spotless = "6.25.0"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||||
@@ -69,9 +72,14 @@ mockk = { group = "io.mockk", name = "mockk", version = "1.14.6" }
|
|||||||
coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coil" }
|
coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coil" }
|
||||||
androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" }
|
androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" }
|
||||||
|
|
||||||
|
# Health Connect
|
||||||
|
health-connect = { group = "androidx.health.connect", name = "connect-client", version.ref = "healthConnect" }
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||||
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||||
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||||||
|
detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" }
|
||||||
|
spotless = { id = "com.diffplug.spotless", version.ref = "spotless" }
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "ascently-docs",
|
"name": "ascently-docs",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "1.0.0",
|
"version": "1.1.0",
|
||||||
"description": "Documentation site for Ascently - FOSS climbing tracking app",
|
"description": "Documentation site for Ascently - FOSS climbing tracking app",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -25,13 +25,13 @@
|
|||||||
"astro": "astro"
|
"astro": "astro"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/node": "^9.5.0",
|
"@astrojs/node": "^9.5.1",
|
||||||
"@astrojs/starlight": "^0.36.1",
|
"@astrojs/starlight": "^0.37.1",
|
||||||
"astro": "^5.14.6",
|
"astro": "^5.16.5",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"sharp": "^0.34.4"
|
"sharp": "^0.34.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/qrcode": "^1.5.5"
|
"@types/qrcode": "^1.5.6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1271
docs/pnpm-lock.yaml
generated
1271
docs/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,62 @@ const hasLink = (link: string | undefined) => link && link.trim() !== "";
|
|||||||
---
|
---
|
||||||
|
|
||||||
<Tabs syncKey="platform">
|
<Tabs syncKey="platform">
|
||||||
|
<TabItem label="iOS" icon="apple">
|
||||||
|
<CardGrid>
|
||||||
|
{
|
||||||
|
hasLink(downloadLinks.ios.appStore) && (
|
||||||
|
<Card title="App Store" icon="rocket">
|
||||||
|
<p style="text-align: center;">
|
||||||
|
<LinkButton
|
||||||
|
href={downloadLinks.ios.appStore}
|
||||||
|
variant="primary"
|
||||||
|
icon="external"
|
||||||
|
>
|
||||||
|
Download on App Store
|
||||||
|
</LinkButton>
|
||||||
|
</p>
|
||||||
|
{showQR && (
|
||||||
|
<p style="text-align: center;">
|
||||||
|
<QRCode
|
||||||
|
data={downloadLinks.ios.appStore}
|
||||||
|
size={200}
|
||||||
|
alt="QR code for App Store"
|
||||||
|
/>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
hasLink(downloadLinks.ios.testFlight) && (
|
||||||
|
<Card title="TestFlight Beta" icon="warning">
|
||||||
|
<p style="text-align: center;">
|
||||||
|
<LinkButton
|
||||||
|
href={downloadLinks.ios.testFlight}
|
||||||
|
variant="secondary"
|
||||||
|
icon="external"
|
||||||
|
>
|
||||||
|
Join TestFlight
|
||||||
|
</LinkButton>
|
||||||
|
</p>
|
||||||
|
{showQR && (
|
||||||
|
<p style="text-align: center;">
|
||||||
|
<QRCode
|
||||||
|
data={downloadLinks.ios.testFlight}
|
||||||
|
size={200}
|
||||||
|
alt="QR code for TestFlight"
|
||||||
|
/>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</CardGrid>
|
||||||
|
|
||||||
|
<p><strong>Requirements:</strong> {requirements.ios}</p>
|
||||||
|
</TabItem>
|
||||||
|
|
||||||
<TabItem label="Android" icon="star">
|
<TabItem label="Android" icon="star">
|
||||||
<CardGrid>
|
<CardGrid>
|
||||||
{
|
{
|
||||||
@@ -96,60 +152,4 @@ const hasLink = (link: string | undefined) => link && link.trim() !== "";
|
|||||||
|
|
||||||
<p><strong>Requirements:</strong> {requirements.android}</p>
|
<p><strong>Requirements:</strong> {requirements.android}</p>
|
||||||
</TabItem>
|
</TabItem>
|
||||||
|
|
||||||
<TabItem label="iOS" icon="apple">
|
|
||||||
<CardGrid>
|
|
||||||
{
|
|
||||||
hasLink(downloadLinks.ios.appStore) && (
|
|
||||||
<Card title="App Store" icon="rocket">
|
|
||||||
<p style="text-align: center;">
|
|
||||||
<LinkButton
|
|
||||||
href={downloadLinks.ios.appStore}
|
|
||||||
variant="primary"
|
|
||||||
icon="external"
|
|
||||||
>
|
|
||||||
Download on App Store
|
|
||||||
</LinkButton>
|
|
||||||
</p>
|
|
||||||
{showQR && (
|
|
||||||
<p style="text-align: center;">
|
|
||||||
<QRCode
|
|
||||||
data={downloadLinks.ios.appStore}
|
|
||||||
size={200}
|
|
||||||
alt="QR code for App Store"
|
|
||||||
/>
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</Card>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
hasLink(downloadLinks.ios.testFlight) && (
|
|
||||||
<Card title="TestFlight Beta" icon="warning">
|
|
||||||
<p style="text-align: center;">
|
|
||||||
<LinkButton
|
|
||||||
href={downloadLinks.ios.testFlight}
|
|
||||||
variant="secondary"
|
|
||||||
icon="external"
|
|
||||||
>
|
|
||||||
Join TestFlight
|
|
||||||
</LinkButton>
|
|
||||||
</p>
|
|
||||||
{showQR && (
|
|
||||||
<p style="text-align: center;">
|
|
||||||
<QRCode
|
|
||||||
data={downloadLinks.ios.testFlight}
|
|
||||||
size={200}
|
|
||||||
alt="QR code for TestFlight"
|
|
||||||
/>
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</Card>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
</CardGrid>
|
|
||||||
|
|
||||||
<p><strong>Requirements:</strong> {requirements.ios}</p>
|
|
||||||
</TabItem>
|
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ export const requirements = {
|
|||||||
|
|
||||||
export const downloadLinks = {
|
export const downloadLinks = {
|
||||||
android: {
|
android: {
|
||||||
releases: "https://git.atri.dad/atridad/Ascently/releases",
|
releases: "https://git.atri.dad/atridad/Ascently/tags?q=Android",
|
||||||
obtainium:
|
obtainium:
|
||||||
"https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.atri.dad/atridad/Ascently/releases",
|
"https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.atri.dad/atridad/Ascently/releases",
|
||||||
playStore: "",
|
playStore: "",
|
||||||
|
|||||||
@@ -42,6 +42,6 @@ Ascently is an **offline-first FOSS** app designed to help climbers track their
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
*Built with ❤️ by Atridad Lahiji*
|
*Built with ❤️ by [Atridad Lahiji](https://atri.dad)*
|
||||||
|
|
||||||
*Contact: me@atri.dad*
|
*Contact: me@atri.dad*
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description: Ascently's Privacy Policy
|
|||||||
|
|
||||||
**Last updated: September 29, 2025**
|
**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.
|
This Privacy Policy describes my policies and procedures regarding the collection, use, and disclosure of your information when you use my software.
|
||||||
|
|
||||||
## No Data Collection
|
## No Data Collection
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ You may optionally integrate with Apple Health or Android Health Connect to impo
|
|||||||
|
|
||||||
This software does not use cookies, tracking pixels, or any other analytics or tracking mechanisms. Your usage of the software is completely private.
|
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
|
## Contact
|
||||||
|
|
||||||
If you have any questions about this Privacy Policy, you can contact me:
|
If you have any questions about this Privacy Policy, you can contact me:
|
||||||
|
|
||||||
|
|||||||
22
ios/.editorconfig
Normal file
22
ios/.editorconfig
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
end_of_line = lf
|
||||||
|
charset = utf-8
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
|
|
||||||
|
[*.swift]
|
||||||
|
indent_size = 4
|
||||||
|
max_line_length = 140
|
||||||
|
|
||||||
|
[*.{plist,storyboard,xib,xcscheme,xcworkspacedata}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
|
|
||||||
|
[Makefile]
|
||||||
|
indent_style = tab
|
||||||
68
ios/.swiftformat
Normal file
68
ios/.swiftformat
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# SwiftFormat Configuration for Ascently iOS
|
||||||
|
# Maintains consistent formatting across the project
|
||||||
|
|
||||||
|
# File options
|
||||||
|
--exclude build,Pods,DerivedData,.build
|
||||||
|
|
||||||
|
# Format options
|
||||||
|
--swiftversion 6.0
|
||||||
|
--indent 4
|
||||||
|
--tabwidth 4
|
||||||
|
--maxwidth 140
|
||||||
|
--wraparguments before-first
|
||||||
|
--wrapparameters before-first
|
||||||
|
--wrapcollections before-first
|
||||||
|
--wrapconditions after-first
|
||||||
|
--wrapreturntype preserve
|
||||||
|
--wrapeffects preserve
|
||||||
|
--closingparen balanced
|
||||||
|
--funcattributes prev-line
|
||||||
|
--typeattributes prev-line
|
||||||
|
--varattributes preserve
|
||||||
|
--storedvarattrs same-line
|
||||||
|
--computedvarattrs preserve
|
||||||
|
--complexattributes prev-line
|
||||||
|
--typeblanklines preserve
|
||||||
|
--structthreshold 20
|
||||||
|
--enumthreshold 20
|
||||||
|
--extensionacl on-declarations
|
||||||
|
--organizetypes class,struct,enum,extension,protocol
|
||||||
|
--modifierorder acl,setteracl,override,static,final,required,convenience,lazy,dynamic
|
||||||
|
--self remove
|
||||||
|
--importgrouping alpha
|
||||||
|
--semicolons inline
|
||||||
|
--operatorfunc spaced
|
||||||
|
--nospaceoperators ..<,...
|
||||||
|
--ranges no-space
|
||||||
|
--emptybraces no-space
|
||||||
|
--trimwhitespace always
|
||||||
|
--stripunusedargs closure-only
|
||||||
|
--header ignore
|
||||||
|
--guardelse auto
|
||||||
|
--elseposition same-line
|
||||||
|
--shortoptionals always
|
||||||
|
--linebreaks lf
|
||||||
|
--xcodeindentation disabled
|
||||||
|
--fragment false
|
||||||
|
--conflictmarkers reject
|
||||||
|
--ifdef no-indent
|
||||||
|
--extensionlength 0
|
||||||
|
|
||||||
|
# Enable rules
|
||||||
|
--enable isEmpty,sortedSwitchCases,redundantInit,redundantGet,redundantObjc
|
||||||
|
--enable blankLineAfterSwitchCase,consecutiveSpaces,duplicateImports
|
||||||
|
--enable elseOnSameLine,emptyBraces,hoistAwait,hoistPatternLet,hoistTry
|
||||||
|
--enable leadingDelimiters,redundantBackticks,redundantBreak,redundantClosure
|
||||||
|
--enable redundantExtensionACL,redundantFileprivate,redundantLetError
|
||||||
|
--enable redundantNilInit,redundantParens,redundantPattern,redundantRawValues
|
||||||
|
--enable redundantReturn,redundantSelf,redundantType,redundantVoidReturnType
|
||||||
|
--enable semicolons,sortImports,spaceAroundBraces,spaceAroundBrackets
|
||||||
|
--enable spaceAroundComments,spaceAroundGenerics,spaceAroundOperators
|
||||||
|
--enable spaceAroundParens,spaceInsideBraces,spaceInsideBrackets
|
||||||
|
--enable spaceInsideComments,spaceInsideGenerics,spaceInsideParens
|
||||||
|
--enable strongOutlets,strongifiedSelf,todos,trailingClosures,trailingCommas
|
||||||
|
--enable typeSugar,unusedArguments,void,wrapArguments,wrapAttributes
|
||||||
|
--enable yodaConditions,blankLinesBetweenScopes,blankLinesAtEndOfScope
|
||||||
|
|
||||||
|
# Disable rules
|
||||||
|
--disable wrapMultilineStatementBraces
|
||||||
139
ios/.swiftlint.yml
Normal file
139
ios/.swiftlint.yml
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
excluded:
|
||||||
|
- build
|
||||||
|
- Pods
|
||||||
|
- DerivedData
|
||||||
|
- .build
|
||||||
|
- AscentlyTests
|
||||||
|
|
||||||
|
disabled_rules:
|
||||||
|
- trailing_whitespace
|
||||||
|
- todo
|
||||||
|
- nesting
|
||||||
|
- opening_brace
|
||||||
|
- multiple_closures_with_trailing_closure
|
||||||
|
- trailing_comma
|
||||||
|
- attributes
|
||||||
|
- function_parameter_count
|
||||||
|
- large_tuple
|
||||||
|
|
||||||
|
opt_in_rules:
|
||||||
|
- empty_count
|
||||||
|
- explicit_init
|
||||||
|
- closure_spacing
|
||||||
|
- overridden_super_call
|
||||||
|
- redundant_nil_coalescing
|
||||||
|
- first_where
|
||||||
|
- sorted_first_last
|
||||||
|
- contains_over_filter_count
|
||||||
|
- contains_over_filter_is_empty
|
||||||
|
- empty_string
|
||||||
|
- prefer_zero_over_explicit_init
|
||||||
|
- flatmap_over_map_reduce
|
||||||
|
- last_where
|
||||||
|
- sorted_imports
|
||||||
|
- toggle_bool
|
||||||
|
- unavailable_function
|
||||||
|
- unneeded_parentheses_in_closure_argument
|
||||||
|
- vertical_whitespace_closing_braces
|
||||||
|
- yoda_condition
|
||||||
|
- collection_alignment
|
||||||
|
- literal_expression_end_indentation
|
||||||
|
|
||||||
|
line_length:
|
||||||
|
warning: 140
|
||||||
|
error: 250
|
||||||
|
ignores_comments: true
|
||||||
|
ignores_urls: true
|
||||||
|
ignores_function_declarations: true
|
||||||
|
ignores_interpolated_strings: true
|
||||||
|
|
||||||
|
type_body_length:
|
||||||
|
warning: 600
|
||||||
|
error: 1000
|
||||||
|
|
||||||
|
file_length:
|
||||||
|
warning: 1000
|
||||||
|
error: 1500
|
||||||
|
ignore_comment_only_lines: true
|
||||||
|
|
||||||
|
function_body_length:
|
||||||
|
warning: 100
|
||||||
|
error: 200
|
||||||
|
|
||||||
|
cyclomatic_complexity:
|
||||||
|
warning: 20
|
||||||
|
error: 30
|
||||||
|
ignores_case_statements: true
|
||||||
|
|
||||||
|
identifier_name:
|
||||||
|
min_length:
|
||||||
|
warning: 2
|
||||||
|
error: 1
|
||||||
|
max_length:
|
||||||
|
warning: 50
|
||||||
|
error: 60
|
||||||
|
validates_start_with_lowercase: error
|
||||||
|
allowed_symbols:
|
||||||
|
- _
|
||||||
|
excluded:
|
||||||
|
- id
|
||||||
|
- i
|
||||||
|
- j
|
||||||
|
- x
|
||||||
|
- y
|
||||||
|
- z
|
||||||
|
- to
|
||||||
|
- at
|
||||||
|
- or
|
||||||
|
- is
|
||||||
|
- no
|
||||||
|
- go
|
||||||
|
- db
|
||||||
|
- DATA_JSON_FILENAME
|
||||||
|
- IMAGES_DIR_NAME
|
||||||
|
- METADATA_FILENAME
|
||||||
|
# ViewBuilder section functions (SwiftUI convention)
|
||||||
|
- StatusSection
|
||||||
|
- IconDisplaySection
|
||||||
|
- DebugSection
|
||||||
|
- TestingSection
|
||||||
|
- ResultsSection
|
||||||
|
- GymSelectionSection
|
||||||
|
- SessionDetailsSection
|
||||||
|
- ProblemSelectionSection
|
||||||
|
- CreateProblemSection
|
||||||
|
- AttemptDetailsSection
|
||||||
|
- BasicInfoSection
|
||||||
|
- ClimbTypesSection
|
||||||
|
- DifficultySystemsSection
|
||||||
|
- NotesSection
|
||||||
|
- ClimbTypeSection
|
||||||
|
- DifficultySection
|
||||||
|
- LocationSection
|
||||||
|
- TagsSection
|
||||||
|
- PhotosSection
|
||||||
|
- AdditionalInfoSection
|
||||||
|
|
||||||
|
type_name:
|
||||||
|
min_length:
|
||||||
|
warning: 3
|
||||||
|
error: 2
|
||||||
|
max_length:
|
||||||
|
warning: 50
|
||||||
|
error: 60
|
||||||
|
|
||||||
|
force_cast: warning
|
||||||
|
|
||||||
|
force_try: warning
|
||||||
|
|
||||||
|
large_tuple:
|
||||||
|
warning: 4
|
||||||
|
error: 6
|
||||||
|
|
||||||
|
nesting:
|
||||||
|
type_level:
|
||||||
|
warning: 3
|
||||||
|
function_level:
|
||||||
|
warning: 5
|
||||||
|
|
||||||
|
reporter: "xcode"
|
||||||
@@ -25,7 +25,7 @@ final class LiveActivityManager {
|
|||||||
pushType: nil
|
pushType: nil
|
||||||
)
|
)
|
||||||
} catch {
|
} catch {
|
||||||
print("Failed to start live activity: \(error)")
|
AppLogger.error("Failed to start live activity: \(error)", tag: "LegacyLiveActivityManager")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -465,7 +465,7 @@
|
|||||||
CODE_SIGN_ENTITLEMENTS = Ascently/Ascently.entitlements;
|
CODE_SIGN_ENTITLEMENTS = Ascently/Ascently.entitlements;
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 30;
|
CURRENT_PROJECT_VERSION = 39;
|
||||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||||
DRIVERKIT_DEPLOYMENT_TARGET = 24.6;
|
DRIVERKIT_DEPLOYMENT_TARGET = 24.6;
|
||||||
ENABLE_PREVIEWS = YES;
|
ENABLE_PREVIEWS = YES;
|
||||||
@@ -487,7 +487,7 @@
|
|||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
||||||
MARKETING_VERSION = 2.2.0;
|
MARKETING_VERSION = 2.5.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently;
|
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
@@ -513,7 +513,7 @@
|
|||||||
CODE_SIGN_ENTITLEMENTS = Ascently/Ascently.entitlements;
|
CODE_SIGN_ENTITLEMENTS = Ascently/Ascently.entitlements;
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 30;
|
CURRENT_PROJECT_VERSION = 39;
|
||||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||||
DRIVERKIT_DEPLOYMENT_TARGET = 24.6;
|
DRIVERKIT_DEPLOYMENT_TARGET = 24.6;
|
||||||
ENABLE_PREVIEWS = YES;
|
ENABLE_PREVIEWS = YES;
|
||||||
@@ -535,7 +535,7 @@
|
|||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
||||||
MARKETING_VERSION = 2.2.0;
|
MARKETING_VERSION = 2.5.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently;
|
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
@@ -602,7 +602,7 @@
|
|||||||
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
|
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
|
||||||
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
|
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 30;
|
CURRENT_PROJECT_VERSION = 39;
|
||||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
INFOPLIST_FILE = SessionStatusLive/Info.plist;
|
INFOPLIST_FILE = SessionStatusLive/Info.plist;
|
||||||
@@ -613,7 +613,7 @@
|
|||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
"@executable_path/../../Frameworks",
|
"@executable_path/../../Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 2.2.0;
|
MARKETING_VERSION = 2.5.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently.SessionStatusLive;
|
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently.SessionStatusLive;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SKIP_INSTALL = YES;
|
SKIP_INSTALL = YES;
|
||||||
@@ -632,7 +632,7 @@
|
|||||||
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
|
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
|
||||||
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
|
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 30;
|
CURRENT_PROJECT_VERSION = 39;
|
||||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
INFOPLIST_FILE = SessionStatusLive/Info.plist;
|
INFOPLIST_FILE = SessionStatusLive/Info.plist;
|
||||||
@@ -643,7 +643,7 @@
|
|||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
"@executable_path/../../Frameworks",
|
"@executable_path/../../Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 2.2.0;
|
MARKETING_VERSION = 2.5.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently.SessionStatusLive;
|
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.Ascently.SessionStatusLive;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SKIP_INSTALL = YES;
|
SKIP_INSTALL = YES;
|
||||||
|
|||||||
Binary file not shown.
24
ios/Ascently/AppIntents/AscentlyShortcuts.swift
Normal file
24
ios/Ascently/AppIntents/AscentlyShortcuts.swift
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import AppIntents
|
||||||
|
|
||||||
|
/// Defines the App Shortcuts available in the Shortcuts app.
|
||||||
|
struct AscentlyShortcuts: AppShortcutsProvider {
|
||||||
|
|
||||||
|
static var shortcutTileColor: ShortcutTileColor {
|
||||||
|
.teal
|
||||||
|
}
|
||||||
|
|
||||||
|
static var appShortcuts: [AppShortcut] {
|
||||||
|
return [
|
||||||
|
AppShortcut(
|
||||||
|
intent: ToggleSessionIntent(),
|
||||||
|
phrases: [
|
||||||
|
"Toggle climb in \(.applicationName)",
|
||||||
|
"Start or stop climb in \(.applicationName)",
|
||||||
|
"Climb toggle in \(.applicationName)",
|
||||||
|
],
|
||||||
|
shortTitle: "Toggle Session",
|
||||||
|
systemImageName: "figure.climbing"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
111
ios/Ascently/AppIntents/SessionIntentSupport.swift
Normal file
111
ios/Ascently/AppIntents/SessionIntentSupport.swift
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// User-visible errors that can arise while handling session-related intents.
|
||||||
|
enum SessionIntentError: LocalizedError {
|
||||||
|
case noRecentGym
|
||||||
|
case noActiveSession
|
||||||
|
case failedToStartSession
|
||||||
|
case failedToEndSession
|
||||||
|
|
||||||
|
var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .noRecentGym:
|
||||||
|
return "There's no recent gym to start a session with."
|
||||||
|
case .noActiveSession:
|
||||||
|
return "There isn't an active session to end right now."
|
||||||
|
case .failedToStartSession:
|
||||||
|
return "Ascently couldn't start a new session."
|
||||||
|
case .failedToEndSession:
|
||||||
|
return "Ascently couldn't finish the active session."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SessionIntentSummary: Sendable {
|
||||||
|
let sessionId: UUID
|
||||||
|
let gymName: String
|
||||||
|
let status: SessionStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Controller for handling session operations from App Intents.
|
||||||
|
@MainActor
|
||||||
|
final class SessionIntentController {
|
||||||
|
|
||||||
|
private let dataManager: ClimbingDataManager
|
||||||
|
|
||||||
|
init(dataManager: ClimbingDataManager = .shared) {
|
||||||
|
self.dataManager = dataManager
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a new session using the most recently visited gym.
|
||||||
|
func startSessionWithLastUsedGym() async throws -> SessionIntentSummary {
|
||||||
|
// Wait for data to load
|
||||||
|
if dataManager.gyms.isEmpty {
|
||||||
|
try? await Task.sleep(nanoseconds: 500_000_000)
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let lastGym = dataManager.getLastUsedGym() else {
|
||||||
|
logFailure(.noRecentGym, context: "No recorded sessions available")
|
||||||
|
throw SessionIntentError.noRecentGym
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let startedSession = await dataManager.startSessionAsync(gymId: lastGym.id) else {
|
||||||
|
logFailure(.failedToStartSession, context: "Data manager failed to create new session")
|
||||||
|
throw SessionIntentError.failedToStartSession
|
||||||
|
}
|
||||||
|
|
||||||
|
return SessionIntentSummary(
|
||||||
|
sessionId: startedSession.id,
|
||||||
|
gymName: lastGym.name,
|
||||||
|
status: startedSession.status
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends the currently active climbing session, if one exists.
|
||||||
|
func endActiveSession() async throws -> SessionIntentSummary {
|
||||||
|
guard let activeSession = dataManager.activeSession else {
|
||||||
|
logFailure(.noActiveSession, context: "No active session stored in data manager")
|
||||||
|
throw SessionIntentError.noActiveSession
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let completedSession = await dataManager.endSessionAsync(activeSession.id) else {
|
||||||
|
logFailure(
|
||||||
|
.failedToEndSession, context: "Data manager failed to complete active session")
|
||||||
|
throw SessionIntentError.failedToEndSession
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let gym = dataManager.gym(withId: completedSession.gymId) else {
|
||||||
|
logFailure(
|
||||||
|
.failedToEndSession,
|
||||||
|
context: "Gym missing for completed session \(completedSession.id)")
|
||||||
|
throw SessionIntentError.failedToEndSession
|
||||||
|
}
|
||||||
|
|
||||||
|
return SessionIntentSummary(
|
||||||
|
sessionId: completedSession.id,
|
||||||
|
gymName: gym.name,
|
||||||
|
status: completedSession.status
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func logFailure(_ error: SessionIntentError, context: String) {
|
||||||
|
// Log error for debugging
|
||||||
|
print("SessionIntentError: \(error). Context: \(context)")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggles the session state: ends active session if one exists, otherwise starts a new one.
|
||||||
|
func toggleSession() async throws -> (summary: SessionIntentSummary, wasStarted: Bool) {
|
||||||
|
// Wait for data to load
|
||||||
|
if dataManager.gyms.isEmpty {
|
||||||
|
try? await Task.sleep(nanoseconds: 500_000_000)
|
||||||
|
}
|
||||||
|
|
||||||
|
if dataManager.activeSession != nil {
|
||||||
|
let summary = try await endActiveSession()
|
||||||
|
return (summary, false)
|
||||||
|
} else {
|
||||||
|
let summary = try await startSessionWithLastUsedGym()
|
||||||
|
return (summary, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
40
ios/Ascently/AppIntents/ToggleSessionIntent.swift
Normal file
40
ios/Ascently/AppIntents/ToggleSessionIntent.swift
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import AppIntents
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Toggles the climbing session state: starts a session if none is active, or ends the current one.
|
||||||
|
struct ToggleSessionIntent: AppIntent {
|
||||||
|
|
||||||
|
static var title: LocalizedStringResource {
|
||||||
|
"Toggle Climbing Session"
|
||||||
|
}
|
||||||
|
|
||||||
|
static var description: IntentDescription {
|
||||||
|
IntentDescription(
|
||||||
|
"Starts a new session at your last gym if you're not climbing, or ends your current session if you are."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
static var openAppWhenRun: Bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
func perform() async throws -> some IntentResult & ProvidesDialog {
|
||||||
|
// Wait for app initialization
|
||||||
|
try? await Task.sleep(nanoseconds: 1_000_000_000)
|
||||||
|
|
||||||
|
let controller = await SessionIntentController()
|
||||||
|
let (summary, wasStarted) = try await controller.toggleSession()
|
||||||
|
|
||||||
|
if wasStarted {
|
||||||
|
// Wait for Live Activity
|
||||||
|
try? await Task.sleep(nanoseconds: 500_000_000)
|
||||||
|
return .result(dialog: IntentDialog("Session started at \(summary.gymName). Have an awesome climb!"))
|
||||||
|
} else {
|
||||||
|
return .result(dialog: IntentDialog("Session at \(summary.gymName) ended. Nice work!"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static var parameterSummary: some ParameterSummary {
|
||||||
|
Summary("Toggle my climbing session")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,25 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
|
class AppDelegate: NSObject, UIApplicationDelegate {
|
||||||
|
func application(
|
||||||
|
_ application: UIApplication,
|
||||||
|
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
|
||||||
|
) -> Bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@main
|
@main
|
||||||
struct AscentlyApp: App {
|
struct AscentlyApp: App {
|
||||||
|
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
|
||||||
|
@Environment(\.scenePhase) private var scenePhase
|
||||||
|
@StateObject private var themeManager = ThemeManager()
|
||||||
|
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
WindowGroup {
|
WindowGroup {
|
||||||
ContentView()
|
ContentView()
|
||||||
|
.environmentObject(themeManager)
|
||||||
|
.tint(themeManager.accentColor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,52 +1,104 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import UIKit
|
import UIKit
|
||||||
|
|
||||||
|
/// A native iOS camera picker presented from a hosting controller so it can
|
||||||
|
/// respect all supported interface orientations. Present with `.fullScreenCover()`.
|
||||||
struct CameraImagePicker: UIViewControllerRepresentable {
|
struct CameraImagePicker: UIViewControllerRepresentable {
|
||||||
@Binding var isPresented: Bool
|
@Environment(\.dismiss) private var dismiss
|
||||||
let onImageCaptured: (UIImage) -> Void
|
let onImageCaptured: (UIImage) -> Void
|
||||||
|
|
||||||
func makeUIViewController(context: Context) -> UIImagePickerController {
|
func makeUIViewController(context: Context) -> CameraHostViewController {
|
||||||
let picker = UIImagePickerController()
|
let host = CameraHostViewController()
|
||||||
picker.delegate = context.coordinator
|
host.onImageCaptured = { image in
|
||||||
picker.sourceType = .camera
|
onImageCaptured(image)
|
||||||
picker.cameraCaptureMode = .photo
|
dismiss()
|
||||||
picker.cameraDevice = .rear
|
}
|
||||||
picker.allowsEditing = false
|
host.onCancel = {
|
||||||
return picker
|
dismiss()
|
||||||
|
}
|
||||||
|
host.pickerDelegate = context.coordinator
|
||||||
|
context.coordinator.onImageCaptured = { image in
|
||||||
|
onImageCaptured(image)
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
context.coordinator.onCancel = {
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
return host
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
|
func updateUIViewController(_ uiViewController: CameraHostViewController, context: Context) {
|
||||||
// Nothing here actually... Q_Q
|
// No dynamic updates needed
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeCoordinator() -> Coordinator {
|
func makeCoordinator() -> Coordinator {
|
||||||
Coordinator(self)
|
Coordinator()
|
||||||
}
|
}
|
||||||
|
|
||||||
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
|
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
|
||||||
let parent: CameraImagePicker
|
var onImageCaptured: ((UIImage) -> Void)?
|
||||||
|
var onCancel: (() -> Void)?
|
||||||
init(_ parent: CameraImagePicker) {
|
|
||||||
self.parent = parent
|
|
||||||
}
|
|
||||||
|
|
||||||
func imagePickerController(
|
func imagePickerController(
|
||||||
_ picker: UIImagePickerController,
|
_ picker: UIImagePickerController,
|
||||||
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
|
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
|
||||||
) {
|
) {
|
||||||
|
picker.dismiss(animated: true) {
|
||||||
if let image = info[.originalImage] as? UIImage {
|
if let image = info[.originalImage] as? UIImage {
|
||||||
parent.onImageCaptured(image)
|
self.onImageCaptured?(image)
|
||||||
|
} else {
|
||||||
|
self.onCancel?()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
parent.isPresented = false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
|
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
|
||||||
parent.isPresented = false
|
picker.dismiss(animated: true) {
|
||||||
|
self.onCancel?()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extension to check camera availability
|
// MARK: - Hosting VC to own presentation/orientation
|
||||||
|
final class CameraHostViewController: UIViewController {
|
||||||
|
var onImageCaptured: ((UIImage) -> Void)?
|
||||||
|
var onCancel: (() -> Void)?
|
||||||
|
weak var pickerDelegate: (UIImagePickerControllerDelegate & UINavigationControllerDelegate)?
|
||||||
|
|
||||||
|
private var didPresent = false
|
||||||
|
|
||||||
|
override func viewDidAppear(_ animated: Bool) {
|
||||||
|
super.viewDidAppear(animated)
|
||||||
|
presentIfNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func presentIfNeeded() {
|
||||||
|
guard !didPresent, UIImagePickerController.isSourceTypeAvailable(.camera) else { return }
|
||||||
|
didPresent = true
|
||||||
|
|
||||||
|
let picker = UIImagePickerController()
|
||||||
|
picker.delegate = pickerDelegate
|
||||||
|
picker.sourceType = .camera
|
||||||
|
picker.cameraCaptureMode = .photo
|
||||||
|
picker.cameraDevice = .rear
|
||||||
|
picker.allowsEditing = false
|
||||||
|
picker.modalPresentationStyle = .fullScreen
|
||||||
|
|
||||||
|
present(picker, animated: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
|
||||||
|
// Defer to app-supported orientations; returning .all allows rotation when permitted by the app
|
||||||
|
return .all
|
||||||
|
}
|
||||||
|
|
||||||
|
override var shouldAutorotate: Bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Camera Availability Check
|
||||||
extension CameraImagePicker {
|
extension CameraImagePicker {
|
||||||
static var isCameraAvailable: Bool {
|
static var isCameraAvailable: Bool {
|
||||||
UIImagePickerController.isSourceTypeAvailable(.camera)
|
UIImagePickerController.isSourceTypeAvailable(.camera)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ struct PhotoOptionSheet: View {
|
|||||||
let onCameraSelected: () -> Void
|
let onCameraSelected: () -> Void
|
||||||
let onPhotoLibrarySelected: () -> Void
|
let onPhotoLibrarySelected: () -> Void
|
||||||
let onDismiss: () -> Void
|
let onDismiss: () -> Void
|
||||||
|
@EnvironmentObject var themeManager: ThemeManager
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
NavigationView {
|
NavigationView {
|
||||||
@@ -29,7 +30,7 @@ struct PhotoOptionSheet: View {
|
|||||||
HStack {
|
HStack {
|
||||||
Image(systemName: "photo.on.rectangle")
|
Image(systemName: "photo.on.rectangle")
|
||||||
.font(.title2)
|
.font(.title2)
|
||||||
.foregroundColor(.blue)
|
.foregroundColor(themeManager.accentColor)
|
||||||
Text("Photo Library")
|
Text("Photo Library")
|
||||||
.font(.headline)
|
.font(.headline)
|
||||||
Spacer()
|
Spacer()
|
||||||
@@ -52,7 +53,7 @@ struct PhotoOptionSheet: View {
|
|||||||
HStack {
|
HStack {
|
||||||
Image(systemName: "camera.fill")
|
Image(systemName: "camera.fill")
|
||||||
.font(.title2)
|
.font(.title2)
|
||||||
.foregroundColor(.blue)
|
.foregroundColor(themeManager.accentColor)
|
||||||
Text("Camera")
|
Text("Camera")
|
||||||
.font(.headline)
|
.font(.headline)
|
||||||
Spacer()
|
Spacer()
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
struct ContentView: View {
|
struct ContentView: View {
|
||||||
@StateObject private var dataManager = ClimbingDataManager()
|
@StateObject private var dataManager = ClimbingDataManager.shared
|
||||||
@State private var selectedTab = 0
|
@State private var selectedTab = 0
|
||||||
@Environment(\.scenePhase) private var scenePhase
|
@Environment(\.scenePhase) private var scenePhase
|
||||||
@State private var notificationObservers: [NSObjectProtocol] = []
|
@State private var notificationObservers: [NSObjectProtocol] = []
|
||||||
@@ -44,7 +44,8 @@ struct ContentView: View {
|
|||||||
.tag(4)
|
.tag(4)
|
||||||
}
|
}
|
||||||
.environmentObject(dataManager)
|
.environmentObject(dataManager)
|
||||||
.onChange(of: scenePhase) { oldPhase, newPhase in
|
.environmentObject(MusicService.shared)
|
||||||
|
.onChange(of: scenePhase) { _, newPhase in
|
||||||
if newPhase == .active {
|
if newPhase == .active {
|
||||||
// Add slight delay to ensure app is fully loaded
|
// Add slight delay to ensure app is fully loaded
|
||||||
Task {
|
Task {
|
||||||
@@ -91,11 +92,12 @@ struct ContentView: View {
|
|||||||
object: nil,
|
object: nil,
|
||||||
queue: .main
|
queue: .main
|
||||||
) { _ in
|
) { _ in
|
||||||
print("App will enter foreground - preparing Live Activity check")
|
Task { @MainActor in
|
||||||
Task {
|
AppLogger.info(
|
||||||
|
"App will enter foreground - preparing Live Activity check", tag: "Lifecycle")
|
||||||
// Small delay to ensure app is fully active
|
// Small delay to ensure app is fully active
|
||||||
try? await Task.sleep(nanoseconds: 800_000_000) // 0.8 seconds
|
try? await Task.sleep(nanoseconds: 800_000_000) // 0.8 seconds
|
||||||
await dataManager.onAppBecomeActive()
|
dataManager.onAppBecomeActive()
|
||||||
// Re-verify health integration when returning from background
|
// Re-verify health integration when returning from background
|
||||||
await dataManager.healthKitService.verifyAndRestoreIntegration()
|
await dataManager.healthKitService.verifyAndRestoreIntegration()
|
||||||
}
|
}
|
||||||
@@ -107,10 +109,11 @@ struct ContentView: View {
|
|||||||
object: nil,
|
object: nil,
|
||||||
queue: .main
|
queue: .main
|
||||||
) { _ in
|
) { _ in
|
||||||
print("App did become active - checking Live Activity status")
|
Task { @MainActor in
|
||||||
Task {
|
AppLogger.info(
|
||||||
|
"App did become active - checking Live Activity status", tag: "Lifecycle")
|
||||||
try? await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds
|
try? await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds
|
||||||
await dataManager.onAppBecomeActive()
|
dataManager.onAppBecomeActive()
|
||||||
await dataManager.healthKitService.verifyAndRestoreIntegration()
|
await dataManager.healthKitService.verifyAndRestoreIntegration()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
<true/>
|
<true/>
|
||||||
<key>NSSupportsLiveActivities</key>
|
<key>NSSupportsLiveActivities</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
|
||||||
<key>NSPhotoLibraryUsageDescription</key>
|
<key>NSPhotoLibraryUsageDescription</key>
|
||||||
<string>This app needs access to your photo library to add photos to climbing problems.</string>
|
<string>This app needs access to your photo library to add photos to climbing problems.</string>
|
||||||
<key>NSCameraUsageDescription</key>
|
<key>NSCameraUsageDescription</key>
|
||||||
@@ -14,5 +15,7 @@
|
|||||||
<string>This app needs access to save your climbing workouts to Apple Health.</string>
|
<string>This app needs access to save your climbing workouts to Apple Health.</string>
|
||||||
<key>NSHealthUpdateUsageDescription</key>
|
<key>NSHealthUpdateUsageDescription</key>
|
||||||
<string>This app needs access to save your climbing workouts to Apple Health.</string>
|
<string>This app needs access to save your climbing workouts to Apple Health.</string>
|
||||||
|
<key>NSAppleMusicUsageDescription</key>
|
||||||
|
<string>This app (optionally) needs access to your music library to play your selected playlist during climbing sessions.</string>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ class HealthKitService: ObservableObject {
|
|||||||
{
|
{
|
||||||
currentWorkoutStartDate = startDate
|
currentWorkoutStartDate = startDate
|
||||||
currentWorkoutSessionId = sessionId
|
currentWorkoutSessionId = sessionId
|
||||||
print("HealthKit: Restored active workout from \(startDate)")
|
AppLogger.info("HealthKit: Restored active workout from \(startDate)", tag: "HealthKit")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,31 +56,34 @@ class HealthKitService: ObservableObject {
|
|||||||
guard isEnabled else { return }
|
guard isEnabled else { return }
|
||||||
|
|
||||||
guard HKHealthStore.isHealthDataAvailable() else {
|
guard HKHealthStore.isHealthDataAvailable() else {
|
||||||
print("HealthKit: Device does not support HealthKit")
|
AppLogger.warning("HealthKit: Device does not support HealthKit", tag: "HealthKit")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
checkAuthorization()
|
checkAuthorization()
|
||||||
|
|
||||||
if !isAuthorized {
|
if !isAuthorized {
|
||||||
print(
|
AppLogger.warning(
|
||||||
"HealthKit: Integration was enabled but authorization lost, attempting to restore..."
|
"HealthKit: Integration was enabled but authorization lost, attempting to restore...",
|
||||||
)
|
tag: "HealthKit")
|
||||||
|
|
||||||
do {
|
do {
|
||||||
try await requestAuthorization()
|
try await requestAuthorization()
|
||||||
print("HealthKit: Authorization restored successfully")
|
AppLogger.info("HealthKit: Authorization restored successfully", tag: "HealthKit")
|
||||||
} catch {
|
} catch {
|
||||||
print("HealthKit: Failed to restore authorization: \(error.localizedDescription)")
|
AppLogger.error(
|
||||||
|
"HealthKit: Failed to restore authorization: \(error.localizedDescription)",
|
||||||
|
tag: "HealthKit")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
print("HealthKit: Integration verified - authorization is valid")
|
AppLogger.info(
|
||||||
|
"HealthKit: Integration verified - authorization is valid", tag: "HealthKit")
|
||||||
}
|
}
|
||||||
|
|
||||||
if hasActiveWorkout() {
|
if hasActiveWorkout() {
|
||||||
print(
|
AppLogger.info(
|
||||||
"HealthKit: Active workout restored - started at \(currentWorkoutStartDate!)"
|
"HealthKit: Active workout restored - started at \(currentWorkoutStartDate!)",
|
||||||
)
|
tag: "HealthKit")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +133,7 @@ class HealthKitService: ObservableObject {
|
|||||||
currentWorkoutStartDate = startDate
|
currentWorkoutStartDate = startDate
|
||||||
currentWorkoutSessionId = sessionId
|
currentWorkoutSessionId = sessionId
|
||||||
persistActiveWorkout()
|
persistActiveWorkout()
|
||||||
print("HealthKit: Started workout for session \(sessionId)")
|
AppLogger.info("HealthKit: Started workout for session \(sessionId)", tag: "HealthKit")
|
||||||
}
|
}
|
||||||
|
|
||||||
func endWorkout(endDate: Date) async throws {
|
func endWorkout(endDate: Date) async throws {
|
||||||
@@ -178,15 +181,17 @@ class HealthKitService: ObservableObject {
|
|||||||
try await builder.endCollection(at: endDate)
|
try await builder.endCollection(at: endDate)
|
||||||
let workout = try await builder.finishWorkout()
|
let workout = try await builder.finishWorkout()
|
||||||
|
|
||||||
print(
|
AppLogger.info(
|
||||||
"HealthKit: Workout saved successfully with id: \(workout?.uuid.uuidString ?? "unknown")"
|
"HealthKit: Workout saved successfully with id: \(workout?.uuid.uuidString ?? "unknown")",
|
||||||
)
|
tag: "HealthKit")
|
||||||
|
|
||||||
currentWorkoutStartDate = nil
|
currentWorkoutStartDate = nil
|
||||||
currentWorkoutSessionId = nil
|
currentWorkoutSessionId = nil
|
||||||
persistActiveWorkout()
|
persistActiveWorkout()
|
||||||
} catch {
|
} catch {
|
||||||
print("HealthKit: Failed to save workout: \(error.localizedDescription)")
|
AppLogger.error(
|
||||||
|
"HealthKit: Failed to save workout: \(error.localizedDescription)", tag: "HealthKit"
|
||||||
|
)
|
||||||
currentWorkoutStartDate = nil
|
currentWorkoutStartDate = nil
|
||||||
currentWorkoutSessionId = nil
|
currentWorkoutSessionId = nil
|
||||||
persistActiveWorkout()
|
persistActiveWorkout()
|
||||||
@@ -199,7 +204,7 @@ class HealthKitService: ObservableObject {
|
|||||||
currentWorkoutStartDate = nil
|
currentWorkoutStartDate = nil
|
||||||
currentWorkoutSessionId = nil
|
currentWorkoutSessionId = nil
|
||||||
persistActiveWorkout()
|
persistActiveWorkout()
|
||||||
print("HealthKit: Workout cancelled")
|
AppLogger.info("HealthKit: Workout cancelled", tag: "HealthKit")
|
||||||
}
|
}
|
||||||
|
|
||||||
func hasActiveWorkout() -> Bool {
|
func hasActiveWorkout() -> Bool {
|
||||||
|
|||||||
197
ios/Ascently/Services/MusicService.swift
Normal file
197
ios/Ascently/Services/MusicService.swift
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
import AVFoundation
|
||||||
|
import Combine
|
||||||
|
import MusicKit
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
class MusicService: ObservableObject {
|
||||||
|
static let shared = MusicService()
|
||||||
|
|
||||||
|
@Published var isAuthorized = false
|
||||||
|
@Published var playlists: MusicItemCollection<Playlist> = []
|
||||||
|
@Published var selectedPlaylistId: String? {
|
||||||
|
didSet {
|
||||||
|
UserDefaults.standard.set(selectedPlaylistId, forKey: "ascently_selected_playlist_id")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Published var isMusicEnabled: Bool {
|
||||||
|
didSet {
|
||||||
|
UserDefaults.standard.set(isMusicEnabled, forKey: "ascently_music_enabled")
|
||||||
|
if !isMusicEnabled {
|
||||||
|
// Genuinely unsure what I want to do with this but we should account for it at some point
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Published var isAutoPlayEnabled: Bool {
|
||||||
|
didSet {
|
||||||
|
UserDefaults.standard.set(isAutoPlayEnabled, forKey: "ascently_music_autoplay_enabled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Published var isAutoStopEnabled: Bool {
|
||||||
|
didSet {
|
||||||
|
UserDefaults.standard.set(isAutoStopEnabled, forKey: "ascently_music_autostop_enabled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Published var isPlaying = false
|
||||||
|
|
||||||
|
private var cancellables = Set<AnyCancellable>()
|
||||||
|
private var hasStartedSessionPlayback = false
|
||||||
|
private var currentPlaylistTrackIds: Set<MusicItemID> = []
|
||||||
|
|
||||||
|
private init() {
|
||||||
|
self.selectedPlaylistId = UserDefaults.standard.string(forKey: "ascently_selected_playlist_id")
|
||||||
|
self.isMusicEnabled = UserDefaults.standard.bool(forKey: "ascently_music_enabled")
|
||||||
|
self.isAutoPlayEnabled = UserDefaults.standard.bool(forKey: "ascently_music_autoplay_enabled")
|
||||||
|
self.isAutoStopEnabled = UserDefaults.standard.bool(forKey: "ascently_music_autostop_enabled")
|
||||||
|
|
||||||
|
if isMusicEnabled {
|
||||||
|
Task {
|
||||||
|
await checkAuthorizationStatus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setupObservers()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func setupObservers() {
|
||||||
|
SystemMusicPlayer.shared.state.objectWillChange
|
||||||
|
.sink { [weak self] _ in
|
||||||
|
self?.updatePlaybackStatus()
|
||||||
|
}
|
||||||
|
.store(in: &cancellables)
|
||||||
|
|
||||||
|
SystemMusicPlayer.shared.queue.objectWillChange
|
||||||
|
.sink { [weak self] _ in
|
||||||
|
self?.checkQueueConsistency()
|
||||||
|
}
|
||||||
|
.store(in: &cancellables)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func updatePlaybackStatus() {
|
||||||
|
Task { @MainActor [weak self] in
|
||||||
|
self?.isPlaying = SystemMusicPlayer.shared.state.playbackStatus == .playing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func checkQueueConsistency() {
|
||||||
|
guard hasStartedSessionPlayback else { return }
|
||||||
|
|
||||||
|
Task { @MainActor [weak self] in
|
||||||
|
guard let self = self else { return }
|
||||||
|
if let currentEntry = SystemMusicPlayer.shared.queue.currentEntry,
|
||||||
|
let item = currentEntry.item {
|
||||||
|
if !self.currentPlaylistTrackIds.isEmpty && !self.currentPlaylistTrackIds.contains(item.id) {
|
||||||
|
self.hasStartedSessionPlayback = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func toggleMusicEnabled(_ enabled: Bool) {
|
||||||
|
isMusicEnabled = enabled
|
||||||
|
if enabled {
|
||||||
|
Task {
|
||||||
|
await checkAuthorizationStatus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAuthorizationStatus() async {
|
||||||
|
let status = await MusicAuthorization.request()
|
||||||
|
self.isAuthorized = status == .authorized
|
||||||
|
if isAuthorized {
|
||||||
|
await fetchPlaylists()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchPlaylists() async {
|
||||||
|
guard isAuthorized else { return }
|
||||||
|
do {
|
||||||
|
var request = MusicLibraryRequest<Playlist>()
|
||||||
|
request.sort(by: \.name, ascending: true)
|
||||||
|
let response = try await request.response()
|
||||||
|
self.playlists = response.items
|
||||||
|
} catch {
|
||||||
|
print("Error fetching playlists: \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func playSelectedPlaylistIfHeadphonesConnected() {
|
||||||
|
guard isMusicEnabled, isAutoPlayEnabled, let playlistId = selectedPlaylistId else { return }
|
||||||
|
|
||||||
|
if isHeadphonesConnected() {
|
||||||
|
playPlaylist(id: playlistId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetSessionPlaybackState() {
|
||||||
|
hasStartedSessionPlayback = false
|
||||||
|
currentPlaylistTrackIds.removeAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
func playPlaylist(id: String) {
|
||||||
|
print("Attempting to play playlist \(id)")
|
||||||
|
Task {
|
||||||
|
do {
|
||||||
|
if playlists.isEmpty {
|
||||||
|
await fetchPlaylists()
|
||||||
|
}
|
||||||
|
|
||||||
|
var targetPlaylist: Playlist?
|
||||||
|
|
||||||
|
if let playlist = playlists.first(where: { $0.id.rawValue == id }) {
|
||||||
|
targetPlaylist = playlist
|
||||||
|
} else {
|
||||||
|
var request = MusicLibraryRequest<Playlist>()
|
||||||
|
request.filter(matching: \.id, equalTo: MusicItemID(id))
|
||||||
|
let response = try await request.response()
|
||||||
|
targetPlaylist = response.items.first
|
||||||
|
}
|
||||||
|
|
||||||
|
if let playlist = targetPlaylist {
|
||||||
|
let detailedPlaylist = try await playlist.with([.tracks])
|
||||||
|
if let tracks = detailedPlaylist.tracks {
|
||||||
|
self.currentPlaylistTrackIds = Set(tracks.map { $0.id })
|
||||||
|
}
|
||||||
|
|
||||||
|
SystemMusicPlayer.shared.queue = [playlist]
|
||||||
|
try await SystemMusicPlayer.shared.play()
|
||||||
|
hasStartedSessionPlayback = true
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
print("Error playing playlist: \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopPlaybackIfEnabled() {
|
||||||
|
guard isMusicEnabled, isAutoStopEnabled else { return }
|
||||||
|
SystemMusicPlayer.shared.stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
func togglePlayback() {
|
||||||
|
Task {
|
||||||
|
if isPlaying {
|
||||||
|
SystemMusicPlayer.shared.pause()
|
||||||
|
} else {
|
||||||
|
if let playlistId = selectedPlaylistId, !hasStartedSessionPlayback {
|
||||||
|
playPlaylist(id: playlistId)
|
||||||
|
} else {
|
||||||
|
try? await SystemMusicPlayer.shared.play()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func isHeadphonesConnected() -> Bool {
|
||||||
|
let route = AVAudioSession.sharedInstance().currentRoute
|
||||||
|
return route.outputs.contains { port in
|
||||||
|
port.portType == .headphones ||
|
||||||
|
port.portType == .bluetoothA2DP ||
|
||||||
|
port.portType == .bluetoothLE ||
|
||||||
|
port.portType == .bluetoothHFP ||
|
||||||
|
port.portType == .usbAudio ||
|
||||||
|
port.portType == .airPlay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
1186
ios/Ascently/Services/Sync/ServerSyncProvider.swift
Normal file
1186
ios/Ascently/Services/Sync/ServerSyncProvider.swift
Normal file
File diff suppressed because it is too large
Load Diff
179
ios/Ascently/Services/Sync/SyncMerger.swift
Normal file
179
ios/Ascently/Services/Sync/SyncMerger.swift
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct SyncMerger {
|
||||||
|
private static let logTag = "SyncMerger"
|
||||||
|
|
||||||
|
static func mergeDataSafely(
|
||||||
|
localBackup: ClimbDataBackup,
|
||||||
|
serverBackup: ClimbDataBackup,
|
||||||
|
dataManager: ClimbingDataManager,
|
||||||
|
imagePathMapping: [String: String]
|
||||||
|
) throws -> (gyms: [Gym], problems: [Problem], sessions: [ClimbSession], attempts: [Attempt], uniqueDeletions: [DeletedItem]) {
|
||||||
|
|
||||||
|
// Merge deletion lists first to prevent resurrection of deleted items
|
||||||
|
let localDeletions = dataManager.getDeletedItems()
|
||||||
|
let allDeletions = localDeletions + serverBackup.deletedItems
|
||||||
|
let uniqueDeletions = Array(Set(allDeletions))
|
||||||
|
|
||||||
|
AppLogger.info("Merging gyms...", tag: logTag)
|
||||||
|
let mergedGyms = mergeGyms(
|
||||||
|
local: dataManager.gyms,
|
||||||
|
server: serverBackup.gyms,
|
||||||
|
deletedItems: uniqueDeletions)
|
||||||
|
|
||||||
|
AppLogger.info("Merging problems...", tag: logTag)
|
||||||
|
let mergedProblems = try mergeProblems(
|
||||||
|
local: dataManager.problems,
|
||||||
|
server: serverBackup.problems,
|
||||||
|
imagePathMapping: imagePathMapping,
|
||||||
|
deletedItems: uniqueDeletions)
|
||||||
|
|
||||||
|
AppLogger.info("Merging sessions...", tag: logTag)
|
||||||
|
let mergedSessions = try mergeSessions(
|
||||||
|
local: dataManager.sessions,
|
||||||
|
server: serverBackup.sessions,
|
||||||
|
deletedItems: uniqueDeletions)
|
||||||
|
|
||||||
|
AppLogger.info("Merging attempts...", tag: logTag)
|
||||||
|
let mergedAttempts = try mergeAttempts(
|
||||||
|
local: dataManager.attempts,
|
||||||
|
server: serverBackup.attempts,
|
||||||
|
deletedItems: uniqueDeletions)
|
||||||
|
|
||||||
|
return (mergedGyms, mergedProblems, mergedSessions, mergedAttempts, uniqueDeletions)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func mergeGyms(local: [Gym], server: [BackupGym], deletedItems: [DeletedItem]) -> [Gym] {
|
||||||
|
var merged = local
|
||||||
|
let deletedGymIds = Set(deletedItems.filter { $0.type == "gym" }.map { $0.id })
|
||||||
|
let localGymIds = Set(local.map { $0.id.uuidString })
|
||||||
|
|
||||||
|
merged.removeAll { deletedGymIds.contains($0.id.uuidString) }
|
||||||
|
|
||||||
|
// Add new items from server (excluding deleted ones)
|
||||||
|
for serverGym in server {
|
||||||
|
if let serverGymConverted = try? serverGym.toGym() {
|
||||||
|
let localHasGym = localGymIds.contains(serverGym.id)
|
||||||
|
let isDeleted = deletedGymIds.contains(serverGym.id)
|
||||||
|
|
||||||
|
if !localHasGym && !isDeleted {
|
||||||
|
merged.append(serverGymConverted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func mergeProblems(
|
||||||
|
local: [Problem],
|
||||||
|
server: [BackupProblem],
|
||||||
|
imagePathMapping: [String: String],
|
||||||
|
deletedItems: [DeletedItem]
|
||||||
|
) throws -> [Problem] {
|
||||||
|
var merged = local
|
||||||
|
let deletedProblemIds = Set(deletedItems.filter { $0.type == "problem" }.map { $0.id })
|
||||||
|
let localProblemIds = Set(local.map { $0.id.uuidString })
|
||||||
|
|
||||||
|
merged.removeAll { deletedProblemIds.contains($0.id.uuidString) }
|
||||||
|
|
||||||
|
for serverProblem in server {
|
||||||
|
let localHasProblem = localProblemIds.contains(serverProblem.id)
|
||||||
|
let isDeleted = deletedProblemIds.contains(serverProblem.id)
|
||||||
|
|
||||||
|
if !localHasProblem && !isDeleted {
|
||||||
|
var problemToAdd = serverProblem
|
||||||
|
|
||||||
|
if !imagePathMapping.isEmpty, let imagePaths = serverProblem.imagePaths, !imagePaths.isEmpty {
|
||||||
|
let updatedImagePaths = imagePaths.compactMap { oldPath in
|
||||||
|
imagePathMapping[oldPath] ?? oldPath
|
||||||
|
}
|
||||||
|
if updatedImagePaths != imagePaths {
|
||||||
|
problemToAdd = BackupProblem(
|
||||||
|
id: serverProblem.id,
|
||||||
|
gymId: serverProblem.gymId,
|
||||||
|
name: serverProblem.name,
|
||||||
|
description: serverProblem.description,
|
||||||
|
climbType: serverProblem.climbType,
|
||||||
|
difficulty: serverProblem.difficulty,
|
||||||
|
tags: serverProblem.tags,
|
||||||
|
location: serverProblem.location,
|
||||||
|
imagePaths: updatedImagePaths,
|
||||||
|
isActive: serverProblem.isActive,
|
||||||
|
dateSet: serverProblem.dateSet,
|
||||||
|
notes: serverProblem.notes,
|
||||||
|
createdAt: serverProblem.createdAt,
|
||||||
|
updatedAt: serverProblem.updatedAt
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let serverProblemConverted = try? problemToAdd.toProblem() {
|
||||||
|
merged.append(serverProblemConverted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func mergeSessions(
|
||||||
|
local: [ClimbSession], server: [BackupClimbSession], deletedItems: [DeletedItem]
|
||||||
|
) throws -> [ClimbSession] {
|
||||||
|
var merged = local
|
||||||
|
let deletedSessionIds = Set(deletedItems.filter { $0.type == "session" }.map { $0.id })
|
||||||
|
let localSessionIds = Set(local.map { $0.id.uuidString })
|
||||||
|
|
||||||
|
merged.removeAll { session in
|
||||||
|
deletedSessionIds.contains(session.id.uuidString) && session.status != .active
|
||||||
|
}
|
||||||
|
|
||||||
|
for serverSession in server {
|
||||||
|
let localHasSession = localSessionIds.contains(serverSession.id)
|
||||||
|
let isDeleted = deletedSessionIds.contains(serverSession.id)
|
||||||
|
|
||||||
|
if !localHasSession && !isDeleted {
|
||||||
|
if let serverSessionConverted = try? serverSession.toClimbSession() {
|
||||||
|
merged.append(serverSessionConverted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func mergeAttempts(
|
||||||
|
local: [Attempt], server: [BackupAttempt], deletedItems: [DeletedItem]
|
||||||
|
) throws -> [Attempt] {
|
||||||
|
var merged = local
|
||||||
|
let deletedAttemptIds = Set(deletedItems.filter { $0.type == "attempt" }.map { $0.id })
|
||||||
|
let localAttemptIds = Set(local.map { $0.id.uuidString })
|
||||||
|
|
||||||
|
// Get active session IDs to protect their attempts
|
||||||
|
let activeSessionIds = Set(
|
||||||
|
local.compactMap { attempt in
|
||||||
|
return attempt.sessionId
|
||||||
|
}.filter { _ in
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
// Remove items that were deleted on other devices (but be conservative with attempts)
|
||||||
|
merged.removeAll { attempt in
|
||||||
|
deletedAttemptIds.contains(attempt.id.uuidString)
|
||||||
|
&& !activeSessionIds.contains(attempt.sessionId)
|
||||||
|
}
|
||||||
|
|
||||||
|
for serverAttempt in server {
|
||||||
|
let localHasAttempt = localAttemptIds.contains(serverAttempt.id)
|
||||||
|
let isDeleted = deletedAttemptIds.contains(serverAttempt.id)
|
||||||
|
|
||||||
|
if !localHasAttempt && !isDeleted {
|
||||||
|
if let serverAttemptConverted = try? serverAttempt.toAttempt() {
|
||||||
|
merged.append(serverAttemptConverted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged
|
||||||
|
}
|
||||||
|
}
|
||||||
73
ios/Ascently/Services/Sync/SyncProvider.swift
Normal file
73
ios/Ascently/Services/Sync/SyncProvider.swift
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
enum SyncProviderType: String, CaseIterable, Identifiable {
|
||||||
|
case none
|
||||||
|
case server
|
||||||
|
case iCloud
|
||||||
|
|
||||||
|
var id: String { rawValue }
|
||||||
|
var displayName: String {
|
||||||
|
switch self {
|
||||||
|
case .none: return "None"
|
||||||
|
case .server: return "Self-Hosted Server"
|
||||||
|
case .iCloud: return "iCloud"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protocol SyncProvider {
|
||||||
|
var type: SyncProviderType { get }
|
||||||
|
var isConfigured: Bool { get }
|
||||||
|
var isConnected: Bool { get }
|
||||||
|
|
||||||
|
func sync(dataManager: ClimbingDataManager) async throws
|
||||||
|
func testConnection() async throws
|
||||||
|
func disconnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SyncError: LocalizedError {
|
||||||
|
case notConfigured
|
||||||
|
case notConnected
|
||||||
|
case invalidURL
|
||||||
|
case invalidResponse
|
||||||
|
case unauthorized
|
||||||
|
case badRequest
|
||||||
|
case serverError(Int)
|
||||||
|
case decodingError(Error)
|
||||||
|
case exportFailed
|
||||||
|
case importFailed(Error)
|
||||||
|
case imageNotFound
|
||||||
|
case imageUploadFailed
|
||||||
|
case providerError(String)
|
||||||
|
|
||||||
|
var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .notConfigured:
|
||||||
|
return "Sync server not configured. Please set server URL and auth token."
|
||||||
|
case .notConnected:
|
||||||
|
return "Not connected to sync server. Please test connection first."
|
||||||
|
case .invalidURL:
|
||||||
|
return "Invalid server URL."
|
||||||
|
case .invalidResponse:
|
||||||
|
return "Invalid response from server."
|
||||||
|
case .unauthorized:
|
||||||
|
return "Authentication failed. Check your auth token."
|
||||||
|
case .badRequest:
|
||||||
|
return "Bad request. Check your data format."
|
||||||
|
case .serverError(let code):
|
||||||
|
return "Server error (code \(code))."
|
||||||
|
case .decodingError(let error):
|
||||||
|
return "Failed to decode response: \(error.localizedDescription)"
|
||||||
|
case .exportFailed:
|
||||||
|
return "Failed to export local data."
|
||||||
|
case .importFailed(let error):
|
||||||
|
return "Failed to import data: \(error.localizedDescription)"
|
||||||
|
case .imageNotFound:
|
||||||
|
return "Image not found on server."
|
||||||
|
case .imageUploadFailed:
|
||||||
|
return "Failed to upload image to server."
|
||||||
|
case .providerError(let message):
|
||||||
|
return "Sync provider error: \(message)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
46
ios/Ascently/Utils/AppLogger.swift
Normal file
46
ios/Ascently/Utils/AppLogger.swift
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Centralized logging utility for the iOS app.
|
||||||
|
///
|
||||||
|
/// All log output is automatically compiled out in non-debug builds to avoid leaking
|
||||||
|
/// sensitive information. Use this instead of calling `print` directly.
|
||||||
|
enum AppLogger {
|
||||||
|
|
||||||
|
enum LogLevel: String {
|
||||||
|
case debug = "DEBUG"
|
||||||
|
case info = "INFO"
|
||||||
|
case warning = "WARN"
|
||||||
|
case error = "ERROR"
|
||||||
|
}
|
||||||
|
|
||||||
|
static func debug(_ message: @autoclosure () -> String, tag: String = #fileID) {
|
||||||
|
log(level: .debug, tag: tag, message: message())
|
||||||
|
}
|
||||||
|
|
||||||
|
static func info(_ message: @autoclosure () -> String, tag: String = #fileID) {
|
||||||
|
log(level: .info, tag: tag, message: message())
|
||||||
|
}
|
||||||
|
|
||||||
|
static func warning(_ message: @autoclosure () -> String, tag: String = #fileID) {
|
||||||
|
log(level: .warning, tag: tag, message: message())
|
||||||
|
}
|
||||||
|
|
||||||
|
static func error(_ message: @autoclosure () -> String, tag: String = #fileID) {
|
||||||
|
log(level: .error, tag: tag, message: message())
|
||||||
|
}
|
||||||
|
|
||||||
|
static func log(level: LogLevel, tag: String, message: @autoclosure () -> String) {
|
||||||
|
#if DEBUG
|
||||||
|
let lastPath = (tag as NSString).lastPathComponent
|
||||||
|
let resolvedTag = lastPath.isEmpty ? tag : lastPath
|
||||||
|
Swift.print("[\(level.rawValue)][\(resolvedTag)] \(message())")
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum LogTag {
|
||||||
|
static let climbingData = "ClimbingData"
|
||||||
|
static let dataManagement = "DataManagementSection"
|
||||||
|
static let exportData = "ExportDataView"
|
||||||
|
static let syncSection = "SyncSection"
|
||||||
|
}
|
||||||
@@ -18,14 +18,17 @@ class DataStateManager {
|
|||||||
private init() {
|
private init() {
|
||||||
// Initialize with current timestamp if this is the first time
|
// Initialize with current timestamp if this is the first time
|
||||||
if !isInitialized() {
|
if !isInitialized() {
|
||||||
print("DataStateManager: First time initialization")
|
AppLogger.info("DataStateManager: First time initialization", tag: "DataState")
|
||||||
// Set initial timestamp to a very old date so server data will be considered newer
|
// Set initial timestamp to a very old date so server data will be considered newer
|
||||||
let epochTime = "1970-01-01T00:00:00.000Z"
|
let epochTime = "1970-01-01T00:00:00.000Z"
|
||||||
userDefaults.set(epochTime, forKey: Keys.lastModified)
|
userDefaults.set(epochTime, forKey: Keys.lastModified)
|
||||||
markAsInitialized()
|
markAsInitialized()
|
||||||
print("DataStateManager initialized with epoch timestamp: \(epochTime)")
|
AppLogger.info(
|
||||||
|
"DataStateManager initialized with epoch timestamp: \(epochTime)", tag: "DataState")
|
||||||
} else {
|
} else {
|
||||||
print("DataStateManager: Already initialized, current timestamp: \(getLastModified())")
|
AppLogger.info(
|
||||||
|
"DataStateManager: Already initialized, current timestamp: \(getLastModified())",
|
||||||
|
tag: "DataState")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,29 +37,32 @@ class DataStateManager {
|
|||||||
func updateDataState() {
|
func updateDataState() {
|
||||||
let now = ISO8601DateFormatter().string(from: Date())
|
let now = ISO8601DateFormatter().string(from: Date())
|
||||||
userDefaults.set(now, forKey: Keys.lastModified)
|
userDefaults.set(now, forKey: Keys.lastModified)
|
||||||
print("iOS Data state updated to: \(now)")
|
AppLogger.info("iOS Data state updated to: \(now)", tag: "DataState")
|
||||||
}
|
}
|
||||||
|
|
||||||
func getLastModified() -> String {
|
func getLastModified() -> String {
|
||||||
if let storedTimestamp = userDefaults.string(forKey: Keys.lastModified) {
|
if let storedTimestamp = userDefaults.string(forKey: Keys.lastModified) {
|
||||||
print("iOS DataStateManager returning stored timestamp: \(storedTimestamp)")
|
AppLogger.debug(
|
||||||
|
"iOS DataStateManager returning stored timestamp: \(storedTimestamp)",
|
||||||
|
tag: "DataState")
|
||||||
return storedTimestamp
|
return storedTimestamp
|
||||||
}
|
}
|
||||||
|
|
||||||
let epochTime = "1970-01-01T00:00:00.000Z"
|
let epochTime = "1970-01-01T00:00:00.000Z"
|
||||||
print("No data state timestamp found - returning epoch time: \(epochTime)")
|
AppLogger.warning(
|
||||||
|
"No data state timestamp found - returning epoch time: \(epochTime)", tag: "DataState")
|
||||||
return epochTime
|
return epochTime
|
||||||
}
|
}
|
||||||
|
|
||||||
func setLastModified(_ timestamp: String) {
|
func setLastModified(_ timestamp: String) {
|
||||||
userDefaults.set(timestamp, forKey: Keys.lastModified)
|
userDefaults.set(timestamp, forKey: Keys.lastModified)
|
||||||
print("Data state set to: \(timestamp)")
|
AppLogger.info("Data state set to: \(timestamp)", tag: "DataState")
|
||||||
}
|
}
|
||||||
|
|
||||||
func reset() {
|
func reset() {
|
||||||
userDefaults.removeObject(forKey: Keys.lastModified)
|
userDefaults.removeObject(forKey: Keys.lastModified)
|
||||||
userDefaults.removeObject(forKey: Keys.initialized)
|
userDefaults.removeObject(forKey: Keys.initialized)
|
||||||
print("Data state reset")
|
AppLogger.info("Data state reset", tag: "DataState")
|
||||||
}
|
}
|
||||||
|
|
||||||
private func isInitialized() -> Bool {
|
private func isInitialized() -> Bool {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import UIKit
|
|||||||
|
|
||||||
class ImageManager {
|
class ImageManager {
|
||||||
static let shared = ImageManager()
|
static let shared = ImageManager()
|
||||||
|
private let logTag = "ImageManager"
|
||||||
|
|
||||||
private let thumbnailCache = NSCache<NSString, UIImage>()
|
private let thumbnailCache = NSCache<NSString, UIImage>()
|
||||||
private let fileManager = FileManager.default
|
private let fileManager = FileManager.default
|
||||||
@@ -30,7 +31,7 @@ class ImageManager {
|
|||||||
|
|
||||||
// Final integrity check
|
// Final integrity check
|
||||||
if !validateStorageIntegrity() {
|
if !validateStorageIntegrity() {
|
||||||
print("CRITICAL: Storage integrity compromised - attempting emergency recovery")
|
logError("CRITICAL: Storage integrity compromised - attempting emergency recovery")
|
||||||
emergencyImageRestore()
|
emergencyImageRestore()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,7 +84,7 @@ class ImageManager {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
print("🔄 Migrating images from OpenClimb to Ascently directory...")
|
logInfo("🔄 Migrating images from OpenClimb to Ascently directory...")
|
||||||
|
|
||||||
do {
|
do {
|
||||||
// Create parent directory if needed
|
// Create parent directory if needed
|
||||||
@@ -94,16 +95,16 @@ class ImageManager {
|
|||||||
|
|
||||||
// Move the entire directory
|
// Move the entire directory
|
||||||
try fileManager.moveItem(at: legacyDir, to: appSupportDirectory)
|
try fileManager.moveItem(at: legacyDir, to: appSupportDirectory)
|
||||||
print("Successfully migrated image directory from OpenClimb to Ascently")
|
logInfo("Successfully migrated image directory from OpenClimb to Ascently")
|
||||||
} catch {
|
} catch {
|
||||||
print("❌ Failed to migrate image directory: \(error)")
|
logError("Failed to migrate image directory: \(error)")
|
||||||
// If move fails, try to copy instead
|
// If move fails, try to copy instead
|
||||||
do {
|
do {
|
||||||
try fileManager.copyItem(at: legacyDir, to: appSupportDirectory)
|
try fileManager.copyItem(at: legacyDir, to: appSupportDirectory)
|
||||||
print("Successfully copied image directory from OpenClimb to Ascently")
|
logInfo("Successfully copied image directory from OpenClimb to Ascently")
|
||||||
// Don't remove the old directory in case of issues
|
// Don't remove the old directory in case of issues
|
||||||
} catch {
|
} catch {
|
||||||
print("❌ Failed to copy image directory: \(error)")
|
logError("Failed to copy image directory: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -122,9 +123,9 @@ class ImageManager {
|
|||||||
attributes: [
|
attributes: [
|
||||||
.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication
|
.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication
|
||||||
])
|
])
|
||||||
print("Created directory: \(directory.path)")
|
logInfo("Created directory: \(directory.path)")
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to create directory \(directory.path): \(error)")
|
logError("ERROR: Failed to create directory \(directory.path): \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,9 +142,9 @@ class ImageManager {
|
|||||||
var backupURL = backupDirectory
|
var backupURL = backupDirectory
|
||||||
try imagesURL.setResourceValues(resourceValues)
|
try imagesURL.setResourceValues(resourceValues)
|
||||||
try backupURL.setResourceValues(resourceValues)
|
try backupURL.setResourceValues(resourceValues)
|
||||||
print("Excluded image directories from iCloud backup")
|
logInfo("Excluded image directories from iCloud backup")
|
||||||
} catch {
|
} catch {
|
||||||
print("WARNING: Failed to exclude from iCloud backup: \(error)")
|
logWarning("WARNING: Failed to exclude from iCloud backup: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,11 +168,11 @@ class ImageManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func performRobustMigration() {
|
private func performRobustMigration() {
|
||||||
print("Starting robust image migration system...")
|
logInfo("Starting robust image migration system...")
|
||||||
|
|
||||||
// Check for interrupted migration
|
// Check for interrupted migration
|
||||||
if let incompleteState = loadMigrationState() {
|
if let incompleteState = loadMigrationState() {
|
||||||
print("Detected interrupted migration, resuming...")
|
logInfo("Detected interrupted migration, resuming...")
|
||||||
resumeMigration(from: incompleteState)
|
resumeMigration(from: incompleteState)
|
||||||
} else {
|
} else {
|
||||||
// Start fresh migration
|
// Start fresh migration
|
||||||
@@ -188,7 +189,7 @@ class ImageManager {
|
|||||||
private func startNewMigration() {
|
private func startNewMigration() {
|
||||||
// First check for images in previous Application Support directories
|
// First check for images in previous Application Support directories
|
||||||
if let previousAppSupportImages = findPreviousAppSupportImages() {
|
if let previousAppSupportImages = findPreviousAppSupportImages() {
|
||||||
print("Found images in previous Application Support directory")
|
logInfo("Found images in previous Application Support directory")
|
||||||
migratePreviousAppSupportImages(from: previousAppSupportImages)
|
migratePreviousAppSupportImages(from: previousAppSupportImages)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -198,7 +199,7 @@ class ImageManager {
|
|||||||
let hasLegacyImportImages = fileManager.fileExists(atPath: legacyImportImagesDirectory.path)
|
let hasLegacyImportImages = fileManager.fileExists(atPath: legacyImportImagesDirectory.path)
|
||||||
|
|
||||||
guard hasLegacyImages || hasLegacyImportImages else {
|
guard hasLegacyImages || hasLegacyImportImages else {
|
||||||
print("No legacy images to migrate")
|
logInfo("No legacy images to migrate")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,7 +214,7 @@ class ImageManager {
|
|||||||
let legacyFiles = try fileManager.contentsOfDirectory(
|
let legacyFiles = try fileManager.contentsOfDirectory(
|
||||||
atPath: legacyImagesDirectory.path)
|
atPath: legacyImagesDirectory.path)
|
||||||
allLegacyFiles.append(contentsOf: legacyFiles)
|
allLegacyFiles.append(contentsOf: legacyFiles)
|
||||||
print("Found \(legacyFiles.count) images in OpenClimbImages")
|
logInfo("Found \(legacyFiles.count) images in OpenClimbImages")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Collect files from Documents/images directory
|
// Collect files from Documents/images directory
|
||||||
@@ -221,10 +222,10 @@ class ImageManager {
|
|||||||
let importFiles = try fileManager.contentsOfDirectory(
|
let importFiles = try fileManager.contentsOfDirectory(
|
||||||
atPath: legacyImportImagesDirectory.path)
|
atPath: legacyImportImagesDirectory.path)
|
||||||
allLegacyFiles.append(contentsOf: importFiles)
|
allLegacyFiles.append(contentsOf: importFiles)
|
||||||
print("Found \(importFiles.count) images in Documents/images")
|
logInfo("Found \(importFiles.count) images in Documents/images")
|
||||||
}
|
}
|
||||||
|
|
||||||
print("Total legacy images to migrate: \(allLegacyFiles.count)")
|
logInfo("Total legacy images to migrate: \(allLegacyFiles.count)")
|
||||||
|
|
||||||
let initialState = MigrationState(
|
let initialState = MigrationState(
|
||||||
version: MigrationState.currentVersion,
|
version: MigrationState.currentVersion,
|
||||||
@@ -237,26 +238,24 @@ class ImageManager {
|
|||||||
|
|
||||||
saveMigrationState(initialState)
|
saveMigrationState(initialState)
|
||||||
performMigrationWithCheckpoints(files: allLegacyFiles, currentState: initialState)
|
performMigrationWithCheckpoints(files: allLegacyFiles, currentState: initialState)
|
||||||
|
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to start migration: \(error)")
|
logError("ERROR: Failed to start migration: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func resumeMigration(from state: MigrationState) {
|
private func resumeMigration(from state: MigrationState) {
|
||||||
print("Resuming migration from checkpoint...")
|
logInfo("Resuming migration from checkpoint...")
|
||||||
print("Progress: \(state.completedFiles.count)/\(state.totalFiles)")
|
logInfo("Progress: \(state.completedFiles.count)/\(state.totalFiles)")
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let legacyFiles = try fileManager.contentsOfDirectory(
|
let legacyFiles = try fileManager.contentsOfDirectory(
|
||||||
atPath: legacyImagesDirectory.path)
|
atPath: legacyImagesDirectory.path)
|
||||||
let remainingFiles = legacyFiles.filter { !state.completedFiles.contains($0) }
|
let remainingFiles = legacyFiles.filter { !state.completedFiles.contains($0) }
|
||||||
|
|
||||||
print("Resuming with \(remainingFiles.count) remaining files")
|
logInfo("Resuming with \(remainingFiles.count) remaining files")
|
||||||
performMigrationWithCheckpoints(files: remainingFiles, currentState: state)
|
performMigrationWithCheckpoints(files: remainingFiles, currentState: state)
|
||||||
|
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to resume migration: \(error)")
|
logError("ERROR: Failed to resume migration: \(error)")
|
||||||
// Fallback: start fresh
|
// Fallback: start fresh
|
||||||
removeMigrationState()
|
removeMigrationState()
|
||||||
startNewMigration()
|
startNewMigration()
|
||||||
@@ -323,11 +322,10 @@ class ImageManager {
|
|||||||
completedFiles.append(fileName)
|
completedFiles.append(fileName)
|
||||||
migratedCount += 1
|
migratedCount += 1
|
||||||
|
|
||||||
print("Migrated: \(fileName) (\(migratedCount)/\(currentState.totalFiles))")
|
logInfo("Migrated: \(fileName) (\(migratedCount)/\(currentState.totalFiles))")
|
||||||
|
|
||||||
} catch {
|
} catch {
|
||||||
failedCount += 1
|
failedCount += 1
|
||||||
print("ERROR: Failed to migrate \(fileName): \(error)")
|
logError("ERROR: Failed to migrate \(fileName): \(error)")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save checkpoint every 5 files or if interrupted
|
// Save checkpoint every 5 files or if interrupted
|
||||||
@@ -341,7 +339,7 @@ class ImageManager {
|
|||||||
lastCheckpoint: Date()
|
lastCheckpoint: Date()
|
||||||
)
|
)
|
||||||
saveMigrationState(checkpointState)
|
saveMigrationState(checkpointState)
|
||||||
print("Checkpoint saved: \(completedFiles.count)/\(currentState.totalFiles)")
|
logInfo("Checkpoint saved: \(completedFiles.count)/\(currentState.totalFiles)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -357,7 +355,7 @@ class ImageManager {
|
|||||||
)
|
)
|
||||||
saveMigrationState(finalState)
|
saveMigrationState(finalState)
|
||||||
|
|
||||||
print("Migration complete: \(migratedCount) migrated, \(failedCount) failed")
|
logInfo("Migration complete: \(migratedCount) migrated, \(failedCount) failed")
|
||||||
|
|
||||||
// Clean up legacy directory if no failures
|
// Clean up legacy directory if no failures
|
||||||
if failedCount == 0 {
|
if failedCount == 0 {
|
||||||
@@ -366,7 +364,7 @@ class ImageManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func verifyMigrationIntegrity() {
|
private func verifyMigrationIntegrity() {
|
||||||
print("Verifying migration integrity...")
|
logInfo("Verifying migration integrity...")
|
||||||
|
|
||||||
var allLegacyFiles = Set<String>()
|
var allLegacyFiles = Set<String>()
|
||||||
|
|
||||||
@@ -384,12 +382,12 @@ class ImageManager {
|
|||||||
allLegacyFiles.formUnion(importFiles)
|
allLegacyFiles.formUnion(importFiles)
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to read legacy directories: \(error)")
|
logError("ERROR: Failed to read legacy directories: \(error)")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
guard !allLegacyFiles.isEmpty else {
|
guard !allLegacyFiles.isEmpty else {
|
||||||
print("No legacy directories to verify against")
|
logInfo("No legacy directories to verify against")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,10 +398,10 @@ class ImageManager {
|
|||||||
let missingFiles = allLegacyFiles.subtracting(migratedFiles)
|
let missingFiles = allLegacyFiles.subtracting(migratedFiles)
|
||||||
|
|
||||||
if missingFiles.isEmpty {
|
if missingFiles.isEmpty {
|
||||||
print("Migration integrity verified - all files present")
|
logInfo("Migration integrity verified - all files present")
|
||||||
cleanupLegacyDirectory()
|
cleanupLegacyDirectory()
|
||||||
} else {
|
} else {
|
||||||
print("WARNING: Missing \(missingFiles.count) files, re-triggering migration")
|
logWarning("WARNING: Missing \(missingFiles.count) files, re-triggering migration")
|
||||||
// Re-trigger migration for missing files
|
// Re-trigger migration for missing files
|
||||||
performMigrationWithCheckpoints(
|
performMigrationWithCheckpoints(
|
||||||
files: Array(missingFiles),
|
files: Array(missingFiles),
|
||||||
@@ -417,16 +415,16 @@ class ImageManager {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to verify migration integrity: \(error)")
|
logError("ERROR: Failed to verify migration integrity: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func cleanupLegacyDirectory() {
|
private func cleanupLegacyDirectory() {
|
||||||
do {
|
do {
|
||||||
try fileManager.removeItem(at: legacyImagesDirectory)
|
try fileManager.removeItem(at: legacyImagesDirectory)
|
||||||
print("Cleaned up legacy directory")
|
logInfo("Cleaned up legacy directory")
|
||||||
} catch {
|
} catch {
|
||||||
print("WARNING: Failed to clean up legacy directory: \(error)")
|
logWarning("WARNING: Failed to clean up legacy directory: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -446,16 +444,16 @@ class ImageManager {
|
|||||||
let data = try Data(contentsOf: migrationStateURL)
|
let data = try Data(contentsOf: migrationStateURL)
|
||||||
let state = try JSONDecoder().decode(MigrationState.self, from: data)
|
let state = try JSONDecoder().decode(MigrationState.self, from: data)
|
||||||
|
|
||||||
// Check if state is too old (more than 1 hour)
|
// Check if state is too old
|
||||||
if Date().timeIntervalSince(state.lastCheckpoint) > 3600 {
|
if Date().timeIntervalSince(state.lastCheckpoint) > 3600 {
|
||||||
print("WARNING: Migration state is stale, starting fresh")
|
logWarning("WARNING: Migration state is stale, starting fresh")
|
||||||
removeMigrationState()
|
removeMigrationState()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return state.isComplete ? nil : state
|
return state.isComplete ? nil : state
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to load migration state: \(error)")
|
logError("ERROR: Failed to load migration state: \(error)")
|
||||||
removeMigrationState()
|
removeMigrationState()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -466,7 +464,7 @@ class ImageManager {
|
|||||||
let data = try JSONEncoder().encode(state)
|
let data = try JSONEncoder().encode(state)
|
||||||
try data.write(to: migrationStateURL)
|
try data.write(to: migrationStateURL)
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to save migration state: \(error)")
|
logError("ERROR: Failed to save migration state: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -482,7 +480,7 @@ class ImageManager {
|
|||||||
private func cleanupMigrationState() {
|
private func cleanupMigrationState() {
|
||||||
try? fileManager.removeItem(at: migrationStateURL)
|
try? fileManager.removeItem(at: migrationStateURL)
|
||||||
try? fileManager.removeItem(at: migrationLockURL)
|
try? fileManager.removeItem(at: migrationLockURL)
|
||||||
print("Cleaned up migration state files")
|
logInfo("Cleaned up migration state files")
|
||||||
}
|
}
|
||||||
|
|
||||||
func saveImageData(_ data: Data, withName name: String? = nil) -> String? {
|
func saveImageData(_ data: Data, withName name: String? = nil) -> String? {
|
||||||
@@ -497,10 +495,10 @@ class ImageManager {
|
|||||||
// Create backup copy
|
// Create backup copy
|
||||||
try data.write(to: backupPath)
|
try data.write(to: backupPath)
|
||||||
|
|
||||||
print("Saved image with backup: \(fileName)")
|
logInfo("Saved image with backup: \(fileName)")
|
||||||
return fileName
|
return fileName
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to save image \(fileName): \(error)")
|
logError("ERROR: Failed to save image \(fileName): \(error)")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -520,7 +518,7 @@ class ImageManager {
|
|||||||
if fileManager.fileExists(atPath: backupPath.path),
|
if fileManager.fileExists(atPath: backupPath.path),
|
||||||
let data = try? Data(contentsOf: backupPath)
|
let data = try? Data(contentsOf: backupPath)
|
||||||
{
|
{
|
||||||
print("Restored image from backup: \(path)")
|
logInfo("Restored image from backup: \(path)")
|
||||||
|
|
||||||
// Restore to primary location
|
// Restore to primary location
|
||||||
try? data.write(to: URL(fileURLWithPath: primaryPath))
|
try? data.write(to: URL(fileURLWithPath: primaryPath))
|
||||||
@@ -595,7 +593,7 @@ class ImageManager {
|
|||||||
do {
|
do {
|
||||||
try fileManager.removeItem(atPath: primaryPath)
|
try fileManager.removeItem(atPath: primaryPath)
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to delete primary image at \(primaryPath): \(error)")
|
logError("ERROR: Failed to delete primary image at \(primaryPath): \(error)")
|
||||||
success = false
|
success = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -605,7 +603,7 @@ class ImageManager {
|
|||||||
do {
|
do {
|
||||||
try fileManager.removeItem(at: backupPath)
|
try fileManager.removeItem(at: backupPath)
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to delete backup image at \(backupPath.path): \(error)")
|
logError("ERROR: Failed to delete backup image at \(backupPath.path): \(error)")
|
||||||
success = false
|
success = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -642,7 +640,7 @@ class ImageManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func performMaintenance() {
|
func performMaintenance() {
|
||||||
print("Starting image maintenance...")
|
logInfo("Starting image maintenance...")
|
||||||
|
|
||||||
syncBackups()
|
syncBackups()
|
||||||
validateImageIntegrity()
|
validateImageIntegrity()
|
||||||
@@ -660,11 +658,11 @@ class ImageManager {
|
|||||||
let backupPath = backupDirectory.appendingPathComponent(fileName)
|
let backupPath = backupDirectory.appendingPathComponent(fileName)
|
||||||
|
|
||||||
try? fileManager.copyItem(at: primaryPath, to: backupPath)
|
try? fileManager.copyItem(at: primaryPath, to: backupPath)
|
||||||
print("Created missing backup for: \(fileName)")
|
logInfo("Created missing backup for: \(fileName)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to sync backups: \(error)")
|
logError("ERROR: Failed to sync backups: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -675,7 +673,7 @@ class ImageManager {
|
|||||||
|
|
||||||
for fileName in files {
|
for fileName in files {
|
||||||
let filePath = imagesDirectory.appendingPathComponent(fileName)
|
let filePath = imagesDirectory.appendingPathComponent(fileName)
|
||||||
if let data = try? Data(contentsOf: filePath), data.count > 0 {
|
if let data = try? Data(contentsOf: filePath), !data.isEmpty {
|
||||||
// Basic validation - check if file has content and is reasonable size
|
// Basic validation - check if file has content and is reasonable size
|
||||||
if data.count > 100 { // Minimum viable image size
|
if data.count > 100 { // Minimum viable image size
|
||||||
validFiles += 1
|
validFiles += 1
|
||||||
@@ -683,14 +681,14 @@ class ImageManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
print("Validated \(validFiles) of \(files.count) image files")
|
logInfo("Validated \(validFiles) of \(files.count) image files")
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to validate images: \(error)")
|
logError("ERROR: Failed to validate images: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func cleanupOrphanedFiles() {
|
private func cleanupOrphanedFiles() {
|
||||||
print("Cleanup would require coordination with data manager")
|
logInfo("Cleanup would require coordination with data manager")
|
||||||
}
|
}
|
||||||
|
|
||||||
func getStorageInfo() -> (primaryCount: Int, backupCount: Int, totalSize: Int64) {
|
func getStorageInfo() -> (primaryCount: Int, backupCount: Int, totalSize: Int64) {
|
||||||
@@ -718,7 +716,7 @@ class ImageManager {
|
|||||||
private func logDirectoryInfo() {
|
private func logDirectoryInfo() {
|
||||||
let info = getStorageInfo()
|
let info = getStorageInfo()
|
||||||
let previousDir = findPreviousAppSupportImages()
|
let previousDir = findPreviousAppSupportImages()
|
||||||
print(
|
logInfo(
|
||||||
"""
|
"""
|
||||||
Ascently Image Storage:
|
Ascently Image Storage:
|
||||||
- App Support: \(appSupportDirectory.path)
|
- App Support: \(appSupportDirectory.path)
|
||||||
@@ -732,7 +730,7 @@ class ImageManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func forceRecoveryMigration() {
|
func forceRecoveryMigration() {
|
||||||
print("FORCE RECOVERY: Starting manual migration recovery...")
|
logInfo("FORCE RECOVERY: Starting manual migration recovery...")
|
||||||
|
|
||||||
// Remove any stale state
|
// Remove any stale state
|
||||||
removeMigrationState()
|
removeMigrationState()
|
||||||
@@ -741,7 +739,7 @@ class ImageManager {
|
|||||||
// Force fresh migration
|
// Force fresh migration
|
||||||
startNewMigration()
|
startNewMigration()
|
||||||
|
|
||||||
print("FORCE RECOVERY: Migration recovery completed")
|
logInfo("FORCE RECOVERY: Migration recovery completed")
|
||||||
}
|
}
|
||||||
|
|
||||||
func saveImportedImage(_ imageData: Data, filename: String) throws -> String {
|
func saveImportedImage(_ imageData: Data, filename: String) throws -> String {
|
||||||
@@ -754,12 +752,12 @@ class ImageManager {
|
|||||||
// Create backup
|
// Create backup
|
||||||
try? imageData.write(to: backupPath)
|
try? imageData.write(to: backupPath)
|
||||||
|
|
||||||
print("Imported image: \(filename)")
|
logInfo("Imported image: \(filename)")
|
||||||
return filename
|
return filename
|
||||||
}
|
}
|
||||||
|
|
||||||
func emergencyImageRestore() {
|
func emergencyImageRestore() {
|
||||||
print("EMERGENCY: Attempting image restoration...")
|
logError("EMERGENCY: Attempting image restoration...")
|
||||||
|
|
||||||
// Try to restore from backup directory
|
// Try to restore from backup directory
|
||||||
do {
|
do {
|
||||||
@@ -777,14 +775,14 @@ class ImageManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
print("EMERGENCY: Restored \(restoredCount) images from backup")
|
logError("EMERGENCY: Restored \(restoredCount) images from backup")
|
||||||
} catch {
|
} catch {
|
||||||
print("EMERGENCY: Failed to restore from backup: \(error)")
|
logError("EMERGENCY: Failed to restore from backup: \(error)")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try previous Application Support directories first
|
// Try previous Application Support directories first
|
||||||
if let previousAppSupportImages = findPreviousAppSupportImages() {
|
if let previousAppSupportImages = findPreviousAppSupportImages() {
|
||||||
print("EMERGENCY: Found previous Application Support images, migrating...")
|
logError("EMERGENCY: Found previous Application Support images, migrating...")
|
||||||
migratePreviousAppSupportImages(from: previousAppSupportImages)
|
migratePreviousAppSupportImages(from: previousAppSupportImages)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -793,23 +791,21 @@ class ImageManager {
|
|||||||
if fileManager.fileExists(atPath: legacyImagesDirectory.path)
|
if fileManager.fileExists(atPath: legacyImagesDirectory.path)
|
||||||
|| fileManager.fileExists(atPath: legacyImportImagesDirectory.path)
|
|| fileManager.fileExists(atPath: legacyImportImagesDirectory.path)
|
||||||
{
|
{
|
||||||
print("EMERGENCY: Attempting legacy migration as fallback...")
|
logError("EMERGENCY: Attempting legacy migration as fallback...")
|
||||||
forceRecoveryMigration()
|
forceRecoveryMigration()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func debugSafeInitialization() -> Bool {
|
func debugSafeInitialization() -> Bool {
|
||||||
print("DEBUG SAFE: Performing debug-safe initialization check...")
|
logDebug("DEBUG SAFE: Performing debug-safe initialization check...")
|
||||||
|
|
||||||
// Check if we're in a debug environment
|
// Check if we're in a debug environment
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
print("DEBUG SAFE: Debug environment detected")
|
logDebug("DEBUG SAFE: Debug environment detected")
|
||||||
|
|
||||||
// Check for interrupted migration more aggressively
|
|
||||||
if fileManager.fileExists(atPath: migrationLockURL.path) {
|
if fileManager.fileExists(atPath: migrationLockURL.path) {
|
||||||
print("DEBUG SAFE: Found migration lock - likely debug interruption")
|
logDebug("DEBUG SAFE: Found migration lock - likely debug interruption")
|
||||||
|
|
||||||
// Give extra time for file system to stabilize
|
|
||||||
Thread.sleep(forTimeInterval: 1.0)
|
Thread.sleep(forTimeInterval: 1.0)
|
||||||
|
|
||||||
// Try emergency recovery
|
// Try emergency recovery
|
||||||
@@ -826,17 +822,17 @@ class ImageManager {
|
|||||||
let primaryEmpty =
|
let primaryEmpty =
|
||||||
(try? fileManager.contentsOfDirectory(atPath: imagesDirectory.path).isEmpty) ?? true
|
(try? fileManager.contentsOfDirectory(atPath: imagesDirectory.path).isEmpty) ?? true
|
||||||
let backupHasFiles =
|
let backupHasFiles =
|
||||||
((try? fileManager.contentsOfDirectory(atPath: backupDirectory.path)) ?? []).count > 0
|
!((try? fileManager.contentsOfDirectory(atPath: backupDirectory.path)) ?? []).isEmpty
|
||||||
|
|
||||||
if primaryEmpty && backupHasFiles {
|
if primaryEmpty && backupHasFiles {
|
||||||
print("DEBUG SAFE: Primary empty but backup exists - restoring")
|
logDebug("DEBUG SAFE: Primary empty but backup exists - restoring")
|
||||||
emergencyImageRestore()
|
emergencyImageRestore()
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if primary storage is empty but previous Application Support images exist
|
// Check if primary storage is empty but previous Application Support images exist
|
||||||
if primaryEmpty, let previousAppSupportImages = findPreviousAppSupportImages() {
|
if primaryEmpty, let previousAppSupportImages = findPreviousAppSupportImages() {
|
||||||
print("DEBUG SAFE: Primary empty but found previous Application Support images")
|
logDebug("DEBUG SAFE: Primary empty but found previous Application Support images")
|
||||||
migratePreviousAppSupportImages(from: previousAppSupportImages)
|
migratePreviousAppSupportImages(from: previousAppSupportImages)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -852,7 +848,7 @@ class ImageManager {
|
|||||||
|
|
||||||
// Check if we have more backups than primary files (sign of corruption)
|
// Check if we have more backups than primary files (sign of corruption)
|
||||||
if backupFiles.count > primaryFiles.count + 5 {
|
if backupFiles.count > primaryFiles.count + 5 {
|
||||||
print(
|
logInfo(
|
||||||
"WARNING INTEGRITY: Backup count significantly exceeds primary - potential corruption"
|
"WARNING INTEGRITY: Backup count significantly exceeds primary - potential corruption"
|
||||||
)
|
)
|
||||||
return false
|
return false
|
||||||
@@ -860,7 +856,7 @@ class ImageManager {
|
|||||||
|
|
||||||
// Check if primary is completely empty but we have data elsewhere
|
// Check if primary is completely empty but we have data elsewhere
|
||||||
if primaryFiles.isEmpty && !backupFiles.isEmpty {
|
if primaryFiles.isEmpty && !backupFiles.isEmpty {
|
||||||
print("WARNING INTEGRITY: Primary storage empty but backups exist")
|
logWarning("WARNING INTEGRITY: Primary storage empty but backups exist")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -874,7 +870,7 @@ class ImageManager {
|
|||||||
for: .applicationSupportDirectory, in: .userDomainMask
|
for: .applicationSupportDirectory, in: .userDomainMask
|
||||||
).first
|
).first
|
||||||
else {
|
else {
|
||||||
print("ERROR: Could not access Application Support directory")
|
logError("ERROR: Could not access Application Support directory")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -908,13 +904,13 @@ class ImageManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Error scanning for previous Application Support directories: \(error)")
|
logError("ERROR: Error scanning for previous Application Support directories: \(error)")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
private func migratePreviousAppSupportImages(from sourceDirectory: URL) {
|
private func migratePreviousAppSupportImages(from sourceDirectory: URL) {
|
||||||
print("Migrating images from previous Application Support directory")
|
logInfo("Migrating images from previous Application Support directory")
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let imageFiles = try fileManager.contentsOfDirectory(atPath: sourceDirectory.path)
|
let imageFiles = try fileManager.contentsOfDirectory(atPath: sourceDirectory.path)
|
||||||
@@ -937,18 +933,32 @@ class ImageManager {
|
|||||||
// Create backup
|
// Create backup
|
||||||
try? fileManager.copyItem(at: sourcePath, to: backupPath)
|
try? fileManager.copyItem(at: sourcePath, to: backupPath)
|
||||||
|
|
||||||
print("Migrated: \(fileName)")
|
logInfo("Migrated: \(fileName)")
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to migrate \(fileName): \(error)")
|
logError("ERROR: Failed to migrate \(fileName): \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
print("Completed migration from previous Application Support directory")
|
logInfo("Completed migration from previous Application Support directory")
|
||||||
|
|
||||||
} catch {
|
} catch {
|
||||||
print("ERROR: Failed to migrate from previous Application Support: \(error)")
|
logError("ERROR: Failed to migrate from previous Application Support: \(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func logInfo(_ message: String) {
|
||||||
|
AppLogger.info(message, tag: logTag)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func logWarning(_ message: String) {
|
||||||
|
AppLogger.warning(message, tag: logTag)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func logError(_ message: String) {
|
||||||
|
AppLogger.error(message, tag: logTag)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func logDebug(_ message: String) {
|
||||||
|
AppLogger.debug(message, tag: logTag)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user