Compare commits
22 Commits
5287b98bc1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 0e8681e03a | |||
| 15094fd954 | |||
| 29eb1dfcdc | |||
| e967ef5322 | |||
| 7a20af72fa | |||
| da351cc53b | |||
| 060bdf5114 | |||
| f167c6eed7 | |||
| 3624fd051f | |||
| ac18b73c07 | |||
| 5f916461ac | |||
| 3394be4ee9 | |||
| e24d290127 | |||
| 7e8545f8db | |||
| ae2737fed1 | |||
| 4641ca9b72 | |||
| 7cec9541e2 | |||
| 37e91af5bd | |||
| 08f451ec71 | |||
| cf7ce027b1 | |||
| fa14d91359 | |||
| b781193d44 |
@@ -0,0 +1,663 @@
|
||||
Copyright (C) 2026 Davide Scaini
|
||||
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -320,3 +320,7 @@ Databases add operational complexity — backups, migrations, running processes,
|
||||
## Why federation?
|
||||
|
||||
Strava, Garmin Connect, and similar platforms are silos. If the company shuts down or changes its terms, your data and your social graph go with it. BincioActivity's federation model is inspired by the open web: you host your own data at a URL, friends subscribe to that URL, and no central authority is involved.
|
||||
|
||||
## License
|
||||
|
||||
[AGPL v3](LICENSE) — see the `LICENSE` file for details.
|
||||
|
||||
+9
-3
@@ -24,11 +24,13 @@ console = Console()
|
||||
@click.option("--sync-secret", default=None, envvar="BINCIO_SYNC_SECRET", help="Shared secret for POST /api/internal/rebuild (used by the sync-strava systemd timer).")
|
||||
@click.option("--jwt-secret", default=None, envvar="BINCIO_AUTH_JWT_SECRET", help="Shared JWT secret from bincio-auth. When set, validates JWTs locally instead of DB session lookup.")
|
||||
@click.option("--auth-api", default=None, envvar="BINCIO_AUTH_API", help="Internal URL of the bincio-auth API (e.g. http://127.0.0.1:4040). When set, admin user-state operations are proxied to bincio-auth.")
|
||||
@click.option("--oidc-issuer", default=None, envvar="BINCIO_OIDC_ISSUER", help="OIDC issuer URL (e.g. https://bincio.org). When set, validates RS256 id_tokens via JWKS (preferred over HS256).")
|
||||
def serve(data_dir: str, site_dir: str | None, host: str, port: int,
|
||||
strava_client_id: str | None, strava_client_secret: str | None,
|
||||
max_users: int | None, public_url: str | None,
|
||||
webroot: str | None, dem_url: str | None,
|
||||
sync_secret: str | None, jwt_secret: str | None, auth_api: str | None) -> None:
|
||||
sync_secret: str | None, jwt_secret: str | None, auth_api: str | None,
|
||||
oidc_issuer: str | None) -> None:
|
||||
"""Start the bincio multi-user application server.
|
||||
|
||||
Handles auth, user management, and write operations.
|
||||
@@ -72,6 +74,8 @@ def serve(data_dir: str, site_dir: str | None, host: str, port: int,
|
||||
deps.jwt_secret = jwt_secret
|
||||
if auth_api:
|
||||
deps.auth_api = auth_api.rstrip("/")
|
||||
if oidc_issuer:
|
||||
deps.oidc_issuer = oidc_issuer
|
||||
|
||||
db = open_db(dd)
|
||||
current_limit = get_setting(db, "max_users")
|
||||
@@ -89,8 +93,10 @@ def serve(data_dir: str, site_dir: str | None, host: str, port: int,
|
||||
else:
|
||||
console.print(" Users: [dim]unlimited[/dim]")
|
||||
console.print(f" DEM: [cyan]{deps.dem_url}[/cyan]")
|
||||
if deps.jwt_secret:
|
||||
console.print(" Auth: [green]JWT (bincio-auth)[/green]")
|
||||
if deps.oidc_issuer:
|
||||
console.print(f" Auth: [green]RS256 via {deps.oidc_issuer}[/green]" + (" + HS256 fallback" if deps.jwt_secret else ""))
|
||||
elif deps.jwt_secret:
|
||||
console.print(" Auth: [green]JWT HS256 (bincio-auth)[/green]")
|
||||
else:
|
||||
console.print(" Auth: [dim]local DB sessions[/dim]")
|
||||
console.print()
|
||||
|
||||
+74
-6
@@ -38,12 +38,20 @@ dem_url: str = "https://api.open-elevation.com"
|
||||
sync_secret: str = ""
|
||||
jwt_secret: str = "" # when set, validates JWTs from bincio-auth instead of DB session lookup
|
||||
auth_api: str = "" # when set, proxies user-state admin ops to bincio-auth (e.g. http://127.0.0.1:4040)
|
||||
oidc_issuer: str = "" # when set, validates RS256 id_tokens via bincio-auth JWKS
|
||||
_db = None
|
||||
_strava_sync_running = False
|
||||
_strava_sync_lock = threading.Lock()
|
||||
_garmin_sync_running = False
|
||||
_garmin_sync_lock = threading.Lock()
|
||||
|
||||
# ── JWKS cache ────────────────────────────────────────────────────────────────
|
||||
|
||||
_jwks_public_key: object = None
|
||||
_jwks_fetched_at: float = 0.0
|
||||
_jwks_lock = threading.Lock()
|
||||
_JWKS_TTL = 3600
|
||||
|
||||
# ── Constants ─────────────────────────────────────────────────────────────────
|
||||
|
||||
_VALID_HANDLE = re.compile(r'^[a-z0-9][a-z0-9_-]{0,29}$')
|
||||
@@ -116,8 +124,59 @@ def _check_rate_limit(
|
||||
|
||||
# ── Auth dependency functions ─────────────────────────────────────────────────
|
||||
|
||||
def _decode_jwt(token: str) -> User | None:
|
||||
"""Decode a bincio-auth JWT and return a User. Returns None on any failure."""
|
||||
def _get_jwks_public_key() -> object:
|
||||
"""Fetch and cache the RSA public key from bincio-auth's JWKS endpoint."""
|
||||
global _jwks_public_key, _jwks_fetched_at
|
||||
now = time.time()
|
||||
with _jwks_lock:
|
||||
if _jwks_public_key is not None and now - _jwks_fetched_at < _JWKS_TTL:
|
||||
return _jwks_public_key
|
||||
import base64
|
||||
import urllib.request
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
url = f"{oidc_issuer.rstrip('/')}/.well-known/jwks.json"
|
||||
with urllib.request.urlopen(url, timeout=5) as r:
|
||||
jwks = json.loads(r.read())
|
||||
k = jwks["keys"][0]
|
||||
|
||||
def _b64i(s: str) -> int:
|
||||
s += "=" * (-len(s) % 4)
|
||||
return int.from_bytes(base64.urlsafe_b64decode(s), "big")
|
||||
|
||||
pub = RSAPublicNumbers(_b64i(k["e"]), _b64i(k["n"])).public_key(default_backend())
|
||||
_jwks_public_key = pub
|
||||
_jwks_fetched_at = now
|
||||
return pub
|
||||
|
||||
|
||||
def _decode_rs256(token: str) -> User | None:
|
||||
"""Decode an RS256 id_token from bincio-auth. Returns None on any failure."""
|
||||
try:
|
||||
pub = _get_jwks_public_key()
|
||||
payload = _jwt.decode(
|
||||
token, pub, algorithms=["RS256"],
|
||||
options={"verify_aud": False},
|
||||
issuer=oidc_issuer,
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
handle = payload.get("sub")
|
||||
if not handle:
|
||||
return None
|
||||
return User(
|
||||
handle=handle,
|
||||
display_name=payload.get("name") or payload.get("display_name", ""),
|
||||
is_admin=bool(payload.get("is_admin", False)),
|
||||
wiki_access=bool(payload.get("wiki_access", True)),
|
||||
activity_access=bool(payload.get("activity_access", False)),
|
||||
suspended=False,
|
||||
created_at=0,
|
||||
)
|
||||
|
||||
|
||||
def _decode_hs256(token: str) -> User | None:
|
||||
"""Decode a bincio-auth HS256 JWT and return a User. Returns None on any failure."""
|
||||
try:
|
||||
payload = _jwt.decode(token, jwt_secret, algorithms=["HS256"])
|
||||
except _jwt.PyJWTError:
|
||||
@@ -136,12 +195,21 @@ def _decode_jwt(token: str) -> User | None:
|
||||
)
|
||||
|
||||
|
||||
def _decode_token(token: str) -> User | None:
|
||||
"""Try RS256 first (if oidc_issuer set), then HS256, then DB session."""
|
||||
if oidc_issuer:
|
||||
user = _decode_rs256(token)
|
||||
if user:
|
||||
return user
|
||||
if jwt_secret:
|
||||
return _decode_hs256(token)
|
||||
return get_session(_get_db(), token)
|
||||
|
||||
|
||||
def _current_user(bincio_session: str | None = Cookie(default=None)) -> User | None:
|
||||
if not bincio_session:
|
||||
return None
|
||||
if jwt_secret:
|
||||
return _decode_jwt(bincio_session)
|
||||
return get_session(_get_db(), bincio_session)
|
||||
return _decode_token(bincio_session)
|
||||
|
||||
|
||||
def _require_user(bincio_session: str | None = Cookie(default=None)) -> User:
|
||||
@@ -170,7 +238,7 @@ def _require_auth(
|
||||
token = auth[7:]
|
||||
if not token:
|
||||
raise HTTPException(401, "Not authenticated")
|
||||
user = _decode_jwt(token) if jwt_secret else get_session(_get_db(), token)
|
||||
user = _decode_token(token)
|
||||
if not user:
|
||||
raise HTTPException(401, "Invalid or expired session")
|
||||
return user
|
||||
|
||||
@@ -165,6 +165,7 @@ async def admin_reset_password_code(
|
||||
bincio_session: str | None = Cookie(default=None),
|
||||
) -> JSONResponse:
|
||||
"""Generate a one-time password reset code for a user. Proxied to bincio-auth."""
|
||||
deps._require_admin(bincio_session)
|
||||
return await _auth_proxy("POST", f"/api/admin/users/{handle}/reset-password-code", bincio_session)
|
||||
|
||||
|
||||
@@ -174,6 +175,7 @@ async def admin_suspend(
|
||||
bincio_session: str | None = Cookie(default=None),
|
||||
) -> JSONResponse:
|
||||
"""Suspend a user account. Proxied to bincio-auth."""
|
||||
deps._require_admin(bincio_session)
|
||||
return await _auth_proxy("POST", f"/api/admin/users/{handle}/suspend", bincio_session)
|
||||
|
||||
|
||||
@@ -183,6 +185,7 @@ async def admin_unsuspend(
|
||||
bincio_session: str | None = Cookie(default=None),
|
||||
) -> JSONResponse:
|
||||
"""Re-enable a suspended user account. Proxied to bincio-auth."""
|
||||
deps._require_admin(bincio_session)
|
||||
return await _auth_proxy("POST", f"/api/admin/users/{handle}/unsuspend", bincio_session)
|
||||
|
||||
|
||||
@@ -192,6 +195,7 @@ async def admin_delete_account(
|
||||
bincio_session: str | None = Cookie(default=None),
|
||||
) -> JSONResponse:
|
||||
"""Delete a user account. Proxied to bincio-auth."""
|
||||
deps._require_admin(bincio_session)
|
||||
return await _auth_proxy("DELETE", f"/api/admin/users/{handle}/account", bincio_session)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Budget transparency endpoints (/api/budget)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Cookie, Depends, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from bincio.serve import deps
|
||||
from bincio.serve.db import User
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_BUDGET_FILE = "budget.json"
|
||||
|
||||
|
||||
def _budget_path() -> Path:
|
||||
return deps._get_data_dir() / _BUDGET_FILE
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
p = _budget_path()
|
||||
if not p.exists():
|
||||
return {"monthly_target_eur": None, "entries": []}
|
||||
try:
|
||||
return json.loads(p.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return {"monthly_target_eur": None, "entries": []}
|
||||
|
||||
|
||||
def _save(data: dict) -> None:
|
||||
_budget_path().write_text(
|
||||
json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def _materialise_recurring(data: dict) -> bool:
|
||||
"""Auto-add a copy of each recurring entry for the current month if absent.
|
||||
|
||||
Returns True if data was modified (caller should save).
|
||||
Copies reference the template via recurring_from so they're not re-generated.
|
||||
"""
|
||||
current = date.today().strftime("%Y-%m")
|
||||
templates = [e for e in data.get("entries", []) if e.get("recurring")]
|
||||
if not templates:
|
||||
return False
|
||||
modified = False
|
||||
for t in templates:
|
||||
if t["month"] == current:
|
||||
continue # template is already this month
|
||||
already = any(
|
||||
e.get("recurring_from") == t["id"] and e["month"] == current
|
||||
for e in data["entries"]
|
||||
)
|
||||
if not already:
|
||||
data["entries"].append({
|
||||
"id": str(uuid.uuid4())[:8],
|
||||
"type": t["type"],
|
||||
"label": t["label"],
|
||||
"amount_eur": t["amount_eur"],
|
||||
"month": current,
|
||||
"note": t.get("note", ""),
|
||||
"recurring_from": t["id"],
|
||||
})
|
||||
modified = True
|
||||
return modified
|
||||
|
||||
|
||||
@router.get("/api/budget")
|
||||
async def get_budget() -> JSONResponse:
|
||||
data = _load()
|
||||
if _materialise_recurring(data):
|
||||
_save(data)
|
||||
return JSONResponse(data)
|
||||
|
||||
|
||||
@router.post("/api/budget/settings")
|
||||
async def update_settings(
|
||||
request: Request,
|
||||
_: User = Depends(deps._require_admin),
|
||||
) -> JSONResponse:
|
||||
body = await request.json()
|
||||
data = _load()
|
||||
if "monthly_target_eur" in body:
|
||||
v = body["monthly_target_eur"]
|
||||
data["monthly_target_eur"] = round(float(v), 2) if v is not None else None
|
||||
_save(data)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.post("/api/budget/entries")
|
||||
async def add_entry(
|
||||
request: Request,
|
||||
_: User = Depends(deps._require_admin),
|
||||
) -> JSONResponse:
|
||||
body = await request.json()
|
||||
entry_type = body.get("type")
|
||||
if entry_type not in ("donation", "expense"):
|
||||
raise HTTPException(400, "type must be 'donation' or 'expense'")
|
||||
label = str(body.get("label", "")).strip()
|
||||
if not label:
|
||||
raise HTTPException(400, "label is required")
|
||||
try:
|
||||
amount = round(float(body["amount_eur"]), 2)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise HTTPException(400, "amount_eur must be a number")
|
||||
month = str(body.get("month", "")).strip()
|
||||
if len(month) != 7 or month[4] != "-":
|
||||
raise HTTPException(400, "month must be YYYY-MM")
|
||||
note = str(body.get("note", "")).strip()
|
||||
|
||||
entry: dict = {
|
||||
"id": str(uuid.uuid4())[:8],
|
||||
"type": entry_type,
|
||||
"label": label,
|
||||
"amount_eur": amount,
|
||||
"month": month,
|
||||
"note": note,
|
||||
}
|
||||
if body.get("recurring"):
|
||||
entry["recurring"] = True
|
||||
data = _load()
|
||||
data.setdefault("entries", []).append(entry)
|
||||
_save(data)
|
||||
return JSONResponse(entry, status_code=201)
|
||||
|
||||
|
||||
@router.patch("/api/budget/entries/{entry_id}")
|
||||
async def update_entry(
|
||||
entry_id: str,
|
||||
request: Request,
|
||||
_: User = Depends(deps._require_admin),
|
||||
) -> JSONResponse:
|
||||
body = await request.json()
|
||||
data = _load()
|
||||
entry = next((e for e in data.get("entries", []) if e["id"] == entry_id), None)
|
||||
if not entry:
|
||||
raise HTTPException(404, "Entry not found")
|
||||
if "label" in body:
|
||||
entry["label"] = str(body["label"]).strip()
|
||||
if "type" in body:
|
||||
if body["type"] not in ("donation", "expense"):
|
||||
raise HTTPException(400, "type must be 'donation' or 'expense'")
|
||||
entry["type"] = body["type"]
|
||||
if "amount_eur" in body:
|
||||
entry["amount_eur"] = round(float(body["amount_eur"]), 2)
|
||||
if "month" in body:
|
||||
entry["month"] = str(body["month"]).strip()
|
||||
if "note" in body:
|
||||
entry["note"] = str(body["note"]).strip()
|
||||
if "recurring" in body:
|
||||
if body["recurring"]:
|
||||
entry["recurring"] = True
|
||||
else:
|
||||
entry.pop("recurring", None)
|
||||
_save(data)
|
||||
return JSONResponse(entry)
|
||||
|
||||
|
||||
@router.delete("/api/budget/entries/{entry_id}")
|
||||
async def delete_entry(
|
||||
entry_id: str,
|
||||
_: User = Depends(deps._require_admin),
|
||||
) -> JSONResponse:
|
||||
data = _load()
|
||||
before = len(data.get("entries", []))
|
||||
data["entries"] = [e for e in data.get("entries", []) if e["id"] != entry_id]
|
||||
if len(data["entries"]) == before:
|
||||
raise HTTPException(404, "Entry not found")
|
||||
_save(data)
|
||||
return JSONResponse({"ok": True})
|
||||
@@ -58,6 +58,14 @@ async def gear_add(
|
||||
if gear_type not in _GEAR_TYPES:
|
||||
raise HTTPException(400, f"type must be one of: {', '.join(sorted(_GEAR_TYPES))}")
|
||||
strava_id = str(body.get("strava_id", "")).strip() or None
|
||||
weight_g = body.get("weight_g")
|
||||
if weight_g is not None:
|
||||
try:
|
||||
weight_g = int(weight_g)
|
||||
if weight_g < 0:
|
||||
raise ValueError
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, "weight_g must be a non-negative integer (grams)")
|
||||
|
||||
user_dir = deps._get_data_dir() / user.handle
|
||||
items = _load(user_dir)
|
||||
@@ -75,6 +83,8 @@ async def gear_add(
|
||||
}
|
||||
if strava_id:
|
||||
item["strava_id"] = strava_id
|
||||
if weight_g is not None:
|
||||
item["weight_g"] = weight_g
|
||||
|
||||
items.append(item)
|
||||
_save(user_dir, items)
|
||||
@@ -110,6 +120,18 @@ async def gear_update(
|
||||
item["type"] = gear_type
|
||||
if "retired" in body:
|
||||
item["retired"] = bool(body["retired"])
|
||||
if "weight_g" in body:
|
||||
w = body["weight_g"]
|
||||
if w is None:
|
||||
item.pop("weight_g", None)
|
||||
else:
|
||||
try:
|
||||
w = int(w)
|
||||
if w < 0:
|
||||
raise ValueError
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, "weight_g must be a non-negative integer (grams)")
|
||||
item["weight_g"] = w
|
||||
|
||||
items[idx] = item
|
||||
_save(user_dir, items)
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""Merge and unmerge activity endpoints."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from bincio.serve import deps, tasks
|
||||
from bincio.serve.db import User
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_MERGES_FILE = "_merges.json"
|
||||
_BACKUP_DIR = "_merge_backup"
|
||||
|
||||
|
||||
def _read_merges(user_dir: Path) -> dict:
|
||||
p = user_dir / _MERGES_FILE
|
||||
if p.exists():
|
||||
try:
|
||||
return json.loads(p.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
pass
|
||||
return {"hidden": [], "merges": {}}
|
||||
|
||||
|
||||
def _write_merges(user_dir: Path, data: dict) -> None:
|
||||
(user_dir / _MERGES_FILE).write_text(
|
||||
json.dumps(data, ensure_ascii=False), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
@router.get("/api/merges")
|
||||
async def get_merges(user: User = Depends(deps._require_auth)) -> JSONResponse:
|
||||
user_dir = deps._get_data_dir() / user.handle
|
||||
return JSONResponse(_read_merges(user_dir))
|
||||
|
||||
|
||||
class MergeRequest(BaseModel):
|
||||
activity_ids: list[str]
|
||||
|
||||
|
||||
@router.post("/api/merge")
|
||||
async def merge_activities(
|
||||
body: MergeRequest,
|
||||
user: User = Depends(deps._require_auth),
|
||||
) -> JSONResponse:
|
||||
if len(body.activity_ids) < 2:
|
||||
raise HTTPException(400, "Need at least 2 activities to merge")
|
||||
|
||||
dd = deps._get_data_dir()
|
||||
user_dir = dd / user.handle
|
||||
acts_dir = user_dir / "activities"
|
||||
|
||||
activities: list[dict] = []
|
||||
for aid in body.activity_ids:
|
||||
deps._check_id(aid)
|
||||
p = acts_dir / f"{aid}.json"
|
||||
if not p.exists():
|
||||
raise HTTPException(404, f"Activity {aid} not found")
|
||||
try:
|
||||
a = json.loads(p.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
raise HTTPException(500, f"Could not read activity {aid}")
|
||||
a["_id"] = aid
|
||||
activities.append(a)
|
||||
|
||||
sports = {a.get("sport") for a in activities}
|
||||
if len(sports) > 1:
|
||||
raise HTTPException(400, "Cannot merge activities of different sports")
|
||||
|
||||
activities.sort(key=lambda a: a.get("started_at", ""))
|
||||
primary = activities[0]
|
||||
secondaries = activities[1:]
|
||||
primary_id = primary["_id"]
|
||||
secondary_ids = [a["_id"] for a in secondaries]
|
||||
|
||||
def _sum(key: str) -> float | None:
|
||||
vals = [a.get(key) for a in activities if a.get(key) is not None]
|
||||
return sum(vals) if vals else None
|
||||
|
||||
def _wavg(key: str) -> float | None:
|
||||
pairs = [(a.get(key), a.get("moving_time_s")) for a in activities]
|
||||
pairs = [(v, w) for v, w in pairs if v is not None and w and w > 0]
|
||||
if not pairs:
|
||||
return None
|
||||
total_w = sum(w for _, w in pairs)
|
||||
return sum(v * w for v, w in pairs) / total_w if total_w > 0 else None
|
||||
|
||||
distance_m = _sum("distance_m")
|
||||
duration_s = _sum("duration_s")
|
||||
moving_time_s = _sum("moving_time_s")
|
||||
elevation_gain_m = _sum("elevation_gain_m")
|
||||
avg_speed_kmh = (distance_m / moving_time_s * 3.6) if distance_m and moving_time_s else None
|
||||
avg_hr_bpm_val = _wavg("avg_hr_bpm")
|
||||
avg_power_w_val = _wavg("avg_power_w")
|
||||
|
||||
backup_dir = user_dir / _BACKUP_DIR
|
||||
backup_dir.mkdir(exist_ok=True)
|
||||
for suffix in (".json", ".geojson", ".timeseries.json"):
|
||||
src = acts_dir / f"{primary_id}{suffix}"
|
||||
if src.exists():
|
||||
shutil.copy2(src, backup_dir / f"{primary_id}{suffix}.bak")
|
||||
|
||||
primary_data: dict[str, Any] = {k: v for k, v in primary.items() if not k.startswith("_")}
|
||||
primary_data["distance_m"] = distance_m
|
||||
primary_data["duration_s"] = duration_s
|
||||
primary_data["moving_time_s"] = moving_time_s
|
||||
primary_data["elevation_gain_m"] = elevation_gain_m
|
||||
if avg_speed_kmh is not None:
|
||||
primary_data["avg_speed_kmh"] = round(avg_speed_kmh, 3)
|
||||
if avg_hr_bpm_val is not None:
|
||||
primary_data["avg_hr_bpm"] = round(avg_hr_bpm_val)
|
||||
if avg_power_w_val is not None:
|
||||
primary_data["avg_power_w"] = round(avg_power_w_val)
|
||||
primary_data["merged_ids"] = secondary_ids
|
||||
|
||||
(acts_dir / f"{primary_id}.json").write_text(
|
||||
json.dumps(primary_data, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
|
||||
_merge_geojson(acts_dir, primary_id, secondary_ids)
|
||||
_merge_timeseries(acts_dir, primary_id, secondary_ids, activities)
|
||||
|
||||
merges = _read_merges(user_dir)
|
||||
for sid in secondary_ids:
|
||||
if sid not in merges["hidden"]:
|
||||
merges["hidden"].append(sid)
|
||||
merges.setdefault("merges", {})[primary_id] = {
|
||||
"secondary_ids": secondary_ids,
|
||||
"merged_at": _now_iso(),
|
||||
}
|
||||
_write_merges(user_dir, merges)
|
||||
|
||||
from bincio.render.merge import merge_one
|
||||
merge_one(user_dir, primary_id)
|
||||
tasks._trigger_rebuild(user.handle)
|
||||
|
||||
return JSONResponse({"ok": True, "primary_id": primary_id, "hidden": secondary_ids})
|
||||
|
||||
|
||||
@router.post("/api/unmerge/{primary_id}")
|
||||
async def unmerge_activity(
|
||||
primary_id: str,
|
||||
user: User = Depends(deps._require_auth),
|
||||
) -> JSONResponse:
|
||||
deps._check_id(primary_id)
|
||||
dd = deps._get_data_dir()
|
||||
user_dir = dd / user.handle
|
||||
acts_dir = user_dir / "activities"
|
||||
backup_dir = user_dir / _BACKUP_DIR
|
||||
|
||||
merges = _read_merges(user_dir)
|
||||
merge_info = merges.get("merges", {}).get(primary_id)
|
||||
if not merge_info:
|
||||
raise HTTPException(404, "No merge record found for this activity")
|
||||
|
||||
secondary_ids: list[str] = merge_info.get("secondary_ids", [])
|
||||
|
||||
for suffix in (".json", ".geojson", ".timeseries.json"):
|
||||
bak = backup_dir / f"{primary_id}{suffix}.bak"
|
||||
if bak.exists():
|
||||
shutil.copy2(bak, acts_dir / f"{primary_id}{suffix}")
|
||||
bak.unlink()
|
||||
|
||||
merges["hidden"] = [h for h in merges.get("hidden", []) if h not in secondary_ids]
|
||||
merges["merges"].pop(primary_id, None)
|
||||
_write_merges(user_dir, merges)
|
||||
|
||||
from bincio.render.merge import merge_one
|
||||
merge_one(user_dir, primary_id)
|
||||
tasks._trigger_rebuild(user.handle)
|
||||
|
||||
return JSONResponse({"ok": True, "restored": secondary_ids})
|
||||
|
||||
|
||||
def _merge_geojson(acts_dir: Path, primary_id: str, secondary_ids: list[str]) -> None:
|
||||
primary_path = acts_dir / f"{primary_id}.geojson"
|
||||
if not primary_path.exists():
|
||||
return
|
||||
try:
|
||||
geo = json.loads(primary_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return
|
||||
features: list = list(geo.get("features", []))
|
||||
for sid in secondary_ids:
|
||||
p = acts_dir / f"{sid}.geojson"
|
||||
if not p.exists():
|
||||
continue
|
||||
try:
|
||||
sec = json.loads(p.read_text(encoding="utf-8"))
|
||||
features.extend(sec.get("features", []))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
geo["features"] = features
|
||||
primary_path.write_text(json.dumps(geo, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
def _merge_timeseries(
|
||||
acts_dir: Path,
|
||||
primary_id: str,
|
||||
secondary_ids: list[str],
|
||||
activities: list[dict],
|
||||
) -> None:
|
||||
primary_path = acts_dir / f"{primary_id}.timeseries.json"
|
||||
if not primary_path.exists():
|
||||
return
|
||||
try:
|
||||
merged = json.loads(primary_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return
|
||||
|
||||
merged = {k: list(v) if isinstance(v, list) else v for k, v in merged.items()}
|
||||
|
||||
_ARRAY_KEYS = ("lat", "lon", "elevation_m", "speed_kmh", "hr_bpm", "cadence_rpm", "power_w", "temperature_c")
|
||||
|
||||
for i, sid in enumerate(secondary_ids):
|
||||
sec_path = acts_dir / f"{sid}.timeseries.json"
|
||||
if not sec_path.exists():
|
||||
continue
|
||||
try:
|
||||
sec = json.loads(sec_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
|
||||
sec_t: list = sec.get("t") or []
|
||||
if not sec_t:
|
||||
continue
|
||||
|
||||
try:
|
||||
p_start = datetime.fromisoformat(
|
||||
activities[0].get("started_at", "").replace("Z", "+00:00")
|
||||
).timestamp()
|
||||
s_start = datetime.fromisoformat(
|
||||
activities[i + 1].get("started_at", "").replace("Z", "+00:00")
|
||||
).timestamp()
|
||||
offset = s_start - p_start
|
||||
except (ValueError, TypeError):
|
||||
cur_t: list = merged.get("t") or []
|
||||
offset = (cur_t[-1] + 1) if cur_t else 0
|
||||
|
||||
adjusted_t = [offset + t for t in sec_t]
|
||||
primary_len = len(merged.get("t") or [])
|
||||
|
||||
if merged.get("t") is None:
|
||||
merged["t"] = []
|
||||
merged["t"].extend(adjusted_t)
|
||||
|
||||
for key in _ARRAY_KEYS:
|
||||
sec_vals = sec.get(key)
|
||||
if sec_vals is None:
|
||||
if merged.get(key) is not None:
|
||||
merged[key] = merged[key] + [None] * len(sec_t)
|
||||
else:
|
||||
if merged.get(key) is None:
|
||||
merged[key] = [None] * primary_len + list(sec_vals)
|
||||
else:
|
||||
merged[key] = merged[key] + list(sec_vals)
|
||||
|
||||
primary_path.write_text(json.dumps(merged, ensure_ascii=False), encoding="utf-8")
|
||||
@@ -20,12 +20,14 @@ from bincio.serve.routers import (
|
||||
activities,
|
||||
admin,
|
||||
auth,
|
||||
budget,
|
||||
download,
|
||||
feed,
|
||||
garmin,
|
||||
gear,
|
||||
ideas,
|
||||
me,
|
||||
merge,
|
||||
ogimage,
|
||||
segments,
|
||||
strava,
|
||||
@@ -53,7 +55,7 @@ app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origin_regex=r"https?://localhost(:\d+)?|https://[a-z0-9-]+\.bincio\.org",
|
||||
allow_credentials=True,
|
||||
allow_methods=["GET", "POST", "DELETE"],
|
||||
allow_methods=["GET", "POST", "PATCH", "DELETE"],
|
||||
allow_headers=["Content-Type"],
|
||||
)
|
||||
|
||||
@@ -63,6 +65,8 @@ for _router in [
|
||||
me.router,
|
||||
admin.router,
|
||||
activities.router,
|
||||
merge.router,
|
||||
budget.router,
|
||||
download.router,
|
||||
uploads.router,
|
||||
segments.router,
|
||||
|
||||
@@ -36,6 +36,25 @@
|
||||
pr_elapsed_s: number;
|
||||
}
|
||||
let segmentEfforts: SegmentEffortHit[] = [];
|
||||
let unmergeWorking = false;
|
||||
|
||||
async function _unmerge() {
|
||||
if (!confirm('Unmerge this activity? The original tracks will be restored and the secondary activities will reappear in your feed.')) return;
|
||||
unmergeWorking = true;
|
||||
try {
|
||||
const r = await fetch(`/api/unmerge/${activity.id}`, { method: 'POST', credentials: 'include' });
|
||||
if (r.ok) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
const d = await r.json();
|
||||
alert(d.detail ?? 'Unmerge failed');
|
||||
}
|
||||
} catch {
|
||||
alert('Unmerge failed');
|
||||
} finally {
|
||||
unmergeWorking = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Local overrides applied immediately after a save (no re-fetch needed)
|
||||
let localTitle = '';
|
||||
@@ -381,6 +400,20 @@
|
||||
class="text-xs px-2 py-0.5 rounded border border-zinc-700 text-zinc-400 hover:border-zinc-500 hover:text-white transition-colors shrink-0"
|
||||
>+ segment</a>
|
||||
{/if}
|
||||
{#if detail?.merged_ids?.length}
|
||||
<span class="text-xs px-2 py-0.5 rounded border border-zinc-600 text-zinc-400 shrink-0">
|
||||
Merged ({detail.merged_ids.length})
|
||||
</span>
|
||||
{#if editEnabled}
|
||||
<button
|
||||
class="text-xs px-2 py-0.5 rounded border border-zinc-700 text-zinc-400 hover:border-zinc-500 hover:text-white transition-colors shrink-0 disabled:opacity-40"
|
||||
disabled={unmergeWorking}
|
||||
on:click={_unmerge}
|
||||
>
|
||||
{unmergeWorking ? 'Working…' : 'Unmerge'}
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{#if descriptionHtml}
|
||||
<div class="text-zinc-400 mt-2 text-sm leading-relaxed [&_img]:rounded-lg [&_img]:my-2 [&_p]:my-1 [&_a]:text-blue-400">
|
||||
|
||||
@@ -59,6 +59,73 @@
|
||||
/** Logged-in handle — resolved async via bincio:me event. */
|
||||
let me: string = '';
|
||||
|
||||
// ── Bulk / select mode ────────────────────────────────────────────────────
|
||||
let selectMode = false;
|
||||
let selected: Set<string> = new Set();
|
||||
let hiddenIds: Set<string> = new Set();
|
||||
let bulkWorking = false;
|
||||
|
||||
async function _loadMerges() {
|
||||
try {
|
||||
const r = await fetch('/api/merges', { credentials: 'include' });
|
||||
if (r.ok) {
|
||||
const data = await r.json();
|
||||
hiddenIds = new Set(data.hidden ?? []);
|
||||
}
|
||||
} catch { /* non-critical */ }
|
||||
}
|
||||
|
||||
function _toggleSelect(id: string) {
|
||||
const s = new Set(selected);
|
||||
s.has(id) ? s.delete(id) : s.add(id);
|
||||
selected = s;
|
||||
}
|
||||
|
||||
function _exitSelect() {
|
||||
selectMode = false;
|
||||
selected = new Set();
|
||||
}
|
||||
|
||||
async function _deleteSelected() {
|
||||
const ids = [...selected];
|
||||
if (!confirm(`Delete ${ids.length} activit${ids.length === 1 ? 'y' : 'ies'}? This cannot be undone.`)) return;
|
||||
bulkWorking = true;
|
||||
for (const id of ids) {
|
||||
try {
|
||||
const r = await fetch(`/api/activity/${id}`, { method: 'DELETE', credentials: 'include' });
|
||||
if (r.ok) all = all.filter(a => a.id !== id);
|
||||
} catch { /* continue */ }
|
||||
}
|
||||
bulkWorking = false;
|
||||
_exitSelect();
|
||||
}
|
||||
|
||||
async function _mergeSelected() {
|
||||
const ids = [...selected];
|
||||
if (ids.length < 2) return;
|
||||
bulkWorking = true;
|
||||
try {
|
||||
const r = await fetch('/api/merge', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ activity_ids: ids }),
|
||||
});
|
||||
const data = await r.json();
|
||||
if (r.ok) {
|
||||
for (const hid of data.hidden ?? []) hiddenIds.add(hid);
|
||||
hiddenIds = new Set(hiddenIds);
|
||||
_exitSelect();
|
||||
} else {
|
||||
alert(data.detail ?? 'Merge failed');
|
||||
}
|
||||
} catch {
|
||||
alert('Merge failed');
|
||||
} finally {
|
||||
bulkWorking = false;
|
||||
}
|
||||
}
|
||||
|
||||
function computeDateRange(preset: string): { dateFrom: string; dateTo: string } {
|
||||
if (preset === 'all') return { dateFrom: '', dateTo: '' };
|
||||
if (/^\d{4}$/.test(preset)) {
|
||||
@@ -74,11 +141,14 @@
|
||||
return { dateFrom: `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T`, dateTo: '' };
|
||||
}
|
||||
|
||||
// Filter out secondary activities hidden by a merge.
|
||||
$: withMerge = all.filter(a => !hiddenIds.has(a.id));
|
||||
|
||||
// Show private activities only to their owner.
|
||||
// On a profile page (filterHandle set): show unlisted if me === filterHandle.
|
||||
// On the global feed: show unlisted only for the logged-in user's own activities.
|
||||
$: isOwner = filterHandle !== '' && me === filterHandle;
|
||||
$: withPrivacy = all.filter(a => {
|
||||
$: withPrivacy = withMerge.filter(a => {
|
||||
if (isUnlisted(a.privacy)) {
|
||||
return filterHandle ? isOwner : (me !== '' && (a as any).handle === me);
|
||||
}
|
||||
@@ -196,8 +266,12 @@
|
||||
// Resolve the logged-in handle so we can show the owner their private activities.
|
||||
if ((window as any).__bincioMe !== undefined) {
|
||||
me = (window as any).__bincioMe;
|
||||
_loadMerges();
|
||||
} else {
|
||||
window.addEventListener('bincio:me', (e: Event) => { me = (e as CustomEvent).detail; }, { once: true });
|
||||
window.addEventListener('bincio:me', (e: Event) => {
|
||||
me = (e as CustomEvent).detail;
|
||||
_loadMerges();
|
||||
}, { once: true });
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -287,6 +361,17 @@
|
||||
on:click={() => viewMode = 'map'}
|
||||
>Map</button>
|
||||
</div>
|
||||
{#if isOwner}
|
||||
<button
|
||||
class="px-3 py-2 rounded-lg border text-sm transition-colors shrink-0"
|
||||
class:border-zinc-700={!selectMode}
|
||||
class:text-zinc-400={!selectMode}
|
||||
class:border-[--accent]={selectMode}
|
||||
class:text-white={selectMode}
|
||||
style={selectMode ? 'background:var(--accent-dim)' : ''}
|
||||
on:click={() => { if (selectMode) _exitSelect(); else selectMode = true; }}
|
||||
>{selectMode ? 'Cancel' : 'Select'}</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -368,8 +453,15 @@
|
||||
{:else}
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{#each visible as a (a.id)}
|
||||
{@const isSelected = selected.has(a.id)}
|
||||
<!-- relative + isolate so the stretched activity link stays below the handle link -->
|
||||
<div class="relative rounded-xl bg-zinc-900 border border-zinc-800 p-4 hover:border-zinc-600 hover:bg-zinc-800/80 transition-all group">
|
||||
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||
<!-- svelte-ignore a11y-no-static-element-interactions -->
|
||||
<div
|
||||
class="relative rounded-xl bg-zinc-900 border p-4 transition-all group {isSelected ? 'border-[--accent]' : 'border-zinc-800'} {selectMode ? 'cursor-pointer' : 'hover:border-zinc-600 hover:bg-zinc-800/80'}"
|
||||
style={isSelected ? 'background:var(--accent-dim)' : ''}
|
||||
on:click={selectMode ? () => _toggleSelect(a.id) : undefined}
|
||||
>
|
||||
<!-- header -->
|
||||
<div class="flex items-start justify-between gap-2 mb-3">
|
||||
<div class="flex-1 min-w-0">
|
||||
@@ -384,19 +476,34 @@
|
||||
{#if isUnlisted(a.privacy)}
|
||||
<span class="text-zinc-500 shrink-0" title="Unlisted">🔒</span>
|
||||
{/if}
|
||||
<a
|
||||
href={a.detail_url ? `${import.meta.env.BASE_URL}activity/${a.id}/` : `${import.meta.env.BASE_URL}activity/local/?id=${a.id}`}
|
||||
class="before:absolute before:inset-0 before:content-[''] truncate"
|
||||
on:click={() => { try { sessionStorage.setItem(`bincio:activity:${a.id}`, JSON.stringify(a)); } catch {} }}
|
||||
>{a.title}</a>
|
||||
{#if selectMode}
|
||||
<span class="truncate">{a.title}</span>
|
||||
{:else}
|
||||
<a
|
||||
href={a.detail_url ? `${import.meta.env.BASE_URL}activity/${a.id}/` : `${import.meta.env.BASE_URL}activity/local/?id=${a.id}`}
|
||||
class="before:absolute before:inset-0 before:content-[''] truncate"
|
||||
on:click={() => { try { sessionStorage.setItem(`bincio:activity:${a.id}`, JSON.stringify(filterHandle && !a.handle ? { ...a, handle: filterHandle } : a)); } catch {} }}
|
||||
>{a.title}</a>
|
||||
{/if}
|
||||
</h3>
|
||||
</div>
|
||||
<span
|
||||
class="text-xs font-medium px-2 py-0.5 rounded-full flex-shrink-0"
|
||||
style="background:{sportColor(a.sport)}22; color:{sportColor(a.sport)}"
|
||||
>
|
||||
{sportIcon(a.sport)} {sportLabel(a.sport, a.sub_sport)}
|
||||
</span>
|
||||
{#if selectMode}
|
||||
<div
|
||||
class="shrink-0 w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors"
|
||||
class:border-zinc-600={!isSelected}
|
||||
class:border-[--accent]={isSelected}
|
||||
style={isSelected ? 'background:var(--accent)' : ''}
|
||||
>
|
||||
{#if isSelected}<span class="text-[10px] text-white leading-none">✓</span>{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<span
|
||||
class="text-xs font-medium px-2 py-0.5 rounded-full flex-shrink-0"
|
||||
style="background:{sportColor(a.sport)}22; color:{sportColor(a.sport)}"
|
||||
>
|
||||
{sportIcon(a.sport)} {sportLabel(a.sport, a.sub_sport)}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- track thumbnail -->
|
||||
@@ -466,3 +573,35 @@
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<!-- Bulk action bar — fixed at bottom when select mode is active -->
|
||||
{#if selectMode}
|
||||
<div class="fixed bottom-0 left-0 right-0 z-50 flex items-center justify-center gap-3 px-4 py-4 bg-zinc-950/95 backdrop-blur border-t border-zinc-800">
|
||||
<span class="text-sm text-zinc-400 mr-2">
|
||||
{selected.size} selected
|
||||
</span>
|
||||
<button
|
||||
class="px-4 py-2 rounded-lg border border-red-700 text-red-400 hover:bg-red-900/30 disabled:opacity-40 transition-colors text-sm"
|
||||
disabled={selected.size === 0 || bulkWorking}
|
||||
on:click={_deleteSelected}
|
||||
>
|
||||
Delete ({selected.size})
|
||||
</button>
|
||||
<button
|
||||
class="px-4 py-2 rounded-lg border border-zinc-600 text-zinc-300 hover:bg-zinc-800 disabled:opacity-40 transition-colors text-sm"
|
||||
disabled={selected.size < 2 || bulkWorking}
|
||||
on:click={_mergeSelected}
|
||||
>
|
||||
Merge ({selected.size})
|
||||
</button>
|
||||
<button
|
||||
class="px-4 py-2 rounded-lg border border-zinc-700 text-zinc-500 hover:text-zinc-300 transition-colors text-sm"
|
||||
on:click={_exitSelect}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
{#if bulkWorking}
|
||||
<span class="text-xs text-zinc-500">Working…</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
let maxHr: number | null = null;
|
||||
let ftpW: number | null = null;
|
||||
let weightKg: number | null = null;
|
||||
let hrZones: [number, number][] = [];
|
||||
let powerZones: [number, number][] = [];
|
||||
let seasons: { name: string; start: string; end: string }[] = [];
|
||||
@@ -24,8 +25,9 @@
|
||||
const res = await fetch(`${editUrl}/api/athlete`);
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
const d = await res.json();
|
||||
maxHr = d.max_hr ?? null;
|
||||
ftpW = d.ftp_w ?? null;
|
||||
maxHr = d.max_hr ?? null;
|
||||
ftpW = d.ftp_w ?? null;
|
||||
weightKg = d.weight_kg ?? null;
|
||||
hrZones = d.hr_zones ? d.hr_zones.map((z: number[]) => [z[0], z[1]] as [number,number]) : [];
|
||||
powerZones = d.power_zones ? d.power_zones.map((z: number[]) => [z[0], z[1]] as [number,number]) : [];
|
||||
seasons = d.seasons ?? [];
|
||||
@@ -76,6 +78,7 @@
|
||||
body: JSON.stringify({
|
||||
max_hr: maxHr,
|
||||
ftp_w: ftpW,
|
||||
weight_kg: weightKg,
|
||||
hr_zones: hrZones,
|
||||
power_zones: powerZones,
|
||||
seasons,
|
||||
@@ -144,6 +147,14 @@
|
||||
class="w-full bg-zinc-900 border border-zinc-700 rounded-md px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
</label>
|
||||
<label class="block">
|
||||
<span class="text-xs text-zinc-500 mb-1 block">Body weight (kg)</span>
|
||||
<input
|
||||
type="number" min="30" max="200" step="0.1"
|
||||
bind:value={weightKg}
|
||||
class="w-full bg-zinc-900 border border-zinc-700 rounded-md px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
// Gear tab state
|
||||
interface GearReplacement { id: string; date: string; note?: string }
|
||||
interface GearPart { id: string; name: string; threshold_km?: number; replacements: GearReplacement[] }
|
||||
interface GearItem { id: string; name: string; type: string; retired: boolean; strava_id?: string; parts?: GearPart[] }
|
||||
interface GearItem { id: string; name: string; type: string; retired: boolean; strava_id?: string; weight_g?: number; parts?: GearPart[] }
|
||||
|
||||
let gearItems: GearItem[] = [];
|
||||
let gearLoading = false;
|
||||
@@ -66,6 +66,7 @@
|
||||
let gearEditName = '';
|
||||
let gearEditType = 'bike';
|
||||
let gearEditRetired = false;
|
||||
let gearEditWeightG: number | null = null;
|
||||
let gearSaving = false;
|
||||
let gearExpandedId: string | null = null;
|
||||
|
||||
@@ -161,7 +162,7 @@
|
||||
}
|
||||
|
||||
function gearStartEdit(item: GearItem) {
|
||||
gearEditId = item.id; gearEditName = item.name; gearEditType = item.type; gearEditRetired = item.retired;
|
||||
gearEditId = item.id; gearEditName = item.name; gearEditType = item.type; gearEditRetired = item.retired; gearEditWeightG = item.weight_g ?? null;
|
||||
}
|
||||
|
||||
async function gearSaveEdit() {
|
||||
@@ -171,7 +172,7 @@
|
||||
const r = await fetch(`/api/gear/${gearEditId}`, {
|
||||
method: 'PATCH', credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: gearEditName.trim(), type: gearEditType, retired: gearEditRetired }),
|
||||
body: JSON.stringify({ name: gearEditName.trim(), type: gearEditType, retired: gearEditRetired, weight_g: gearEditWeightG }),
|
||||
});
|
||||
const d = await r.json();
|
||||
if (r.ok) {
|
||||
@@ -673,6 +674,14 @@
|
||||
<input type="checkbox" bind:checked={gearEditRetired} class="accent-blue-500" />
|
||||
Retired
|
||||
</label>
|
||||
<label class="flex items-center gap-1.5 text-sm text-zinc-400">
|
||||
<input
|
||||
type="number" min="0" step="1" placeholder="weight (g)"
|
||||
bind:value={gearEditWeightG}
|
||||
class="w-28 bg-zinc-700 text-white text-sm px-2 py-1 rounded border border-zinc-600 focus:border-blue-500 outline-none"
|
||||
/>
|
||||
<span class="text-xs">g</span>
|
||||
</label>
|
||||
<button
|
||||
on:click={gearSaveEdit}
|
||||
disabled={gearSaving || !gearEditName.trim()}
|
||||
@@ -703,6 +712,9 @@
|
||||
{#if gearDistances[item.name] > 0}
|
||||
<span class="text-xs text-zinc-400">{formatDistance(gearDistances[item.name])}</span>
|
||||
{/if}
|
||||
{#if item.weight_g}
|
||||
<span class="text-xs text-zinc-500">{item.weight_g >= 1000 ? (item.weight_g / 1000).toFixed(2).replace(/\.?0+$/, '') + ' kg' : item.weight_g + ' g'}</span>
|
||||
{/if}
|
||||
{#if item.retired}
|
||||
<span class="text-xs text-zinc-600 border border-zinc-700 rounded px-1.5 py-0.5">Retired</span>
|
||||
{/if}
|
||||
@@ -910,8 +922,14 @@
|
||||
<span class="text-white font-medium">{athlete.ftp_w} W</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if !athlete.max_hr && !athlete.ftp_w}
|
||||
<p class="text-zinc-500 text-sm">Set <code>athlete.max_hr</code> and <code>athlete.ftp_w</code> in your config, or use Edit profile.</p>
|
||||
{#if athlete.weight_kg}
|
||||
<div class="flex justify-between text-sm">
|
||||
<span class="text-zinc-400">Weight</span>
|
||||
<span class="text-white font-medium">{athlete.weight_kg} kg</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if !athlete.max_hr && !athlete.ftp_w && !athlete.weight_kg}
|
||||
<p class="text-zinc-500 text-sm">No key numbers set yet. Use Edit profile to add Max HR, FTP, and body weight.</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
+10
-14
@@ -101,10 +101,12 @@ try {
|
||||
{instancePrivate && !isPublicPage && (
|
||||
<style is:inline>[data-auth-pending]{visibility:hidden}</style>
|
||||
<script is:inline define:vars={{ authUrl }}>
|
||||
window.__bincioAuthUrl = authUrl;
|
||||
fetch('/api/me', { credentials: 'include' })
|
||||
.then(r => {
|
||||
if (r.status === 401 || r.status === 404) {
|
||||
window.location.replace(authUrl ? authUrl + '/login/' : '/login/');
|
||||
const next = authUrl ? '?next=' + encodeURIComponent(window.location.href) : '';
|
||||
window.location.replace(authUrl ? authUrl + '/login/' + next : '/login/');
|
||||
} else {
|
||||
document.body.removeAttribute('data-auth-pending');
|
||||
}
|
||||
@@ -257,15 +259,10 @@ try {
|
||||
class="hidden sm:inline text-xs text-zinc-500 hover:text-white transition-colors px-1"
|
||||
>Planner</a>
|
||||
)}
|
||||
<!-- Ideas / About — always visible on desktop -->
|
||||
<a
|
||||
href={`${baseUrl}ideas/`}
|
||||
href={`${baseUrl}support/`}
|
||||
class="hidden sm:inline text-xs text-zinc-500 hover:text-white transition-colors px-1"
|
||||
>Ideas</a>
|
||||
<a
|
||||
href={`${baseUrl}about/`}
|
||||
class="hidden sm:inline text-xs text-zinc-500 hover:text-white transition-colors px-1"
|
||||
>About</a>
|
||||
>Support</a>
|
||||
<!-- Settings link — hidden until logged in -->
|
||||
<a
|
||||
id="nav-settings"
|
||||
@@ -330,12 +327,9 @@ try {
|
||||
style="display:none; color: var(--text-4)"
|
||||
class="text-sm px-2 py-1.5 rounded hover:bg-zinc-800 transition-colors">Planner</a>
|
||||
)}
|
||||
<a href={`${baseUrl}ideas/`}
|
||||
<a href={`${baseUrl}support/`}
|
||||
class="text-sm px-2 py-1.5 rounded hover:bg-zinc-800 transition-colors"
|
||||
style="color: var(--text-4)">Ideas</a>
|
||||
<a href={`${baseUrl}about/`}
|
||||
class="text-sm px-2 py-1.5 rounded hover:bg-zinc-800 transition-colors"
|
||||
style="color: var(--text-4)">About</a>
|
||||
style="color: var(--text-4)">Support</a>
|
||||
<a href={`${baseUrl}settings/`}
|
||||
class="text-sm px-2 py-1.5 rounded hover:bg-zinc-800 transition-colors"
|
||||
style="color: var(--text-4)">Settings</a>
|
||||
@@ -597,7 +591,8 @@ try {
|
||||
|
||||
<!-- User widget: only needed for multi-user (single-user nav links are static) -->
|
||||
{!singleHandle && (
|
||||
<script define:vars={{ baseUrl, authUrl }}>
|
||||
<script define:vars={{ baseUrl }}>
|
||||
const authUrl = window.__bincioAuthUrl || '';
|
||||
(async () => {
|
||||
try {
|
||||
const r = await fetch('/api/me', { credentials: 'include' });
|
||||
@@ -739,6 +734,7 @@ try {
|
||||
|
||||
{editEnabled && (
|
||||
<script define:vars={{ editUrl, baseUrl }}>
|
||||
const authUrl = window.__bincioAuthUrl || '';
|
||||
const modal = document.getElementById('upload-modal');
|
||||
const openBtn = document.getElementById('upload-btn');
|
||||
const closeBtn = document.getElementById('upload-close');
|
||||
|
||||
@@ -44,6 +44,7 @@ export interface AthleteJson {
|
||||
best_climbs?: BestClimb[];
|
||||
max_hr?: number;
|
||||
ftp_w?: number;
|
||||
weight_kg?: number;
|
||||
hr_zones?: [number, number][];
|
||||
power_zones?: [number, number][];
|
||||
seasons?: { name: string; start: string; end: string }[];
|
||||
@@ -130,6 +131,8 @@ export interface ActivityDetail extends Omit<ActivitySummary, 'detail_url' | 'tr
|
||||
source_file?: string | null;
|
||||
download_disabled?: boolean;
|
||||
custom: Record<string, unknown>;
|
||||
/** IDs of secondary activities merged into this one (set by /api/merge). */
|
||||
merged_ids?: string[] | null;
|
||||
}
|
||||
|
||||
export interface Lap {
|
||||
|
||||
@@ -1,252 +1,6 @@
|
||||
---
|
||||
import Base from '../../layouts/Base.astro';
|
||||
const baseUrl = import.meta.env.BASE_URL ?? '/';
|
||||
const labels = {
|
||||
community: 'Community',
|
||||
members: 'member',
|
||||
members_pl: 'members',
|
||||
day: 'day',
|
||||
days: 'days',
|
||||
invited_by: 'invited by',
|
||||
founder: 'founder',
|
||||
loading: 'Loading…',
|
||||
};
|
||||
const target = `${baseUrl}support/`;
|
||||
---
|
||||
<Base title="About — BincioActivity" public={true}>
|
||||
<div class="max-w-2xl mx-auto">
|
||||
<div class="flex items-baseline justify-between mb-1">
|
||||
<h1 class="text-2xl font-bold text-white">About BincioActivity</h1>
|
||||
<div class="flex gap-3 text-xs text-zinc-500">
|
||||
<span class="text-zinc-300 font-medium">EN</span>
|
||||
<a href={`${baseUrl}about/it/`} class="hover:text-white transition-colors">IT</a>
|
||||
<a href={`${baseUrl}about/es/`} class="hover:text-white transition-colors">ES</a>
|
||||
<a href={`${baseUrl}about/ca/`} class="hover:text-white transition-colors">CA</a>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-sm text-zinc-500 mb-4">Open-source, self-hosted activity tracking</p>
|
||||
<div class="flex flex-wrap gap-2 mb-4">
|
||||
<a
|
||||
href="https://ko-fi.com/brutsalvadi"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-opacity hover:opacity-90"
|
||||
style="background:#FF5E5B; color:#fff;"
|
||||
>
|
||||
☕ Support on Ko-fi
|
||||
</a>
|
||||
<a
|
||||
href="https://web.satispay.com/download/qrcode/S6Y-CON--BE9BD345-4499-4C1D-9AC3-D62FC5FF0AD4"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-opacity hover:opacity-90"
|
||||
style="background:#E3162C; color:#fff;"
|
||||
>
|
||||
Satispay @brutsalvadi
|
||||
</a>
|
||||
</div>
|
||||
<div class="mb-8">
|
||||
<img
|
||||
src="/satispay-qr.jpg"
|
||||
alt="Satispay QR code — @brutsalvadi"
|
||||
class="w-36 h-36 rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-8 text-sm text-zinc-400 leading-relaxed">
|
||||
|
||||
<!-- Community stats (shown only in multi-user mode) -->
|
||||
<section id="stats-section" style="display:none">
|
||||
<h2 class="text-base font-semibold text-white mb-3">Community</h2>
|
||||
<p id="stats-summary" class="text-zinc-500 text-xs mb-4"></p>
|
||||
<div id="stats-tree" class="text-sm"></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">What is this?</h2>
|
||||
<p>
|
||||
BincioActivity is a free, open-source platform for tracking your outdoor activities —
|
||||
cycling, running, hiking, and more. It is designed to be self-hosted: you (or someone
|
||||
you trust) run the server, and your data stays under your control.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
Activities are stored in an open JSON format called BAS (BincioActivity Schema),
|
||||
which is designed to be readable and portable. The platform has no hidden analytics,
|
||||
no advertising, and no third-party data sharing.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Joining & invitations</h2>
|
||||
<p>
|
||||
This instance is invite-only. To join, you need an invite link from an existing
|
||||
member — each link is single-use and tied to a unique code.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
Once you have an account, you can generate up to <strong class="text-zinc-300">3 invite links</strong> to
|
||||
share with people you trust. You can manage your invites from the <a id="invites-link" href="invites/" class="text-blue-400 hover:text-blue-300 transition-colors">invites page</a>
|
||||
(requires login).
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Your data on this server</h2>
|
||||
<p>
|
||||
When you upload a FIT, GPX, or TCX file, the server converts it to BAS format.
|
||||
By default the original source file is also kept in your account's
|
||||
<code class="text-zinc-300 bg-zinc-800 px-1 rounded">originals/</code> folder.
|
||||
You can opt out of this at upload time by unchecking <em>"Keep original file on server"</em>.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
Keeping originals is recommended during these early stages of the project: if the
|
||||
processing pipeline improves (better elevation smoothing, speed calculation, lap
|
||||
detection, etc.) you can re-import your files to take advantage of the changes.
|
||||
If you chose not to keep originals, you would need to upload the files again manually.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
When syncing from Strava, the raw activity data fetched from the Strava API can
|
||||
similarly be stored locally. This is controlled by an instance-wide setting
|
||||
configured by the server operator.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Early-stage software</h2>
|
||||
<p>
|
||||
BincioActivity is under active development. The data format, processing pipeline,
|
||||
and server API may change between versions. Breaking changes are possible, especially
|
||||
at this stage. When they occur, re-importing your original files is the safest way
|
||||
to bring your data up to date.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
There is no guarantee of uptime, data integrity, or forward compatibility for
|
||||
any particular version. Use this software at your own risk, and keep your own
|
||||
backups of important data.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="border border-zinc-800 rounded-xl p-4 bg-zinc-900/50">
|
||||
<h2 class="text-base font-semibold text-white mb-2">Disclaimer</h2>
|
||||
<p>
|
||||
BincioActivity is provided <strong class="text-zinc-300">"as is"</strong>, without
|
||||
warranty of any kind. The authors and server operators accept no responsibility for:
|
||||
</p>
|
||||
<ul class="list-disc list-inside mt-2 space-y-1">
|
||||
<li>Loss, corruption, or unauthorised access to your activity data</li>
|
||||
<li>Data exposed through misconfiguration of the server or infrastructure</li>
|
||||
<li>Inaccuracies in computed statistics (distance, elevation, heart rate, etc.)</li>
|
||||
<li>Any consequences of acting on information displayed by this application</li>
|
||||
</ul>
|
||||
<p class="mt-3">
|
||||
You are responsible for securing your account with a strong password, reviewing
|
||||
what data you share, and making your own backups. GPS and health data can be
|
||||
sensitive — think carefully about what you upload and who can see it.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Open source</h2>
|
||||
<p>
|
||||
BincioActivity is open-source software. You are free to inspect the code,
|
||||
self-host your own instance, and contribute improvements.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</Base>
|
||||
|
||||
<script define:vars={{ labels }}>
|
||||
(async () => {
|
||||
try {
|
||||
const me = await fetch('/api/me', { credentials: 'include' });
|
||||
if (!me.ok) return; // not logged in — hide community section
|
||||
} catch { return; }
|
||||
let data;
|
||||
try {
|
||||
const r = await fetch('/api/stats');
|
||||
if (!r.ok) return; // single-user mode — no stats endpoint
|
||||
data = await r.json();
|
||||
} catch { return; }
|
||||
|
||||
// Fix invites link to use absolute base URL
|
||||
const invLink = document.getElementById('invites-link');
|
||||
if (invLink) invLink.href = '/invites/';
|
||||
|
||||
if (!data.user_count) return;
|
||||
|
||||
const section = document.getElementById('stats-section');
|
||||
const summary = document.getElementById('stats-summary');
|
||||
const treeEl = document.getElementById('stats-tree');
|
||||
|
||||
const n = data.user_count;
|
||||
summary.textContent = `${n} ${n === 1 ? labels.members : labels.members_pl}`;
|
||||
section.style.display = '';
|
||||
|
||||
// Build adjacency map: handle → [children]
|
||||
const byHandle = {};
|
||||
for (const m of data.members) byHandle[m.handle] = m;
|
||||
const children = {};
|
||||
const roots = [];
|
||||
for (const m of data.members) {
|
||||
if (m.invited_by && byHandle[m.invited_by]) {
|
||||
(children[m.invited_by] ??= []).push(m.handle);
|
||||
} else {
|
||||
roots.push(m.handle);
|
||||
}
|
||||
}
|
||||
|
||||
function formatDuration(days) {
|
||||
if (days < 1) return `< 1 ${labels.day}`;
|
||||
if (days === 1) return `1 ${labels.day}`;
|
||||
if (days < 30) return `${days} ${labels.days}`;
|
||||
const months = Math.floor(days / 30);
|
||||
return months === 1 ? `1 mo` : `${months} mo`;
|
||||
}
|
||||
|
||||
function renderNode(handle, depth) {
|
||||
const m = byHandle[handle];
|
||||
const indent = depth * 20;
|
||||
const isRoot = !m.invited_by;
|
||||
const sub = isRoot
|
||||
? labels.founder
|
||||
: `${labels.invited_by} @${m.invited_by}`;
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.className = 'flex items-baseline gap-2 py-1.5 border-b border-zinc-800/50';
|
||||
row.style.paddingLeft = `${indent}px`;
|
||||
if (depth > 0) {
|
||||
const connector = document.createElement('span');
|
||||
connector.className = 'text-zinc-700 shrink-0';
|
||||
connector.textContent = '└';
|
||||
row.appendChild(connector);
|
||||
}
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.className = 'text-white font-medium';
|
||||
name.textContent = m.display_name || `@${handle}`;
|
||||
row.appendChild(name);
|
||||
|
||||
const handle_el = document.createElement('span');
|
||||
handle_el.className = 'text-zinc-600 text-xs';
|
||||
handle_el.textContent = `@${handle}`;
|
||||
row.appendChild(handle_el);
|
||||
|
||||
const spacer = document.createElement('span');
|
||||
spacer.className = 'flex-1';
|
||||
row.appendChild(spacer);
|
||||
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'text-zinc-600 text-xs text-right shrink-0';
|
||||
meta.innerHTML = `${formatDuration(m.member_for_days)}<br><span class="text-zinc-700">${sub}</span>`;
|
||||
row.appendChild(meta);
|
||||
|
||||
treeEl.appendChild(row);
|
||||
|
||||
for (const child of (children[handle] ?? [])) {
|
||||
renderNode(child, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
for (const root of roots) renderNode(root, 0);
|
||||
})();
|
||||
</script>
|
||||
<meta http-equiv="refresh" content={`0;url=${target}`} />
|
||||
<script define:vars={{ target }}>window.location.replace(target);</script>
|
||||
|
||||
@@ -3,7 +3,7 @@ import Base from '../../layouts/Base.astro';
|
||||
const authUrl = import.meta.env.PUBLIC_AUTH_URL ?? '';
|
||||
---
|
||||
<Base title="Admin — BincioActivity">
|
||||
<div class="max-w-3xl mx-auto px-4 py-10">
|
||||
<div class="max-w-3xl mx-auto px-4 py-10" data-auth-url={authUrl}>
|
||||
<h1 class="text-2xl font-bold text-white mb-8">Admin</h1>
|
||||
|
||||
<!-- Disk overview -->
|
||||
@@ -113,7 +113,8 @@ const authUrl = import.meta.env.PUBLIC_AUTH_URL ?? '';
|
||||
</div>
|
||||
</Base>
|
||||
|
||||
<script define:vars={{ authUrl }}>
|
||||
<script>
|
||||
const authUrl = (document.querySelector<HTMLElement>('.max-w-3xl[data-auth-url]')?.dataset.authUrl) ?? '';
|
||||
const overviewEl = document.getElementById('disk-overview')!;
|
||||
const tbodyEl = document.getElementById('user-list')!;
|
||||
const dialog = document.getElementById('confirm-dialog') as HTMLDialogElement;
|
||||
@@ -407,10 +408,26 @@ const authUrl = import.meta.env.PUBLIC_AUTH_URL ?? '';
|
||||
const resetUrl = authUrl
|
||||
? `${authUrl}/reset-password/?code=${d.code}`
|
||||
: `/reset-password/?code=${d.code}`;
|
||||
btn.textContent = '🔗 Copy reset link';
|
||||
btn.title = resetUrl;
|
||||
btn.classList.add('text-yellow-300');
|
||||
btn.addEventListener('click', () => navigator.clipboard.writeText(resetUrl), { once: true });
|
||||
// Show the URL inline so the admin can always see and copy it
|
||||
const cell = btn.closest('td')!;
|
||||
btn.remove();
|
||||
cell.innerHTML = `
|
||||
<div class="flex flex-col gap-1">
|
||||
<input readonly value="${resetUrl}"
|
||||
class="w-full px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-yellow-300 text-xs font-mono focus:outline-none focus:border-zinc-500 cursor-text"
|
||||
onclick="this.select()" />
|
||||
<button class="copy-url-btn text-xs px-2 py-1 rounded bg-zinc-700 hover:bg-zinc-600 text-zinc-300 transition-colors">Copy</button>
|
||||
</div>`;
|
||||
const input = cell.querySelector<HTMLInputElement>('input')!;
|
||||
const copyBtn = cell.querySelector<HTMLButtonElement>('.copy-url-btn')!;
|
||||
input.select();
|
||||
navigator.clipboard.writeText(resetUrl).catch(() => {});
|
||||
copyBtn.addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(resetUrl).catch(() => {});
|
||||
input.select();
|
||||
copyBtn.textContent = 'Copied!';
|
||||
setTimeout(() => { copyBtn.textContent = 'Copy'; }, 2000);
|
||||
});
|
||||
} else {
|
||||
btn.textContent = 'Error';
|
||||
btn.classList.add('text-red-400');
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
---
|
||||
import Base from '../../layouts/Base.astro';
|
||||
import IdeasPage from '../../components/IdeasPage.svelte';
|
||||
const target = (import.meta.env.BASE_URL ?? '/') + 'support/#ideas';
|
||||
---
|
||||
<Base title="Ideas — BincioActivity">
|
||||
<IdeasPage client:only="svelte" />
|
||||
</Base>
|
||||
<meta http-equiv="refresh" content={`0;url=${target}`} />
|
||||
<script define:vars={{ target }}>window.location.replace(target);</script>
|
||||
|
||||
@@ -51,6 +51,25 @@ import Base from '../../layouts/Base.astro';
|
||||
<p id="display-name-status" class="text-xs mt-2 hidden"></p>
|
||||
</section>
|
||||
|
||||
<!-- Email card -->
|
||||
<section class="mb-6 rounded-xl bg-zinc-900 border border-zinc-800 p-5">
|
||||
<h2 class="text-sm font-semibold text-zinc-400 uppercase tracking-wider mb-1">Email</h2>
|
||||
<p class="text-xs text-zinc-500 mb-4">Used to receive a reset link when you forget your password.</p>
|
||||
<form id="email-form" class="flex gap-2 items-end">
|
||||
<div class="flex-1">
|
||||
<label class="block text-xs text-zinc-500 mb-1" for="email-input">Email address</label>
|
||||
<input id="email-input" type="email" autocomplete="email"
|
||||
class="w-full px-3 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent] text-sm"
|
||||
placeholder="you@example.com" />
|
||||
</div>
|
||||
<button type="submit"
|
||||
class="px-4 py-2 rounded-lg text-sm bg-zinc-700 hover:bg-zinc-600 text-white transition-colors shrink-0">
|
||||
Save
|
||||
</button>
|
||||
</form>
|
||||
<p id="email-status" class="text-xs mt-2 hidden"></p>
|
||||
</section>
|
||||
|
||||
<!-- Password card -->
|
||||
<section class="mb-6 rounded-xl bg-zinc-900 border border-zinc-800 p-5">
|
||||
<h2 class="text-sm font-semibold text-zinc-400 uppercase tracking-wider mb-4">Password</h2>
|
||||
@@ -602,10 +621,48 @@ import Base from '../../layouts/Base.astro';
|
||||
}
|
||||
});
|
||||
|
||||
// ── Email ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
const emailForm = document.getElementById('email-form') as HTMLFormElement;
|
||||
const emailInput = document.getElementById('email-input') as HTMLInputElement;
|
||||
const emailStatus = document.getElementById('email-status') as HTMLElement;
|
||||
|
||||
async function loadEmail() {
|
||||
const authUrl: string = (window as any).__bincioAuthUrl ?? '';
|
||||
if (!authUrl) return; // single-user / no bincio-auth
|
||||
try {
|
||||
const r = await fetch(`${authUrl}/api/me/email`, { credentials: 'include' });
|
||||
if (r.ok) {
|
||||
const { email } = await r.json();
|
||||
if (email) emailInput.value = email;
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
emailForm.addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
const authUrl: string = (window as any).__bincioAuthUrl ?? '';
|
||||
if (!authUrl) { setStatus(emailStatus, 'Not available on this instance.', false); return; }
|
||||
const email = emailInput.value.trim();
|
||||
try {
|
||||
const r = await fetch(`${authUrl}/api/me/email`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
const d = await r.json().catch(() => ({}));
|
||||
setStatus(emailStatus, r.ok ? 'Saved.' : (d.detail ?? 'Failed.'), r.ok);
|
||||
} catch {
|
||||
setStatus(emailStatus, 'Could not reach server.', false);
|
||||
}
|
||||
});
|
||||
|
||||
// ── Init ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
loadMe();
|
||||
loadStorage();
|
||||
loadEmail();
|
||||
loadNavPrefs();
|
||||
loadActivityDefaults();
|
||||
loadStravaCreds();
|
||||
|
||||
@@ -0,0 +1,646 @@
|
||||
---
|
||||
import Base from '../../layouts/Base.astro';
|
||||
import IdeasPage from '../../components/IdeasPage.svelte';
|
||||
const baseUrl = import.meta.env.BASE_URL ?? '/';
|
||||
---
|
||||
<Base title="Support — BincioActivity">
|
||||
<div class="max-w-2xl mx-auto">
|
||||
<h1 class="text-2xl font-bold text-white mb-1">Support</h1>
|
||||
<p class="text-sm text-zinc-500 mb-5">Open-source, self-hosted activity tracking</p>
|
||||
|
||||
<!-- Tab bar -->
|
||||
<div class="flex gap-1 border-b border-zinc-800 mb-6 overflow-x-auto">
|
||||
<button data-tab="donate" class="tab-btn px-4 py-2 text-sm font-medium rounded-t transition-colors shrink-0">Donate</button>
|
||||
<button data-tab="ideas" class="tab-btn px-4 py-2 text-sm font-medium rounded-t transition-colors shrink-0">Ideas</button>
|
||||
<button data-tab="feedback" class="tab-btn px-4 py-2 text-sm font-medium rounded-t transition-colors shrink-0">Feedback</button>
|
||||
<button data-tab="community" class="tab-btn px-4 py-2 text-sm font-medium rounded-t transition-colors shrink-0">Community</button>
|
||||
<button data-tab="about" class="tab-btn px-4 py-2 text-sm font-medium rounded-t transition-colors shrink-0">About</button>
|
||||
</div>
|
||||
|
||||
<!-- ── DONATE ─────────────────────────────────────────────────────── -->
|
||||
<div id="tab-donate" class="tab-panel">
|
||||
<div class="flex flex-wrap gap-2 mb-4">
|
||||
<a href="https://ko-fi.com/brutsalvadi" target="_blank" rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity"
|
||||
style="background:#FF5E5B; color:#fff;">
|
||||
☕ Support on Ko-fi
|
||||
</a>
|
||||
<div class="relative">
|
||||
<a href="https://web.satispay.com/download/qrcode/S6Y-CON--BE9BD345-4499-4C1D-9AC3-D62FC5FF0AD4"
|
||||
target="_blank" rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity"
|
||||
style="background:#E3162C; color:#fff;">
|
||||
Satispay @brutsalvadi
|
||||
</a>
|
||||
<span class="absolute -top-2 -right-2 px-1.5 py-0.5 rounded-full text-[10px] font-semibold bg-green-500 text-white leading-none">
|
||||
preferred
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-8">
|
||||
<img src="/satispay-qr.jpg" alt="Satispay QR code — @brutsalvadi" class="w-36 h-36 rounded-xl" />
|
||||
</div>
|
||||
|
||||
<!-- Budget section -->
|
||||
<div class="border-t border-zinc-800 pt-6">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h2 class="text-base font-semibold text-white">Running costs</h2>
|
||||
<p class="text-xs text-zinc-500 mt-0.5">Transparent breakdown of donations and expenses</p>
|
||||
</div>
|
||||
<div id="budget-admin-controls" class="hidden flex gap-2">
|
||||
<button id="budget-set-goal-btn"
|
||||
class="px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-300 hover:text-white text-xs font-medium transition-colors border border-zinc-700">
|
||||
Set monthly goal
|
||||
</button>
|
||||
<button id="budget-add-btn"
|
||||
class="px-3 py-1.5 rounded-lg bg-[--accent] hover:opacity-90 text-white text-xs font-medium transition-opacity">
|
||||
+ Add entry
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Set-goal form (admin, hidden by default) -->
|
||||
<form id="budget-goal-form" class="hidden mb-4 p-3 rounded-xl bg-zinc-900 border border-zinc-800 text-sm">
|
||||
<label class="block text-zinc-400 mb-1 text-xs">Monthly goal (€)</label>
|
||||
<div class="flex gap-2">
|
||||
<input id="budget-goal-input" type="number" min="0" step="0.01" placeholder="e.g. 20"
|
||||
class="flex-1 px-3 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-[--accent]" />
|
||||
<button type="submit" class="px-4 py-1.5 rounded-lg bg-[--accent] hover:opacity-90 text-white text-sm font-medium transition-opacity">Save</button>
|
||||
<button type="button" id="budget-goal-cancel" class="px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-400 text-sm transition-colors">Cancel</button>
|
||||
</div>
|
||||
<p id="budget-goal-err" class="text-red-400 text-xs mt-1 hidden"></p>
|
||||
</form>
|
||||
|
||||
<!-- Add-entry form (admin, hidden by default) -->
|
||||
<form id="budget-add-form" class="hidden mb-4 p-3 rounded-xl bg-zinc-900 border border-zinc-800 text-sm space-y-2">
|
||||
<div class="flex gap-2">
|
||||
<button type="button" data-type="donation" class="entry-type-btn flex-1 py-1.5 rounded-lg border text-xs font-medium transition-colors">💚 Donation</button>
|
||||
<button type="button" data-type="expense" class="entry-type-btn flex-1 py-1.5 rounded-lg border text-xs font-medium transition-colors">🔴 Expense</button>
|
||||
</div>
|
||||
<input id="entry-label" type="text" placeholder="Label (e.g. VPS hosting)"
|
||||
class="w-full px-3 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-[--accent]" />
|
||||
<div class="flex gap-2">
|
||||
<div class="flex-1 relative">
|
||||
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500 text-sm">€</span>
|
||||
<input id="entry-amount" type="number" min="0" step="0.01" placeholder="0.00"
|
||||
class="w-full pl-7 pr-3 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-[--accent]" />
|
||||
</div>
|
||||
<input id="entry-month" type="month"
|
||||
class="flex-1 px-3 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-[--accent] [color-scheme:dark]" />
|
||||
</div>
|
||||
<input id="entry-note" type="text" placeholder="Note (optional)"
|
||||
class="w-full px-3 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-sm focus:outline-none focus:border-[--accent]" />
|
||||
<label class="flex items-center gap-2 text-xs text-zinc-400 cursor-pointer select-none">
|
||||
<input id="entry-recurring" type="checkbox" class="accent-[--accent] w-3.5 h-3.5" />
|
||||
Repeat every month
|
||||
</label>
|
||||
<p id="budget-add-err" class="text-red-400 text-xs hidden"></p>
|
||||
<div class="flex gap-2 pt-1">
|
||||
<button type="submit" class="px-4 py-1.5 rounded-lg bg-[--accent] hover:opacity-90 text-white text-sm font-medium transition-opacity">Add</button>
|
||||
<button type="button" id="budget-add-cancel" class="px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-400 text-sm transition-colors">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div id="budget-list">
|
||||
<p class="text-zinc-500 text-sm text-center py-6">Loading…</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── IDEAS ────────────────────────────────────────────────────────── -->
|
||||
<div id="tab-ideas" class="tab-panel" style="display:none">
|
||||
<IdeasPage client:only="svelte" />
|
||||
</div>
|
||||
|
||||
<!-- ── ABOUT ──────────────────────────────────────────────────────── -->
|
||||
<div id="tab-about" class="tab-panel" style="display:none">
|
||||
<div class="flex justify-end gap-3 text-xs text-zinc-500 mb-5">
|
||||
<span class="text-zinc-300 font-medium">EN</span>
|
||||
<a href={`${baseUrl}about/it/`} class="hover:text-white transition-colors">IT</a>
|
||||
<a href={`${baseUrl}about/es/`} class="hover:text-white transition-colors">ES</a>
|
||||
<a href={`${baseUrl}about/ca/`} class="hover:text-white transition-colors">CA</a>
|
||||
</div>
|
||||
<div class="space-y-8 text-sm text-zinc-400 leading-relaxed">
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">What is this?</h2>
|
||||
<p>
|
||||
BincioActivity is a free, open-source platform for tracking your outdoor activities —
|
||||
cycling, running, hiking, and more. It is designed to be self-hosted: you (or someone
|
||||
you trust) run the server, and your data stays under your control.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
Activities are stored in an open JSON format called BAS (BincioActivity Schema),
|
||||
which is designed to be readable and portable. The platform has no hidden analytics,
|
||||
no advertising, and no third-party data sharing.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Joining & invitations</h2>
|
||||
<p>
|
||||
This instance is invite-only. To join, you need an invite link from an existing
|
||||
member — each link is single-use and tied to a unique code.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
Once you have an account, you can generate up to <strong class="text-zinc-300">3 invite links</strong> to
|
||||
share with people you trust. You can manage your invites from the
|
||||
<a href="/invites/" class="text-blue-400 hover:text-blue-300 transition-colors">invites page</a>.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Your data on this server</h2>
|
||||
<p>
|
||||
When you upload a FIT, GPX, or TCX file, the server converts it to BAS format.
|
||||
By default the original source file is also kept in your account's
|
||||
<code class="text-zinc-300 bg-zinc-800 px-1 rounded">originals/</code> folder.
|
||||
You can opt out of this at upload time by unchecking <em>"Keep original file on server"</em>.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
Keeping originals is recommended during these early stages of the project: if the
|
||||
processing pipeline improves (better elevation smoothing, speed calculation, lap
|
||||
detection, etc.) you can re-import your files to take advantage of the changes.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Early-stage software</h2>
|
||||
<p>
|
||||
BincioActivity is under active development. The data format, processing pipeline,
|
||||
and server API may change between versions. Breaking changes are possible, especially
|
||||
at this stage. When they occur, re-importing your original files is the safest way
|
||||
to bring your data up to date.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
There is no guarantee of uptime, data integrity, or forward compatibility for
|
||||
any particular version. Use this software at your own risk, and keep your own
|
||||
backups of important data.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="border border-zinc-800 rounded-xl p-4 bg-zinc-900/50">
|
||||
<h2 class="text-base font-semibold text-white mb-2">Disclaimer</h2>
|
||||
<p>
|
||||
BincioActivity is provided <strong class="text-zinc-300">"as is"</strong>, without
|
||||
warranty of any kind. The authors and server operators accept no responsibility for:
|
||||
</p>
|
||||
<ul class="list-disc list-inside mt-2 space-y-1">
|
||||
<li>Loss, corruption, or unauthorised access to your activity data</li>
|
||||
<li>Data exposed through misconfiguration of the server or infrastructure</li>
|
||||
<li>Inaccuracies in computed statistics (distance, elevation, heart rate, etc.)</li>
|
||||
<li>Any consequences of acting on information displayed by this application</li>
|
||||
</ul>
|
||||
<p class="mt-3">
|
||||
You are responsible for securing your account with a strong password, reviewing
|
||||
what data you share, and making your own backups. GPS and health data can be
|
||||
sensitive — think carefully about what you upload and who can see it.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="text-base font-semibold text-white mb-2">Open source</h2>
|
||||
<p>
|
||||
BincioActivity is open-source software. You are free to inspect the code,
|
||||
self-host your own instance, and contribute improvements.
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── COMMUNITY ──────────────────────────────────────────────────── -->
|
||||
<div id="tab-community" class="tab-panel" style="display:none">
|
||||
<p id="community-summary" class="text-zinc-500 text-xs mb-4"></p>
|
||||
<div id="community-tree" class="text-sm"></div>
|
||||
<p id="community-empty" class="text-zinc-500 text-sm text-center py-6" style="display:none">Community stats not available.</p>
|
||||
</div>
|
||||
|
||||
<!-- ── FEEDBACK ───────────────────────────────────────────────────── -->
|
||||
<div id="tab-feedback" class="tab-panel" style="display:none">
|
||||
<h2 class="text-base font-semibold text-white mb-1">Send feedback</h2>
|
||||
<p class="text-sm text-zinc-500 mb-5">Report a bug, suggest a feature, or share anything useful.</p>
|
||||
|
||||
<form id="feedback-form" class="space-y-4">
|
||||
<textarea id="fb-text" rows="6" placeholder="What's on your mind?"
|
||||
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 text-sm focus:outline-none focus:border-[--accent] resize-none"></textarea>
|
||||
|
||||
<div>
|
||||
<p class="text-xs text-zinc-500 mb-2">Attach up to 3 screenshots (max 2 MB each)</p>
|
||||
<div id="fb-drop"
|
||||
class="border-2 border-dashed border-zinc-700 rounded-lg p-5 text-center text-zinc-500 text-sm cursor-pointer hover:border-zinc-500 hover:text-zinc-300 transition-colors">
|
||||
<span>Drop images or click to browse</span>
|
||||
<input id="fb-input" type="file" accept="image/*" multiple class="hidden" />
|
||||
</div>
|
||||
<div id="fb-previews" class="flex gap-2 flex-wrap mt-2"></div>
|
||||
</div>
|
||||
|
||||
<p id="fb-error" class="text-red-400 text-sm hidden"></p>
|
||||
<button type="submit"
|
||||
class="w-full py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white font-medium text-sm transition-opacity">
|
||||
Send feedback
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div id="fb-success" class="hidden text-center mt-12">
|
||||
<p class="text-2xl mb-2">Thanks!</p>
|
||||
<p class="text-zinc-400 text-sm">Your feedback has been received.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</Base>
|
||||
|
||||
<script>
|
||||
// ── Tabs ──────────────────────────────────────────────────────────────────────
|
||||
const TABS = ['donate', 'ideas', 'feedback', 'community', 'about'] as const;
|
||||
type TabName = typeof TABS[number];
|
||||
|
||||
function showTab(name: TabName) {
|
||||
TABS.forEach(t => {
|
||||
const panel = document.getElementById(`tab-${t}`)!;
|
||||
const btn = document.querySelector<HTMLElement>(`.tab-btn[data-tab="${t}"]`)!;
|
||||
const active = t === name;
|
||||
panel.style.display = active ? '' : 'none';
|
||||
btn.classList.toggle('text-white', active);
|
||||
btn.classList.toggle('border-b-2', active);
|
||||
btn.classList.toggle('border-[--accent]', active);
|
||||
btn.classList.toggle('-mb-px', active);
|
||||
btn.classList.toggle('text-zinc-400', !active);
|
||||
});
|
||||
if (history.replaceState) history.replaceState(null, '', '#' + name);
|
||||
}
|
||||
|
||||
const hash = location.hash.slice(1) as TabName;
|
||||
showTab(TABS.includes(hash) ? hash : 'donate');
|
||||
document.querySelectorAll<HTMLElement>('.tab-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => showTab(btn.dataset.tab as TabName));
|
||||
});
|
||||
|
||||
// ── Community tree ────────────────────────────────────────────────────────────
|
||||
let communityLoaded = false;
|
||||
|
||||
async function loadCommunity() {
|
||||
const summaryEl = document.getElementById('community-summary')!;
|
||||
const treeEl = document.getElementById('community-tree')!;
|
||||
const emptyEl = document.getElementById('community-empty')!;
|
||||
let data: any;
|
||||
try {
|
||||
const r = await fetch('/api/stats');
|
||||
if (!r.ok) { emptyEl.style.display = ''; return; }
|
||||
data = await r.json();
|
||||
} catch { emptyEl.style.display = ''; return; }
|
||||
if (!data.user_count) { emptyEl.style.display = ''; return; }
|
||||
|
||||
const n = data.user_count;
|
||||
summaryEl.textContent = `${n} ${n === 1 ? 'member' : 'members'}`;
|
||||
|
||||
const byHandle: Record<string, any> = {};
|
||||
for (const m of data.members) byHandle[m.handle] = m;
|
||||
const children: Record<string, string[]> = {};
|
||||
const roots: string[] = [];
|
||||
for (const m of data.members) {
|
||||
if (m.invited_by && byHandle[m.invited_by]) {
|
||||
(children[m.invited_by] ??= []).push(m.handle);
|
||||
} else {
|
||||
roots.push(m.handle);
|
||||
}
|
||||
}
|
||||
|
||||
function formatDays(days: number) {
|
||||
if (days < 1) return '< 1 day';
|
||||
if (days < 30) return `${days} ${days === 1 ? 'day' : 'days'}`;
|
||||
const mo = Math.floor(days / 30);
|
||||
return mo === 1 ? '1 mo' : `${mo} mo`;
|
||||
}
|
||||
|
||||
function renderNode(handle: string, depth: number) {
|
||||
const m = byHandle[handle];
|
||||
const row = document.createElement('div');
|
||||
row.className = 'flex items-baseline gap-2 py-1.5 border-b border-zinc-800/50';
|
||||
row.style.paddingLeft = `${depth * 20}px`;
|
||||
if (depth > 0) {
|
||||
const c = document.createElement('span');
|
||||
c.className = 'text-zinc-700 shrink-0';
|
||||
c.textContent = '└';
|
||||
row.appendChild(c);
|
||||
}
|
||||
const name = document.createElement('span');
|
||||
name.className = 'text-white font-medium';
|
||||
name.textContent = m.display_name || `@${handle}`;
|
||||
row.appendChild(name);
|
||||
const hEl = document.createElement('span');
|
||||
hEl.className = 'text-zinc-600 text-xs';
|
||||
hEl.textContent = `@${handle}`;
|
||||
row.appendChild(hEl);
|
||||
const spacer = document.createElement('span');
|
||||
spacer.className = 'flex-1';
|
||||
row.appendChild(spacer);
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'text-zinc-600 text-xs text-right shrink-0';
|
||||
const sub = m.invited_by ? `invited by @${m.invited_by}` : 'founder';
|
||||
meta.innerHTML = `${formatDays(m.member_for_days)}<br><span class="text-zinc-700">${sub}</span>`;
|
||||
row.appendChild(meta);
|
||||
treeEl.appendChild(row);
|
||||
for (const child of (children[handle] ?? [])) renderNode(child, depth + 1);
|
||||
}
|
||||
for (const root of roots) renderNode(root, 0);
|
||||
}
|
||||
|
||||
document.querySelector<HTMLElement>('.tab-btn[data-tab="community"]')!.addEventListener('click', () => {
|
||||
if (!communityLoaded) { communityLoaded = true; loadCommunity(); }
|
||||
});
|
||||
if (location.hash.slice(1) === 'community') { communityLoaded = true; loadCommunity(); }
|
||||
|
||||
// ── Budget ────────────────────────────────────────────────────────────────────
|
||||
let budgetData: { monthly_target_eur: number | null; entries: any[] } | null = null;
|
||||
let isAdmin = false;
|
||||
let addEntryType: 'donation' | 'expense' = 'donation';
|
||||
const expandedMonths = new Set<string>();
|
||||
let budgetFirstRender = true;
|
||||
|
||||
async function loadBudget() {
|
||||
try {
|
||||
const [br, mr] = await Promise.all([
|
||||
fetch('/api/budget'),
|
||||
fetch('/api/me', { credentials: 'include' }),
|
||||
]);
|
||||
budgetData = br.ok ? await br.json() : { monthly_target_eur: null, entries: [] };
|
||||
if (mr.ok) { const me = await mr.json(); isAdmin = !!me.is_admin; }
|
||||
} catch {
|
||||
budgetData = { monthly_target_eur: null, entries: [] };
|
||||
}
|
||||
renderBudget();
|
||||
}
|
||||
|
||||
function fmtEur(n: number) {
|
||||
return `€${n.toFixed(2).replace('.00', '')}`;
|
||||
}
|
||||
|
||||
function monthLabel(ym: string) {
|
||||
const [y, m] = ym.split('-');
|
||||
return new Date(parseInt(y), parseInt(m) - 1, 1)
|
||||
.toLocaleString('default', { month: 'long', year: 'numeric' });
|
||||
}
|
||||
|
||||
function renderBudget() {
|
||||
const listEl = document.getElementById('budget-list')!;
|
||||
const adminCtrls = document.getElementById('budget-admin-controls')!;
|
||||
const goalInput = document.getElementById('budget-goal-input') as HTMLInputElement;
|
||||
|
||||
if (isAdmin) {
|
||||
adminCtrls.classList.remove('hidden');
|
||||
if (budgetData?.monthly_target_eur != null) goalInput.value = String(budgetData.monthly_target_eur);
|
||||
}
|
||||
|
||||
const entries = budgetData?.entries ?? [];
|
||||
if (entries.length === 0) {
|
||||
listEl.innerHTML = `<p class="text-zinc-500 text-sm text-center py-6">${isAdmin ? 'No entries yet. Add the first one above.' : 'No budget entries yet.'}</p>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const byMonth: Record<string, any[]> = {};
|
||||
for (const e of entries) (byMonth[e.month] ??= []).push(e);
|
||||
const months = Object.keys(byMonth).sort().reverse();
|
||||
|
||||
if (budgetFirstRender) { expandedMonths.add(months[0]); budgetFirstRender = false; }
|
||||
|
||||
listEl.innerHTML = '';
|
||||
|
||||
for (const ym of months) {
|
||||
const items = byMonth[ym];
|
||||
const donated = items.filter(e => e.type === 'donation').reduce((s, e) => s + e.amount_eur, 0);
|
||||
const spent = items.filter(e => e.type === 'expense' ).reduce((s, e) => s + e.amount_eur, 0);
|
||||
const balance = donated - spent;
|
||||
const target = budgetData?.monthly_target_eur;
|
||||
const pct = target ? Math.min(100, Math.round(donated / target * 100)) : null;
|
||||
const open = expandedMonths.has(ym);
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'mb-2 rounded-xl border border-zinc-800 overflow-hidden';
|
||||
|
||||
// ── Month header row ──────────────────────────────────────────────────
|
||||
const header = document.createElement('button');
|
||||
header.className = 'w-full flex items-center gap-2 px-3 py-2.5 bg-zinc-900 hover:bg-zinc-800/60 transition-colors text-sm';
|
||||
header.innerHTML = `
|
||||
<span class="font-medium text-white shrink-0">${monthLabel(ym)}</span>
|
||||
${pct !== null
|
||||
? `<div class="flex-1 mx-2 flex items-center gap-1.5"><div class="flex-1 h-1.5 rounded-full bg-zinc-800 overflow-hidden"><div class="h-full rounded-full" style="width:${pct}%;background:var(--accent)"></div></div><span class="text-xs text-zinc-500 shrink-0">${pct}%</span></div>`
|
||||
: `<span class="flex-1"></span>`}
|
||||
<span class="text-xs text-green-400"><span class="hidden sm:inline text-zinc-600 mr-0.5">donated</span>+${fmtEur(donated)}</span>
|
||||
<span class="text-xs text-zinc-700">/</span>
|
||||
<span class="text-xs text-red-400"><span class="hidden sm:inline text-zinc-600 mr-0.5">spent</span>−${fmtEur(spent)}</span>
|
||||
<span class="text-xs text-zinc-700">/</span>
|
||||
<span class="text-xs ${balance >= 0 ? 'text-zinc-300' : 'text-red-400'}"><span class="hidden sm:inline text-zinc-600 mr-0.5">balance</span>${balance >= 0 ? '+' : '−'}${fmtEur(Math.abs(balance))}</span>
|
||||
<span class="text-zinc-600 text-xs ml-1">${open ? '▲' : '▼'}</span>`;
|
||||
header.addEventListener('click', () => {
|
||||
if (expandedMonths.has(ym)) expandedMonths.delete(ym); else expandedMonths.add(ym);
|
||||
renderBudget();
|
||||
});
|
||||
wrapper.appendChild(header);
|
||||
|
||||
// ── Expanded detail ───────────────────────────────────────────────────
|
||||
if (open) {
|
||||
const detail = document.createElement('div');
|
||||
detail.className = 'border-t border-zinc-800';
|
||||
|
||||
const entriesDiv = document.createElement('div');
|
||||
entriesDiv.className = 'divide-y divide-zinc-800/60';
|
||||
let entriesHtml = '';
|
||||
for (const e of items) {
|
||||
const icon = e.type === 'donation' ? '💚' : '🔴';
|
||||
const sign = e.type === 'donation' ? '+' : '−';
|
||||
const color = e.type === 'donation' ? 'text-green-400' : 'text-red-400';
|
||||
const recurBadge = e.recurring
|
||||
? `<span class="text-zinc-500 text-xs shrink-0" title="Repeats every month">↻</span>`
|
||||
: e.recurring_from
|
||||
? `<span class="text-zinc-600 text-xs shrink-0" title="Auto-added (recurring)">↻</span>`
|
||||
: '';
|
||||
const adminBtns = isAdmin
|
||||
? `<button data-edit="${e.id}" class="edit-btn text-zinc-600 hover:text-zinc-300 text-xs px-1 transition-colors">✎</button>
|
||||
<button data-del="${e.id}" class="del-btn text-zinc-700 hover:text-red-400 text-xs px-1 transition-colors">✕</button>`
|
||||
: '';
|
||||
entriesHtml += `<div class="flex items-center gap-3 px-3 py-2 bg-zinc-900 text-sm" data-entry-id="${e.id}">
|
||||
<span class="text-base shrink-0">${icon}</span>
|
||||
<span class="flex-1 text-zinc-300 min-w-0">${e.label}${e.note ? `<span class="text-zinc-600 text-xs ml-2">${e.note}</span>` : ''}</span>
|
||||
${recurBadge}
|
||||
<span class="font-medium shrink-0 ${color}">${sign}${fmtEur(e.amount_eur)}</span>
|
||||
${adminBtns}
|
||||
</div>`;
|
||||
}
|
||||
entriesDiv.innerHTML = entriesHtml;
|
||||
detail.appendChild(entriesDiv);
|
||||
wrapper.appendChild(detail);
|
||||
|
||||
entriesDiv.querySelectorAll<HTMLElement>('.del-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
if (!confirm('Delete this entry?')) return;
|
||||
const r = await fetch(`/api/budget/entries/${btn.dataset.del}`, { method: 'DELETE', credentials: 'include' });
|
||||
if (r.ok) { budgetData!.entries = budgetData!.entries.filter(e => e.id !== btn.dataset.del); renderBudget(); }
|
||||
});
|
||||
});
|
||||
|
||||
entriesDiv.querySelectorAll<HTMLElement>('.edit-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const id = btn.dataset.edit!;
|
||||
const entry = budgetData!.entries.find(e => e.id === id);
|
||||
if (!entry) return;
|
||||
const row = entriesDiv.querySelector<HTMLElement>(`[data-entry-id="${id}"]`)!;
|
||||
row.innerHTML = `
|
||||
<form class="inline-edit-form flex flex-wrap gap-2 items-center w-full py-1" data-id="${id}">
|
||||
<select name="type" class="px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none">
|
||||
<option value="donation" ${entry.type==='donation'?'selected':''}>💚 Donation</option>
|
||||
<option value="expense" ${entry.type==='expense' ?'selected':''}>🔴 Expense</option>
|
||||
</select>
|
||||
<input name="label" value="${entry.label}" placeholder="Label"
|
||||
class="flex-1 min-w-24 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
|
||||
<input name="amount_eur" type="number" value="${entry.amount_eur}" step="0.01" min="0"
|
||||
class="w-20 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
|
||||
<input name="month" type="month" value="${entry.month}"
|
||||
class="px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none [color-scheme:dark]" />
|
||||
<input name="note" value="${entry.note ?? ''}" placeholder="Note"
|
||||
class="flex-1 min-w-24 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
|
||||
<label class="flex items-center gap-1 text-xs text-zinc-400 cursor-pointer">
|
||||
<input type="checkbox" name="recurring" ${entry.recurring?'checked':''} class="accent-[--accent] w-3 h-3" />↻
|
||||
</label>
|
||||
<button type="submit" class="px-3 py-1 rounded bg-[--accent] text-white text-xs hover:opacity-90">Save</button>
|
||||
<button type="button" class="cancel-edit px-2 py-1 rounded bg-zinc-800 text-zinc-400 text-xs hover:bg-zinc-700">✕</button>
|
||||
</form>`;
|
||||
row.querySelector<HTMLFormElement>('.inline-edit-form')!.addEventListener('submit', async ev => {
|
||||
ev.preventDefault();
|
||||
const fd = new FormData(ev.target as HTMLFormElement);
|
||||
const body = { type: fd.get('type'), label: fd.get('label'), amount_eur: parseFloat(fd.get('amount_eur') as string), month: fd.get('month'), note: fd.get('note'), recurring: fd.get('recurring') === 'on' };
|
||||
const r = await fetch(`/api/budget/entries/${id}`, { method: 'PATCH', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
if (r.ok) { const updated = await r.json(); const idx = budgetData!.entries.findIndex(e => e.id === id); if (idx !== -1) budgetData!.entries[idx] = updated; renderBudget(); }
|
||||
});
|
||||
row.querySelector('.cancel-edit')!.addEventListener('click', renderBudget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
listEl.appendChild(wrapper);
|
||||
}
|
||||
}
|
||||
|
||||
// Load budget on page load (donate is the default tab)
|
||||
loadBudget();
|
||||
|
||||
// Goal form
|
||||
const goalForm = document.getElementById('budget-goal-form') as HTMLFormElement;
|
||||
const goalBtn = document.getElementById('budget-set-goal-btn')!;
|
||||
const goalCancel = document.getElementById('budget-goal-cancel')!;
|
||||
const goalErr = document.getElementById('budget-goal-err')!;
|
||||
goalBtn.addEventListener('click', () => goalForm.classList.toggle('hidden'));
|
||||
goalCancel.addEventListener('click', () => goalForm.classList.add('hidden'));
|
||||
goalForm.addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
goalErr.classList.add('hidden');
|
||||
const v = parseFloat((document.getElementById('budget-goal-input') as HTMLInputElement).value);
|
||||
const r = await fetch('/api/budget/settings', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ monthly_target_eur: isNaN(v) ? null : v }) });
|
||||
if (r.ok) { if (budgetData) budgetData.monthly_target_eur = isNaN(v) ? null : v; goalForm.classList.add('hidden'); renderBudget(); }
|
||||
else { goalErr.textContent = 'Failed to save goal.'; goalErr.classList.remove('hidden'); }
|
||||
});
|
||||
|
||||
// Add-entry form
|
||||
const addForm = document.getElementById('budget-add-form') as HTMLFormElement;
|
||||
const addBtn = document.getElementById('budget-add-btn')!;
|
||||
const addCancel = document.getElementById('budget-add-cancel')!;
|
||||
const addErr = document.getElementById('budget-add-err')!;
|
||||
|
||||
const now = new Date();
|
||||
const defaultMonth = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;
|
||||
(document.getElementById('entry-month') as HTMLInputElement).value = defaultMonth;
|
||||
|
||||
addForm.querySelectorAll<HTMLButtonElement>('.entry-type-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
addEntryType = btn.dataset.type as 'donation' | 'expense';
|
||||
addForm.querySelectorAll<HTMLButtonElement>('.entry-type-btn').forEach(b => {
|
||||
const a = b.dataset.type === addEntryType;
|
||||
b.classList.toggle('border-[--accent]', a); b.classList.toggle('text-white', a); b.classList.toggle('bg-zinc-800', a);
|
||||
b.classList.toggle('border-zinc-700', !a); b.classList.toggle('text-zinc-400', !a);
|
||||
});
|
||||
});
|
||||
});
|
||||
(addForm.querySelector('.entry-type-btn[data-type="donation"]') as HTMLButtonElement).click();
|
||||
|
||||
addBtn.addEventListener('click', () => { addForm.classList.toggle('hidden'); addErr.classList.add('hidden'); });
|
||||
addCancel.addEventListener('click', () => addForm.classList.add('hidden'));
|
||||
|
||||
addForm.addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
addErr.classList.add('hidden');
|
||||
const label = (document.getElementById('entry-label') as HTMLInputElement).value.trim();
|
||||
const amount = parseFloat((document.getElementById('entry-amount') as HTMLInputElement).value);
|
||||
const month = (document.getElementById('entry-month') as HTMLInputElement).value;
|
||||
const note = (document.getElementById('entry-note') as HTMLInputElement).value.trim();
|
||||
if (!label) { addErr.textContent = 'Label is required.'; addErr.classList.remove('hidden'); return; }
|
||||
if (isNaN(amount)) { addErr.textContent = 'Amount is required.'; addErr.classList.remove('hidden'); return; }
|
||||
const recurring = (document.getElementById('entry-recurring') as HTMLInputElement).checked;
|
||||
const r = await fetch('/api/budget/entries', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: addEntryType, label, amount_eur: amount, month, note, recurring: recurring || undefined }) });
|
||||
if (r.ok) {
|
||||
budgetData!.entries.push(await r.json());
|
||||
addForm.classList.add('hidden'); addForm.reset();
|
||||
(document.getElementById('entry-month') as HTMLInputElement).value = defaultMonth;
|
||||
(document.getElementById('entry-recurring') as HTMLInputElement).checked = false;
|
||||
(addForm.querySelector('.entry-type-btn[data-type="donation"]') as HTMLButtonElement).click();
|
||||
renderBudget();
|
||||
} else {
|
||||
const d = await r.json().catch(() => ({}));
|
||||
addErr.textContent = d.detail ?? 'Failed to add entry.'; addErr.classList.remove('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
// ── Feedback ──────────────────────────────────────────────────────────────────
|
||||
const MAX_IMAGES = 3;
|
||||
const MAX_BYTES = 2 * 1024 * 1024;
|
||||
const fbForm = document.getElementById('feedback-form') as HTMLFormElement;
|
||||
const fbDrop = document.getElementById('fb-drop')!;
|
||||
const fbInput = document.getElementById('fb-input') as HTMLInputElement;
|
||||
const fbPreviews = document.getElementById('fb-previews')!;
|
||||
const fbErr = document.getElementById('fb-error')!;
|
||||
const fbSuccess = document.getElementById('fb-success')!;
|
||||
let fbFiles: File[] = [];
|
||||
|
||||
function fbShowErr(msg: string) { fbErr.textContent = msg; fbErr.classList.remove('hidden'); }
|
||||
function fbClearErr() { fbErr.classList.add('hidden'); }
|
||||
function fbRenderPreviews() {
|
||||
fbPreviews.innerHTML = '';
|
||||
fbFiles.forEach((f, i) => {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'relative';
|
||||
wrap.innerHTML = `<img src="${URL.createObjectURL(f)}" class="w-20 h-20 object-cover rounded-lg border border-zinc-700" />
|
||||
<button type="button" data-i="${i}" class="rm-btn absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-zinc-800 border border-zinc-600 text-zinc-300 hover:text-white text-xs flex items-center justify-center">×</button>`;
|
||||
fbPreviews.appendChild(wrap);
|
||||
});
|
||||
fbPreviews.querySelectorAll<HTMLElement>('.rm-btn').forEach(b => {
|
||||
b.addEventListener('click', () => { fbFiles.splice(parseInt(b.dataset.i!), 1); fbRenderPreviews(); fbClearErr(); });
|
||||
});
|
||||
}
|
||||
function fbAddFiles(files: FileList | File[]) {
|
||||
fbClearErr();
|
||||
for (const f of Array.from(files)) {
|
||||
if (fbFiles.length >= MAX_IMAGES) { fbShowErr(`Max ${MAX_IMAGES} images.`); break; }
|
||||
if (f.size > MAX_BYTES) { fbShowErr(`"${f.name}" exceeds 2 MB.`); continue; }
|
||||
fbFiles.push(f);
|
||||
}
|
||||
fbRenderPreviews(); fbInput.value = '';
|
||||
}
|
||||
fbDrop.addEventListener('click', () => fbInput.click());
|
||||
fbDrop.addEventListener('dragover', e => { e.preventDefault(); fbDrop.style.borderColor = 'var(--accent)'; });
|
||||
fbDrop.addEventListener('dragleave', () => { fbDrop.style.borderColor = ''; });
|
||||
fbDrop.addEventListener('drop', e => { e.preventDefault(); fbDrop.style.borderColor = ''; if (e.dataTransfer?.files.length) fbAddFiles(e.dataTransfer.files); });
|
||||
fbInput.addEventListener('change', () => { if (fbInput.files?.length) fbAddFiles(fbInput.files); });
|
||||
fbForm.addEventListener('submit', async e => {
|
||||
e.preventDefault(); fbClearErr();
|
||||
const text = (document.getElementById('fb-text') as HTMLTextAreaElement).value.trim();
|
||||
if (!text && fbFiles.length === 0) { fbShowErr('Please write something or attach an image.'); return; }
|
||||
const fd = new FormData(); fd.append('text', text);
|
||||
for (const f of fbFiles) fd.append('images', f);
|
||||
const btn = fbForm.querySelector('button[type=submit]') as HTMLButtonElement;
|
||||
btn.disabled = true; btn.textContent = 'Sending…';
|
||||
try {
|
||||
const r = await fetch('/api/feedback', { method: 'POST', credentials: 'include', body: fd });
|
||||
if (!r.ok) { const d = await r.json().catch(() => ({})); throw new Error(d.detail ?? `Error ${r.status}`); }
|
||||
fbForm.classList.add('hidden'); fbSuccess.classList.remove('hidden');
|
||||
} catch (err: any) { fbShowErr(err.message); btn.disabled = false; btn.textContent = 'Send feedback'; }
|
||||
});
|
||||
</script>
|
||||
@@ -59,13 +59,8 @@ class TestAdminUserOps:
|
||||
def test_delete_account_requires_admin(self, client: TestClient):
|
||||
assert client.delete("/api/admin/users/alice/account").status_code == 401
|
||||
|
||||
def test_admin_reset_password_code(self, admin_client: TestClient, tmp_data):
|
||||
from bincio.serve.db import create_user, open_db
|
||||
db = open_db(tmp_data)
|
||||
try:
|
||||
create_user(db, "target", "Target", "targetpass1")
|
||||
except Exception:
|
||||
pass
|
||||
def test_admin_reset_password_code_proxied(self, admin_client: TestClient):
|
||||
# This endpoint proxies to bincio-auth; without BINCIO_AUTH_API configured
|
||||
# in the test environment it returns 503.
|
||||
r = admin_client.post("/api/admin/users/target/reset-password-code")
|
||||
assert r.status_code == 200
|
||||
assert "code" in r.json()
|
||||
assert r.status_code == 503
|
||||
|
||||
+3
-3
@@ -154,10 +154,10 @@ def test_hysteresis_recalc_barometric(tmp_path):
|
||||
result = recalculate_elevation_hysteresis(tmp_path, "test-act")
|
||||
|
||||
assert result["altitude_source"] == "barometric"
|
||||
assert result["threshold_m"] == pytest.approx(1.0)
|
||||
assert result["threshold_m"] == pytest.approx(1.5)
|
||||
# Edge effect is ≤1% on a 30-min ramp
|
||||
assert result["elevation_gain_m"] == pytest.approx(1800.0, rel=0.02)
|
||||
assert result["elevation_loss_m"] == pytest.approx(0.0, abs=1.0)
|
||||
assert result["elevation_loss_m"] == pytest.approx(0.0, abs=1.5)
|
||||
|
||||
|
||||
def test_hysteresis_recalc_gps(tmp_path):
|
||||
@@ -166,7 +166,7 @@ def test_hysteresis_recalc_gps(tmp_path):
|
||||
|
||||
result = recalculate_elevation_hysteresis(tmp_path, "test-act")
|
||||
|
||||
assert result["threshold_m"] == pytest.approx(3.0)
|
||||
assert result["threshold_m"] == pytest.approx(2.0)
|
||||
assert result["elevation_gain_m"] == pytest.approx(1800.0, rel=0.02)
|
||||
|
||||
|
||||
|
||||
@@ -73,25 +73,25 @@ class TestHysteresisEndpoint:
|
||||
assert "elevation_loss_m" in body
|
||||
assert body["elevation_gain_m"] > 0
|
||||
assert body["altitude_source"] == "barometric"
|
||||
assert body["threshold_m"] == pytest.approx(1.0)
|
||||
assert body["threshold_m"] == pytest.approx(1.5)
|
||||
|
||||
def test_gps_source_uses_3m_threshold(self, tmp_path):
|
||||
def test_gps_source_uses_2m_threshold(self, tmp_path):
|
||||
elevations = [float(i) for i in range(1801)]
|
||||
_make_activity(tmp_path, self.AID, elevations, altitude_source="gps")
|
||||
|
||||
r = CLIENT.post(f"/api/activity/{self.AID}/recalculate-elevation/hysteresis")
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json()["threshold_m"] == pytest.approx(3.0)
|
||||
assert r.json()["threshold_m"] == pytest.approx(2.0)
|
||||
|
||||
def test_unknown_source_falls_back_to_gps_threshold(self, tmp_path):
|
||||
def test_unknown_source_uses_1_5m_threshold(self, tmp_path):
|
||||
elevations = [float(i) for i in range(1801)]
|
||||
_make_activity(tmp_path, self.AID, elevations, altitude_source="unknown")
|
||||
|
||||
r = CLIENT.post(f"/api/activity/{self.AID}/recalculate-elevation/hysteresis")
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json()["threshold_m"] == pytest.approx(3.0)
|
||||
assert r.json()["threshold_m"] == pytest.approx(1.5)
|
||||
|
||||
def test_uses_original_elevation_when_dem_backup_present(self, tmp_path):
|
||||
original = [float(i) for i in range(1801)] # real 1800 m climb
|
||||
|
||||
+25
-21
@@ -29,13 +29,14 @@ def _pt(offset_s: int, **kw) -> DataPoint:
|
||||
return DataPoint(timestamp=_ts(offset_s), **kw)
|
||||
|
||||
|
||||
def _activity(points: list[DataPoint], sport: str = "cycling") -> ParsedActivity:
|
||||
def _activity(points: list[DataPoint], sport: str = "cycling", altitude_source: str = "unknown") -> ParsedActivity:
|
||||
return ParsedActivity(
|
||||
points=points,
|
||||
sport=sport,
|
||||
started_at=_ts(0),
|
||||
source_file="test.fit",
|
||||
source_hash="sha256:abc",
|
||||
altitude_source=altitude_source,
|
||||
)
|
||||
|
||||
|
||||
@@ -110,12 +111,13 @@ def test_compute_moving_time_excludes_stops():
|
||||
|
||||
|
||||
def test_compute_elevation_gain():
|
||||
# Barometric source: no MA smoothing, so even 3 points produce correct gain.
|
||||
pts = [
|
||||
_pt(0, lat=48.0, lon=11.0, elevation_m=100.0),
|
||||
_pt(10, lat=48.001, lon=11.0, elevation_m=150.0),
|
||||
_pt(20, lat=48.002, lon=11.0, elevation_m=120.0),
|
||||
]
|
||||
m = compute(_activity(pts))
|
||||
m = compute(_activity(pts, altitude_source="barometric"))
|
||||
assert m.elevation_gain_m == 50.0
|
||||
assert m.elevation_loss_m == 30.0
|
||||
|
||||
@@ -134,8 +136,8 @@ def _ele_pts(elevations: list[float]) -> list[DataPoint]:
|
||||
|
||||
|
||||
def test_elevation_hysteresis_large_step_always_counted():
|
||||
# A single 50m step is way above any threshold — both sources should count it.
|
||||
pts = _ele_pts([100.0, 150.0])
|
||||
# A 50m step with 5 points per level so the GPS moving average doesn't flatten it.
|
||||
pts = _ele_pts([100.0] * 5 + [150.0] * 5)
|
||||
gain_baro, _ = _elevation(pts, "barometric")
|
||||
gain_gps, _ = _elevation(pts, "gps")
|
||||
assert gain_baro == 50.0
|
||||
@@ -143,26 +145,25 @@ def test_elevation_hysteresis_large_step_always_counted():
|
||||
|
||||
|
||||
def test_elevation_hysteresis_flat_gps_noise_suppressed():
|
||||
# Flat coastal route: 16m of GPS noise oscillating within ±8m.
|
||||
# All steps are sub-1m — hysteresis should return ~0 gain.
|
||||
import math
|
||||
# GPS noise within ±0.5m — peak-to-peak 1.0m, well below the 2.0m GPS threshold.
|
||||
n = 1000
|
||||
elevations = [100.0 + 3.0 * math.sin(i * 0.1) for i in range(n)]
|
||||
elevations = [100.0 + 0.5 * math.sin(i * 0.1) for i in range(n)]
|
||||
pts = _ele_pts(elevations)
|
||||
gain, loss = _elevation(pts, "gps")
|
||||
# With threshold=10m no oscillation within ±3m should ever commit.
|
||||
assert gain == 0.0
|
||||
assert loss == 0.0
|
||||
|
||||
|
||||
def test_elevation_hysteresis_barometric_threshold_lower():
|
||||
# Steps of exactly 7m — above barometric (5m) but below GPS (10m) threshold.
|
||||
elevations = [0.0, 7.0, 0.0, 7.0]
|
||||
# 1.7m steps at 100m baseline (avoids sensor-dropout suppression which
|
||||
# skips values near 0): above the 1.5m barometric threshold but, after GPS
|
||||
# MA smoothing, the effective diff stays below the 2.0m GPS threshold.
|
||||
elevations = [100.0, 101.7, 100.0, 101.7]
|
||||
pts = _ele_pts(elevations)
|
||||
gain_baro, _ = _elevation(pts, "barometric")
|
||||
gain_gps, _ = _elevation(pts, "gps")
|
||||
assert gain_baro == 14.0 # both 7m steps committed
|
||||
assert gain_gps == 0.0 # 7m < 10m threshold → suppressed
|
||||
assert gain_baro == pytest.approx(3.4) # both 1.7m steps committed
|
||||
assert gain_gps == 0.0 # MA + 2.0m threshold suppresses
|
||||
|
||||
|
||||
def test_elevation_hysteresis_real_climb_approximated():
|
||||
@@ -350,33 +351,36 @@ def test_best_efforts_no_targets_for_sport():
|
||||
# ── best climb ────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_best_climb_simple_ascent():
|
||||
# 0 → 100 m with no gaps
|
||||
ele = [float(i) for i in range(101)]
|
||||
# 0 → 100 m with no gaps; x is cumulative distance (m)
|
||||
ele = [(float(i), float(i)) for i in range(101)]
|
||||
result = _best_climb(ele)
|
||||
assert result == 100.0
|
||||
|
||||
|
||||
def test_best_climb_with_descent():
|
||||
# Up 50, down 20, up 80 → best contiguous window = 80
|
||||
ele = list(range(0, 51)) + list(range(50, 30, -1)) + list(range(30, 111))
|
||||
vals = list(range(0, 51)) + list(range(50, 30, -1)) + list(range(30, 111))
|
||||
ele = [(float(i), float(v)) for i, v in enumerate(vals)]
|
||||
result = _best_climb(ele)
|
||||
assert result is not None
|
||||
assert result >= 80.0
|
||||
|
||||
|
||||
def test_best_climb_none_gap_resets_window():
|
||||
# 50 m up, then a GPS gap, then 30 m up — windows don't bridge the gap
|
||||
ele: list = list(range(0, 51)) + [None] + list(range(0, 31))
|
||||
result = _best_climb(ele)
|
||||
# 50 m up, then a GPS gap (skipped), then 30 m up — windows don't bridge the gap.
|
||||
# None elevations are excluded when building dist_ele, so the climb restarts at 0.
|
||||
ele_up1 = [(float(i), float(i)) for i in range(51)]
|
||||
ele_up2 = [(float(51 + i), float(i)) for i in range(31)]
|
||||
result = _best_climb(ele_up1 + ele_up2)
|
||||
assert result == 50.0
|
||||
|
||||
|
||||
def test_best_climb_only_descent():
|
||||
ele = [100.0, 80.0, 60.0, 40.0]
|
||||
ele = [(float(i), v) for i, v in enumerate([100.0, 80.0, 60.0, 40.0])]
|
||||
result = _best_climb(ele)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_best_climb_too_few_samples():
|
||||
assert _best_climb([]) is None
|
||||
assert _best_climb([100.0]) is None
|
||||
assert _best_climb([(0.0, 100.0)]) is None
|
||||
|
||||
@@ -70,6 +70,7 @@ def _dummy_metrics(**overrides):
|
||||
avg_cadence_rpm=None, avg_power_w=None, np_power_w=None, max_power_w=None,
|
||||
bbox=None, start_latlng=None, end_latlng=None,
|
||||
mmp=None, best_efforts=None, best_climb_m=None,
|
||||
climbing_vam_mh=None, climbing_time_s=None,
|
||||
)
|
||||
defaults.update(overrides)
|
||||
return ComputedMetrics(**defaults)
|
||||
@@ -216,6 +217,8 @@ def test_build_summary_required_fields():
|
||||
mmp=None,
|
||||
best_efforts=None,
|
||||
best_climb_m=None,
|
||||
climbing_vam_mh=None,
|
||||
climbing_time_s=None,
|
||||
)
|
||||
summary = build_summary(act, metrics, "2024-06-01T073012Z-test-ride")
|
||||
# Required fields per schema
|
||||
|
||||
Reference in New Issue
Block a user